babylon.max.js 5.5 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720
  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 pointerdoubletap 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 Color4 object from the current Color3 and the given alpha
  1546. * @param alpha defines the alpha component on the new Color4 object (default is 1)
  1547. * @returns a new 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. if (x < this.x)
  3219. this.x = x;
  3220. if (y < this.y)
  3221. this.y = y;
  3222. if (z < this.z)
  3223. this.z = z;
  3224. return this;
  3225. };
  3226. /**
  3227. * Updates the current Vector3 with the maximal coordinate values between its and the given coordinates.
  3228. * @param x defines the x coordinate of the operand
  3229. * @param y defines the y coordinate of the operand
  3230. * @param z defines the z coordinate of the operand
  3231. * @returns the current updated Vector3
  3232. */
  3233. Vector3.prototype.maximizeInPlaceFromFloats = function (x, y, z) {
  3234. if (x > this.x)
  3235. this.x = x;
  3236. if (y > this.y)
  3237. this.y = y;
  3238. if (z > this.z)
  3239. this.z = z;
  3240. return this;
  3241. };
  3242. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3243. /**
  3244. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3245. */
  3246. get: function () {
  3247. var absX = Math.abs(this.x);
  3248. var absY = Math.abs(this.y);
  3249. if (absX !== absY) {
  3250. return true;
  3251. }
  3252. var absZ = Math.abs(this.z);
  3253. if (absX !== absZ) {
  3254. return true;
  3255. }
  3256. if (absY !== absZ) {
  3257. return true;
  3258. }
  3259. return false;
  3260. },
  3261. enumerable: true,
  3262. configurable: true
  3263. });
  3264. /**
  3265. * Gets a new Vector3 from current Vector3 floored values
  3266. * @returns a new Vector3
  3267. */
  3268. Vector3.prototype.floor = function () {
  3269. return new Vector3(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z));
  3270. };
  3271. /**
  3272. * Gets a new Vector3 from current Vector3 floored values
  3273. * @returns a new Vector3
  3274. */
  3275. Vector3.prototype.fract = function () {
  3276. return new Vector3(this.x - Math.floor(this.x), this.y - Math.floor(this.y), this.z - Math.floor(this.z));
  3277. };
  3278. // Properties
  3279. /**
  3280. * Gets the length of the Vector3
  3281. * @returns the length of the Vecto3
  3282. */
  3283. Vector3.prototype.length = function () {
  3284. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3285. };
  3286. /**
  3287. * Gets the squared length of the Vector3
  3288. * @returns squared length of the Vector3
  3289. */
  3290. Vector3.prototype.lengthSquared = function () {
  3291. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3292. };
  3293. /**
  3294. * Normalize the current Vector3.
  3295. * Please note that this is an in place operation.
  3296. * @returns the current updated Vector3
  3297. */
  3298. Vector3.prototype.normalize = function () {
  3299. var len = this.length();
  3300. if (len === 0 || len === 1.0)
  3301. return this;
  3302. var num = 1.0 / len;
  3303. this.x *= num;
  3304. this.y *= num;
  3305. this.z *= num;
  3306. return this;
  3307. };
  3308. /**
  3309. * Normalize the current Vector3 to a new vector
  3310. * @returns the new Vector3
  3311. */
  3312. Vector3.prototype.normalizeToNew = function () {
  3313. var normalized = new Vector3(0, 0, 0);
  3314. this.normalizeToRef(normalized);
  3315. return normalized;
  3316. };
  3317. /**
  3318. * Normalize the current Vector3 to the reference
  3319. * @param reference define the Vector3 to update
  3320. * @returns the updated Vector3
  3321. */
  3322. Vector3.prototype.normalizeToRef = function (reference) {
  3323. var len = this.length();
  3324. if (len === 0 || len === 1.0) {
  3325. reference.set(this.x, this.y, this.z);
  3326. return reference;
  3327. }
  3328. var scale = 1.0 / len;
  3329. this.scaleToRef(scale, reference);
  3330. return reference;
  3331. };
  3332. /**
  3333. * Creates a new Vector3 copied from the current Vector3
  3334. * @returns the new Vector3
  3335. */
  3336. Vector3.prototype.clone = function () {
  3337. return new Vector3(this.x, this.y, this.z);
  3338. };
  3339. /**
  3340. * Copies the given vector coordinates to the current Vector3 ones
  3341. * @param source defines the source Vector3
  3342. * @returns the current updated Vector3
  3343. */
  3344. Vector3.prototype.copyFrom = function (source) {
  3345. this.x = source.x;
  3346. this.y = source.y;
  3347. this.z = source.z;
  3348. return this;
  3349. };
  3350. /**
  3351. * Copies the given floats to the current Vector3 coordinates
  3352. * @param x defines the x coordinate of the operand
  3353. * @param y defines the y coordinate of the operand
  3354. * @param z defines the z coordinate of the operand
  3355. * @returns the current updated Vector3
  3356. */
  3357. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3358. this.x = x;
  3359. this.y = y;
  3360. this.z = z;
  3361. return this;
  3362. };
  3363. /**
  3364. * Copies the given floats to the current Vector3 coordinates
  3365. * @param x defines the x coordinate of the operand
  3366. * @param y defines the y coordinate of the operand
  3367. * @param z defines the z coordinate of the operand
  3368. * @returns the current updated Vector3
  3369. */
  3370. Vector3.prototype.set = function (x, y, z) {
  3371. return this.copyFromFloats(x, y, z);
  3372. };
  3373. // Statics
  3374. /**
  3375. * Get the clip factor between two vectors
  3376. * @param vector0 defines the first operand
  3377. * @param vector1 defines the second operand
  3378. * @param axis defines the axis to use
  3379. * @param size defines the size along the axis
  3380. * @returns the clip factor
  3381. */
  3382. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3383. var d0 = Vector3.Dot(vector0, axis) - size;
  3384. var d1 = Vector3.Dot(vector1, axis) - size;
  3385. var s = d0 / (d0 - d1);
  3386. return s;
  3387. };
  3388. /**
  3389. * Get angle between two vectors
  3390. * @param vector0 angle between vector0 and vector1
  3391. * @param vector1 angle between vector0 and vector1
  3392. * @param normal direction of the normal
  3393. * @return the angle between vector0 and vector1
  3394. */
  3395. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3396. var v0 = MathTmp.Vector3[1].copyFrom(vector0).normalize();
  3397. var v1 = MathTmp.Vector3[2].copyFrom(vector1).normalize();
  3398. var dot = Vector3.Dot(v0, v1);
  3399. var n = MathTmp.Vector3[3];
  3400. Vector3.CrossToRef(v0, v1, n);
  3401. if (Vector3.Dot(n, normal) > 0) {
  3402. return Math.acos(dot);
  3403. }
  3404. return -Math.acos(dot);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set from the index "offset" of the given array
  3408. * @param array defines the source array
  3409. * @param offset defines the offset in the source array
  3410. * @returns the new Vector3
  3411. */
  3412. Vector3.FromArray = function (array, offset) {
  3413. if (!offset) {
  3414. offset = 0;
  3415. }
  3416. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3417. };
  3418. /**
  3419. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3420. * This function is deprecated. Use FromArray instead
  3421. * @param array defines the source array
  3422. * @param offset defines the offset in the source array
  3423. * @returns the new Vector3
  3424. */
  3425. Vector3.FromFloatArray = function (array, offset) {
  3426. return Vector3.FromArray(array, offset);
  3427. };
  3428. /**
  3429. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3430. * @param array defines the source array
  3431. * @param offset defines the offset in the source array
  3432. * @param result defines the Vector3 where to store the result
  3433. */
  3434. Vector3.FromArrayToRef = function (array, offset, result) {
  3435. result.x = array[offset];
  3436. result.y = array[offset + 1];
  3437. result.z = array[offset + 2];
  3438. };
  3439. /**
  3440. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3441. * This function is deprecated. Use FromArrayToRef instead.
  3442. * @param array defines the source array
  3443. * @param offset defines the offset in the source array
  3444. * @param result defines the Vector3 where to store the result
  3445. */
  3446. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3447. return Vector3.FromArrayToRef(array, offset, result);
  3448. };
  3449. /**
  3450. * Sets the given vector "result" with the given floats.
  3451. * @param x defines the x coordinate of the source
  3452. * @param y defines the y coordinate of the source
  3453. * @param z defines the z coordinate of the source
  3454. * @param result defines the Vector3 where to store the result
  3455. */
  3456. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3457. result.x = x;
  3458. result.y = y;
  3459. result.z = z;
  3460. };
  3461. /**
  3462. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3463. * @returns a new empty Vector3
  3464. */
  3465. Vector3.Zero = function () {
  3466. return new Vector3(0.0, 0.0, 0.0);
  3467. };
  3468. /**
  3469. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3470. * @returns a new unit Vector3
  3471. */
  3472. Vector3.One = function () {
  3473. return new Vector3(1.0, 1.0, 1.0);
  3474. };
  3475. /**
  3476. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3477. * @returns a new up Vector3
  3478. */
  3479. Vector3.Up = function () {
  3480. return new Vector3(0.0, 1.0, 0.0);
  3481. };
  3482. /**
  3483. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3484. * @returns a new down Vector3
  3485. */
  3486. Vector3.Down = function () {
  3487. return new Vector3(0.0, -1.0, 0.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.Forward = function () {
  3494. return new Vector3(0.0, 0.0, 1.0);
  3495. };
  3496. /**
  3497. * Returns a new Vector3 set to (0.0, 0.0, -1.0)
  3498. * @returns a new forward Vector3
  3499. */
  3500. Vector3.Backward = function () {
  3501. return new Vector3(0.0, 0.0, -1.0);
  3502. };
  3503. /**
  3504. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3505. * @returns a new right Vector3
  3506. */
  3507. Vector3.Right = function () {
  3508. return new Vector3(1.0, 0.0, 0.0);
  3509. };
  3510. /**
  3511. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3512. * @returns a new left Vector3
  3513. */
  3514. Vector3.Left = function () {
  3515. return new Vector3(-1.0, 0.0, 0.0);
  3516. };
  3517. /**
  3518. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3519. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3520. * @param vector defines the Vector3 to transform
  3521. * @param transformation defines the transformation matrix
  3522. * @returns the transformed Vector3
  3523. */
  3524. Vector3.TransformCoordinates = function (vector, transformation) {
  3525. var result = Vector3.Zero();
  3526. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3527. return result;
  3528. };
  3529. /**
  3530. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3531. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3532. * @param vector defines the Vector3 to transform
  3533. * @param transformation defines the transformation matrix
  3534. * @param result defines the Vector3 where to store the result
  3535. */
  3536. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3537. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3538. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3539. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3540. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3541. result.x = x / w;
  3542. result.y = y / w;
  3543. result.z = z / w;
  3544. };
  3545. /**
  3546. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3547. * This method computes tranformed coordinates only, not transformed direction vectors
  3548. * @param x define the x coordinate of the source vector
  3549. * @param y define the y coordinate of the source vector
  3550. * @param z define the z coordinate of the source vector
  3551. * @param transformation defines the transformation matrix
  3552. * @param result defines the Vector3 where to store the result
  3553. */
  3554. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3555. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3556. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3557. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3558. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3559. result.x = rx / rw;
  3560. result.y = ry / rw;
  3561. result.z = rz / rw;
  3562. };
  3563. /**
  3564. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3565. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3566. * @param vector defines the Vector3 to transform
  3567. * @param transformation defines the transformation matrix
  3568. * @returns the new Vector3
  3569. */
  3570. Vector3.TransformNormal = function (vector, transformation) {
  3571. var result = Vector3.Zero();
  3572. Vector3.TransformNormalToRef(vector, transformation, result);
  3573. return result;
  3574. };
  3575. /**
  3576. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3577. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3578. * @param vector defines the Vector3 to transform
  3579. * @param transformation defines the transformation matrix
  3580. * @param result defines the Vector3 where to store the result
  3581. */
  3582. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3583. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3584. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3585. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3586. result.x = x;
  3587. result.y = y;
  3588. result.z = z;
  3589. };
  3590. /**
  3591. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3592. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3593. * @param x define the x coordinate of the source vector
  3594. * @param y define the y coordinate of the source vector
  3595. * @param z define the z coordinate of the source vector
  3596. * @param transformation defines the transformation matrix
  3597. * @param result defines the Vector3 where to store the result
  3598. */
  3599. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3600. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3601. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3602. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3603. };
  3604. /**
  3605. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3606. * @param value1 defines the first control point
  3607. * @param value2 defines the second control point
  3608. * @param value3 defines the third control point
  3609. * @param value4 defines the fourth control point
  3610. * @param amount defines the amount on the spline to use
  3611. * @returns the new Vector3
  3612. */
  3613. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3614. var squared = amount * amount;
  3615. var cubed = amount * squared;
  3616. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3617. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3618. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3619. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3620. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3621. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3622. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3623. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3624. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3625. return new Vector3(x, y, z);
  3626. };
  3627. /**
  3628. * 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"
  3629. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3630. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3631. * @param value defines the current value
  3632. * @param min defines the lower range value
  3633. * @param max defines the upper range value
  3634. * @returns the new Vector3
  3635. */
  3636. Vector3.Clamp = function (value, min, max) {
  3637. var x = value.x;
  3638. x = (x > max.x) ? max.x : x;
  3639. x = (x < min.x) ? min.x : x;
  3640. var y = value.y;
  3641. y = (y > max.y) ? max.y : y;
  3642. y = (y < min.y) ? min.y : y;
  3643. var z = value.z;
  3644. z = (z > max.z) ? max.z : z;
  3645. z = (z < min.z) ? min.z : z;
  3646. return new Vector3(x, y, z);
  3647. };
  3648. /**
  3649. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3650. * @param value1 defines the first control point
  3651. * @param tangent1 defines the first tangent vector
  3652. * @param value2 defines the second control point
  3653. * @param tangent2 defines the second tangent vector
  3654. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3655. * @returns the new Vector3
  3656. */
  3657. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3658. var squared = amount * amount;
  3659. var cubed = amount * squared;
  3660. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3661. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3662. var part3 = (cubed - (2.0 * squared)) + amount;
  3663. var part4 = cubed - squared;
  3664. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3665. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3666. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3667. return new Vector3(x, y, z);
  3668. };
  3669. /**
  3670. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3671. * @param start defines the start value
  3672. * @param end defines the end value
  3673. * @param amount max defines amount between both (between 0 and 1)
  3674. * @returns the new Vector3
  3675. */
  3676. Vector3.Lerp = function (start, end, amount) {
  3677. var result = new Vector3(0, 0, 0);
  3678. Vector3.LerpToRef(start, end, amount, result);
  3679. return result;
  3680. };
  3681. /**
  3682. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3683. * @param start defines the start value
  3684. * @param end defines the end value
  3685. * @param amount max defines amount between both (between 0 and 1)
  3686. * @param result defines the Vector3 where to store the result
  3687. */
  3688. Vector3.LerpToRef = function (start, end, amount, result) {
  3689. result.x = start.x + ((end.x - start.x) * amount);
  3690. result.y = start.y + ((end.y - start.y) * amount);
  3691. result.z = start.z + ((end.z - start.z) * amount);
  3692. };
  3693. /**
  3694. * Returns the dot product (float) between the vectors "left" and "right"
  3695. * @param left defines the left operand
  3696. * @param right defines the right operand
  3697. * @returns the dot product
  3698. */
  3699. Vector3.Dot = function (left, right) {
  3700. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3701. };
  3702. /**
  3703. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3704. * The cross product is then orthogonal to both "left" and "right"
  3705. * @param left defines the left operand
  3706. * @param right defines the right operand
  3707. * @returns the cross product
  3708. */
  3709. Vector3.Cross = function (left, right) {
  3710. var result = Vector3.Zero();
  3711. Vector3.CrossToRef(left, right, result);
  3712. return result;
  3713. };
  3714. /**
  3715. * Sets the given vector "result" with the cross product of "left" and "right"
  3716. * The cross product is then orthogonal to both "left" and "right"
  3717. * @param left defines the left operand
  3718. * @param right defines the right operand
  3719. * @param result defines the Vector3 where to store the result
  3720. */
  3721. Vector3.CrossToRef = function (left, right, result) {
  3722. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3723. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3724. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3725. result.copyFrom(MathTmp.Vector3[0]);
  3726. };
  3727. /**
  3728. * Returns a new Vector3 as the normalization of the given vector
  3729. * @param vector defines the Vector3 to normalize
  3730. * @returns the new Vector3
  3731. */
  3732. Vector3.Normalize = function (vector) {
  3733. var result = Vector3.Zero();
  3734. Vector3.NormalizeToRef(vector, result);
  3735. return result;
  3736. };
  3737. /**
  3738. * Sets the given vector "result" with the normalization of the given first vector
  3739. * @param vector defines the Vector3 to normalize
  3740. * @param result defines the Vector3 where to store the result
  3741. */
  3742. Vector3.NormalizeToRef = function (vector, result) {
  3743. result.copyFrom(vector);
  3744. result.normalize();
  3745. };
  3746. /**
  3747. * Project a Vector3 onto screen space
  3748. * @param vector defines the Vector3 to project
  3749. * @param world defines the world matrix to use
  3750. * @param transform defines the transform (view x projection) matrix to use
  3751. * @param viewport defines the screen viewport to use
  3752. * @returns the new Vector3
  3753. */
  3754. Vector3.Project = function (vector, world, transform, viewport) {
  3755. var cw = viewport.width;
  3756. var ch = viewport.height;
  3757. var cx = viewport.x;
  3758. var cy = viewport.y;
  3759. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3760. 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);
  3761. var matrix = MathTmp.Matrix[0];
  3762. world.multiplyToRef(transform, matrix);
  3763. matrix.multiplyToRef(viewportMatrix, matrix);
  3764. return Vector3.TransformCoordinates(vector, matrix);
  3765. };
  3766. /**
  3767. * Unproject from screen space to object space
  3768. * @param source defines the screen space Vector3 to use
  3769. * @param viewportWidth defines the current width of the viewport
  3770. * @param viewportHeight defines the current height of the viewport
  3771. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3772. * @param transform defines the transform (view x projection) matrix to use
  3773. * @returns the new Vector3
  3774. */
  3775. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3776. var matrix = MathTmp.Matrix[0];
  3777. world.multiplyToRef(transform, matrix);
  3778. matrix.invert();
  3779. source.x = source.x / viewportWidth * 2 - 1;
  3780. source.y = -(source.y / viewportHeight * 2 - 1);
  3781. var vector = Vector3.TransformCoordinates(source, matrix);
  3782. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3783. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3784. vector = vector.scale(1.0 / num);
  3785. }
  3786. return vector;
  3787. };
  3788. /**
  3789. * Unproject from screen space to object space
  3790. * @param source defines the screen space Vector3 to use
  3791. * @param viewportWidth defines the current width of the viewport
  3792. * @param viewportHeight defines the current height of the viewport
  3793. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3794. * @param view defines the view matrix to use
  3795. * @param projection defines the projection matrix to use
  3796. * @returns the new Vector3
  3797. */
  3798. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3799. var result = Vector3.Zero();
  3800. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3801. return result;
  3802. };
  3803. /**
  3804. * Unproject from screen space to object space
  3805. * @param source defines the screen space Vector3 to use
  3806. * @param viewportWidth defines the current width of the viewport
  3807. * @param viewportHeight defines the current height of the viewport
  3808. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3809. * @param view defines the view matrix to use
  3810. * @param projection defines the projection matrix to use
  3811. * @param result defines the Vector3 where to store the result
  3812. */
  3813. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3814. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3815. };
  3816. /**
  3817. * Unproject from screen space to object space
  3818. * @param sourceX defines the screen space x coordinate to use
  3819. * @param sourceY defines the screen space y coordinate to use
  3820. * @param sourceZ defines the screen space z coordinate to use
  3821. * @param viewportWidth defines the current width of the viewport
  3822. * @param viewportHeight defines the current height of the viewport
  3823. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3824. * @param view defines the view matrix to use
  3825. * @param projection defines the projection matrix to use
  3826. * @param result defines the Vector3 where to store the result
  3827. */
  3828. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3829. var matrix = MathTmp.Matrix[0];
  3830. world.multiplyToRef(view, matrix);
  3831. matrix.multiplyToRef(projection, matrix);
  3832. matrix.invert();
  3833. var screenSource = MathTmp.Vector3[0];
  3834. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3835. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3836. screenSource.z = 2 * sourceZ - 1.0;
  3837. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3838. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3839. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3840. result.scaleInPlace(1.0 / num);
  3841. }
  3842. };
  3843. /**
  3844. * Gets the minimal coordinate values between two Vector3
  3845. * @param left defines the first operand
  3846. * @param right defines the second operand
  3847. * @returns the new Vector3
  3848. */
  3849. Vector3.Minimize = function (left, right) {
  3850. var min = left.clone();
  3851. min.minimizeInPlace(right);
  3852. return min;
  3853. };
  3854. /**
  3855. * Gets the maximal coordinate values between two Vector3
  3856. * @param left defines the first operand
  3857. * @param right defines the second operand
  3858. * @returns the new Vector3
  3859. */
  3860. Vector3.Maximize = function (left, right) {
  3861. var max = left.clone();
  3862. max.maximizeInPlace(right);
  3863. return max;
  3864. };
  3865. /**
  3866. * Returns the distance between the vectors "value1" and "value2"
  3867. * @param value1 defines the first operand
  3868. * @param value2 defines the second operand
  3869. * @returns the distance
  3870. */
  3871. Vector3.Distance = function (value1, value2) {
  3872. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3873. };
  3874. /**
  3875. * Returns the squared distance between the vectors "value1" and "value2"
  3876. * @param value1 defines the first operand
  3877. * @param value2 defines the second operand
  3878. * @returns the squared distance
  3879. */
  3880. Vector3.DistanceSquared = function (value1, value2) {
  3881. var x = value1.x - value2.x;
  3882. var y = value1.y - value2.y;
  3883. var z = value1.z - value2.z;
  3884. return (x * x) + (y * y) + (z * z);
  3885. };
  3886. /**
  3887. * Returns a new Vector3 located at the center between "value1" and "value2"
  3888. * @param value1 defines the first operand
  3889. * @param value2 defines the second operand
  3890. * @returns the new Vector3
  3891. */
  3892. Vector3.Center = function (value1, value2) {
  3893. var center = value1.add(value2);
  3894. center.scaleInPlace(0.5);
  3895. return center;
  3896. };
  3897. /**
  3898. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3899. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3900. * to something in order to rotate it from its local system to the given target system
  3901. * Note: axis1, axis2 and axis3 are normalized during this operation
  3902. * @param axis1 defines the first axis
  3903. * @param axis2 defines the second axis
  3904. * @param axis3 defines the third axis
  3905. * @returns a new Vector3
  3906. */
  3907. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3908. var rotation = Vector3.Zero();
  3909. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3910. return rotation;
  3911. };
  3912. /**
  3913. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3914. * @param axis1 defines the first axis
  3915. * @param axis2 defines the second axis
  3916. * @param axis3 defines the third axis
  3917. * @param ref defines the Vector3 where to store the result
  3918. */
  3919. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3920. var quat = MathTmp.Quaternion[0];
  3921. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3922. quat.toEulerAnglesToRef(ref);
  3923. };
  3924. return Vector3;
  3925. }());
  3926. BABYLON.Vector3 = Vector3;
  3927. /**
  3928. * Vector4 class created for EulerAngle class conversion to Quaternion
  3929. */
  3930. var Vector4 = /** @class */ (function () {
  3931. /**
  3932. * Creates a Vector4 object from the given floats.
  3933. * @param x x value of the vector
  3934. * @param y y value of the vector
  3935. * @param z z value of the vector
  3936. * @param w w value of the vector
  3937. */
  3938. function Vector4(
  3939. /** x value of the vector */
  3940. x,
  3941. /** y value of the vector */
  3942. y,
  3943. /** z value of the vector */
  3944. z,
  3945. /** w value of the vector */
  3946. w) {
  3947. this.x = x;
  3948. this.y = y;
  3949. this.z = z;
  3950. this.w = w;
  3951. }
  3952. /**
  3953. * Returns the string with the Vector4 coordinates.
  3954. * @returns a string containing all the vector values
  3955. */
  3956. Vector4.prototype.toString = function () {
  3957. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3958. };
  3959. /**
  3960. * Returns the string "Vector4".
  3961. * @returns "Vector4"
  3962. */
  3963. Vector4.prototype.getClassName = function () {
  3964. return "Vector4";
  3965. };
  3966. /**
  3967. * Returns the Vector4 hash code.
  3968. * @returns a unique hash code
  3969. */
  3970. Vector4.prototype.getHashCode = function () {
  3971. var hash = this.x || 0;
  3972. hash = (hash * 397) ^ (this.y || 0);
  3973. hash = (hash * 397) ^ (this.z || 0);
  3974. hash = (hash * 397) ^ (this.w || 0);
  3975. return hash;
  3976. };
  3977. // Operators
  3978. /**
  3979. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3980. * @returns the resulting array
  3981. */
  3982. Vector4.prototype.asArray = function () {
  3983. var result = new Array();
  3984. this.toArray(result, 0);
  3985. return result;
  3986. };
  3987. /**
  3988. * Populates the given array from the given index with the Vector4 coordinates.
  3989. * @param array array to populate
  3990. * @param index index of the array to start at (default: 0)
  3991. * @returns the Vector4.
  3992. */
  3993. Vector4.prototype.toArray = function (array, index) {
  3994. if (index === undefined) {
  3995. index = 0;
  3996. }
  3997. array[index] = this.x;
  3998. array[index + 1] = this.y;
  3999. array[index + 2] = this.z;
  4000. array[index + 3] = this.w;
  4001. return this;
  4002. };
  4003. /**
  4004. * Adds the given vector to the current Vector4.
  4005. * @param otherVector the vector to add
  4006. * @returns the updated Vector4.
  4007. */
  4008. Vector4.prototype.addInPlace = function (otherVector) {
  4009. this.x += otherVector.x;
  4010. this.y += otherVector.y;
  4011. this.z += otherVector.z;
  4012. this.w += otherVector.w;
  4013. return this;
  4014. };
  4015. /**
  4016. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  4017. * @param otherVector the vector to add
  4018. * @returns the resulting vector
  4019. */
  4020. Vector4.prototype.add = function (otherVector) {
  4021. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  4022. };
  4023. /**
  4024. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  4025. * @param otherVector the vector to add
  4026. * @param result the vector to store the result
  4027. * @returns the current Vector4.
  4028. */
  4029. Vector4.prototype.addToRef = function (otherVector, result) {
  4030. result.x = this.x + otherVector.x;
  4031. result.y = this.y + otherVector.y;
  4032. result.z = this.z + otherVector.z;
  4033. result.w = this.w + otherVector.w;
  4034. return this;
  4035. };
  4036. /**
  4037. * Subtract in place the given vector from the current Vector4.
  4038. * @param otherVector the vector to subtract
  4039. * @returns the updated Vector4.
  4040. */
  4041. Vector4.prototype.subtractInPlace = function (otherVector) {
  4042. this.x -= otherVector.x;
  4043. this.y -= otherVector.y;
  4044. this.z -= otherVector.z;
  4045. this.w -= otherVector.w;
  4046. return this;
  4047. };
  4048. /**
  4049. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  4050. * @param otherVector the vector to add
  4051. * @returns the new vector with the result
  4052. */
  4053. Vector4.prototype.subtract = function (otherVector) {
  4054. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  4055. };
  4056. /**
  4057. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  4058. * @param otherVector the vector to subtract
  4059. * @param result the vector to store the result
  4060. * @returns the current Vector4.
  4061. */
  4062. Vector4.prototype.subtractToRef = function (otherVector, result) {
  4063. result.x = this.x - otherVector.x;
  4064. result.y = this.y - otherVector.y;
  4065. result.z = this.z - otherVector.z;
  4066. result.w = this.w - otherVector.w;
  4067. return this;
  4068. };
  4069. /**
  4070. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4071. */
  4072. /**
  4073. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4074. * @param x value to subtract
  4075. * @param y value to subtract
  4076. * @param z value to subtract
  4077. * @param w value to subtract
  4078. * @returns new vector containing the result
  4079. */
  4080. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  4081. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  4082. };
  4083. /**
  4084. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  4085. * @param x value to subtract
  4086. * @param y value to subtract
  4087. * @param z value to subtract
  4088. * @param w value to subtract
  4089. * @param result the vector to store the result in
  4090. * @returns the current Vector4.
  4091. */
  4092. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  4093. result.x = this.x - x;
  4094. result.y = this.y - y;
  4095. result.z = this.z - z;
  4096. result.w = this.w - w;
  4097. return this;
  4098. };
  4099. /**
  4100. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  4101. * @returns a new vector with the negated values
  4102. */
  4103. Vector4.prototype.negate = function () {
  4104. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  4105. };
  4106. /**
  4107. * Multiplies the current Vector4 coordinates by scale (float).
  4108. * @param scale the number to scale with
  4109. * @returns the updated Vector4.
  4110. */
  4111. Vector4.prototype.scaleInPlace = function (scale) {
  4112. this.x *= scale;
  4113. this.y *= scale;
  4114. this.z *= scale;
  4115. this.w *= scale;
  4116. return this;
  4117. };
  4118. /**
  4119. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4120. * @param scale the number to scale with
  4121. * @returns a new vector with the result
  4122. */
  4123. Vector4.prototype.scale = function (scale) {
  4124. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4125. };
  4126. /**
  4127. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4128. * @param scale the number to scale with
  4129. * @param result a vector to store the result in
  4130. * @returns the current Vector4.
  4131. */
  4132. Vector4.prototype.scaleToRef = function (scale, result) {
  4133. result.x = this.x * scale;
  4134. result.y = this.y * scale;
  4135. result.z = this.z * scale;
  4136. result.w = this.w * scale;
  4137. return this;
  4138. };
  4139. /**
  4140. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4141. * @param scale defines the scale factor
  4142. * @param result defines the Vector4 object where to store the result
  4143. * @returns the unmodified current Vector4
  4144. */
  4145. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4146. result.x += this.x * scale;
  4147. result.y += this.y * scale;
  4148. result.z += this.z * scale;
  4149. result.w += this.w * scale;
  4150. return this;
  4151. };
  4152. /**
  4153. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4154. * @param otherVector the vector to compare against
  4155. * @returns true if they are equal
  4156. */
  4157. Vector4.prototype.equals = function (otherVector) {
  4158. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4159. };
  4160. /**
  4161. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4162. * @param otherVector vector to compare against
  4163. * @param epsilon (Default: very small number)
  4164. * @returns true if they are equal
  4165. */
  4166. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4167. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4168. return otherVector
  4169. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4170. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4171. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4172. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4173. };
  4174. /**
  4175. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4176. * @param x x value to compare against
  4177. * @param y y value to compare against
  4178. * @param z z value to compare against
  4179. * @param w w value to compare against
  4180. * @returns true if equal
  4181. */
  4182. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4183. return this.x === x && this.y === y && this.z === z && this.w === w;
  4184. };
  4185. /**
  4186. * Multiplies in place the current Vector4 by the given one.
  4187. * @param otherVector vector to multiple with
  4188. * @returns the updated Vector4.
  4189. */
  4190. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4191. this.x *= otherVector.x;
  4192. this.y *= otherVector.y;
  4193. this.z *= otherVector.z;
  4194. this.w *= otherVector.w;
  4195. return this;
  4196. };
  4197. /**
  4198. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4199. * @param otherVector vector to multiple with
  4200. * @returns resulting new vector
  4201. */
  4202. Vector4.prototype.multiply = function (otherVector) {
  4203. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4204. };
  4205. /**
  4206. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4207. * @param otherVector vector to multiple with
  4208. * @param result vector to store the result
  4209. * @returns the current Vector4.
  4210. */
  4211. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4212. result.x = this.x * otherVector.x;
  4213. result.y = this.y * otherVector.y;
  4214. result.z = this.z * otherVector.z;
  4215. result.w = this.w * otherVector.w;
  4216. return this;
  4217. };
  4218. /**
  4219. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4220. * @param x x value multiply with
  4221. * @param y y value multiply with
  4222. * @param z z value multiply with
  4223. * @param w w value multiply with
  4224. * @returns resulting new vector
  4225. */
  4226. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4227. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4228. };
  4229. /**
  4230. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4231. * @param otherVector vector to devide with
  4232. * @returns resulting new vector
  4233. */
  4234. Vector4.prototype.divide = function (otherVector) {
  4235. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4236. };
  4237. /**
  4238. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4239. * @param otherVector vector to devide with
  4240. * @param result vector to store the result
  4241. * @returns the current Vector4.
  4242. */
  4243. Vector4.prototype.divideToRef = function (otherVector, result) {
  4244. result.x = this.x / otherVector.x;
  4245. result.y = this.y / otherVector.y;
  4246. result.z = this.z / otherVector.z;
  4247. result.w = this.w / otherVector.w;
  4248. return this;
  4249. };
  4250. /**
  4251. * Divides the current Vector3 coordinates by the given ones.
  4252. * @param otherVector vector to devide with
  4253. * @returns the updated Vector3.
  4254. */
  4255. Vector4.prototype.divideInPlace = function (otherVector) {
  4256. return this.divideToRef(otherVector, this);
  4257. };
  4258. /**
  4259. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4260. * @param other defines the second operand
  4261. * @returns the current updated Vector4
  4262. */
  4263. Vector4.prototype.minimizeInPlace = function (other) {
  4264. if (other.x < this.x)
  4265. this.x = other.x;
  4266. if (other.y < this.y)
  4267. this.y = other.y;
  4268. if (other.z < this.z)
  4269. this.z = other.z;
  4270. if (other.w < this.w)
  4271. this.w = other.w;
  4272. return this;
  4273. };
  4274. /**
  4275. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4276. * @param other defines the second operand
  4277. * @returns the current updated Vector4
  4278. */
  4279. Vector4.prototype.maximizeInPlace = function (other) {
  4280. if (other.x > this.x)
  4281. this.x = other.x;
  4282. if (other.y > this.y)
  4283. this.y = other.y;
  4284. if (other.z > this.z)
  4285. this.z = other.z;
  4286. if (other.w > this.w)
  4287. this.w = other.w;
  4288. return this;
  4289. };
  4290. /**
  4291. * Gets a new Vector4 from current Vector4 floored values
  4292. * @returns a new Vector4
  4293. */
  4294. Vector4.prototype.floor = function () {
  4295. return new Vector4(Math.floor(this.x), Math.floor(this.y), Math.floor(this.z), Math.floor(this.w));
  4296. };
  4297. /**
  4298. * Gets a new Vector4 from current Vector3 floored values
  4299. * @returns a new Vector4
  4300. */
  4301. Vector4.prototype.fract = function () {
  4302. 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));
  4303. };
  4304. // Properties
  4305. /**
  4306. * Returns the Vector4 length (float).
  4307. * @returns the length
  4308. */
  4309. Vector4.prototype.length = function () {
  4310. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4311. };
  4312. /**
  4313. * Returns the Vector4 squared length (float).
  4314. * @returns the length squared
  4315. */
  4316. Vector4.prototype.lengthSquared = function () {
  4317. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4318. };
  4319. // Methods
  4320. /**
  4321. * Normalizes in place the Vector4.
  4322. * @returns the updated Vector4.
  4323. */
  4324. Vector4.prototype.normalize = function () {
  4325. var len = this.length();
  4326. if (len === 0)
  4327. return this;
  4328. var num = 1.0 / len;
  4329. this.x *= num;
  4330. this.y *= num;
  4331. this.z *= num;
  4332. this.w *= num;
  4333. return this;
  4334. };
  4335. /**
  4336. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4337. * @returns this converted to a new vector3
  4338. */
  4339. Vector4.prototype.toVector3 = function () {
  4340. return new Vector3(this.x, this.y, this.z);
  4341. };
  4342. /**
  4343. * Returns a new Vector4 copied from the current one.
  4344. * @returns the new cloned vector
  4345. */
  4346. Vector4.prototype.clone = function () {
  4347. return new Vector4(this.x, this.y, this.z, this.w);
  4348. };
  4349. /**
  4350. * Updates the current Vector4 with the given one coordinates.
  4351. * @param source the source vector to copy from
  4352. * @returns the updated Vector4.
  4353. */
  4354. Vector4.prototype.copyFrom = function (source) {
  4355. this.x = source.x;
  4356. this.y = source.y;
  4357. this.z = source.z;
  4358. this.w = source.w;
  4359. return this;
  4360. };
  4361. /**
  4362. * Updates the current Vector4 coordinates with the given floats.
  4363. * @param x float to copy from
  4364. * @param y float to copy from
  4365. * @param z float to copy from
  4366. * @param w float to copy from
  4367. * @returns the updated Vector4.
  4368. */
  4369. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4370. this.x = x;
  4371. this.y = y;
  4372. this.z = z;
  4373. this.w = w;
  4374. return this;
  4375. };
  4376. /**
  4377. * Updates the current Vector4 coordinates with the given floats.
  4378. * @param x float to set from
  4379. * @param y float to set from
  4380. * @param z float to set from
  4381. * @param w float to set from
  4382. * @returns the updated Vector4.
  4383. */
  4384. Vector4.prototype.set = function (x, y, z, w) {
  4385. return this.copyFromFloats(x, y, z, w);
  4386. };
  4387. // Statics
  4388. /**
  4389. * Returns a new Vector4 set from the starting index of the given array.
  4390. * @param array the array to pull values from
  4391. * @param offset the offset into the array to start at
  4392. * @returns the new vector
  4393. */
  4394. Vector4.FromArray = function (array, offset) {
  4395. if (!offset) {
  4396. offset = 0;
  4397. }
  4398. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4399. };
  4400. /**
  4401. * Updates the given vector "result" from the starting index of the given array.
  4402. * @param array the array to pull values from
  4403. * @param offset the offset into the array to start at
  4404. * @param result the vector to store the result in
  4405. */
  4406. Vector4.FromArrayToRef = function (array, offset, result) {
  4407. result.x = array[offset];
  4408. result.y = array[offset + 1];
  4409. result.z = array[offset + 2];
  4410. result.w = array[offset + 3];
  4411. };
  4412. /**
  4413. * Updates the given vector "result" from the starting index of the given Float32Array.
  4414. * @param array the array to pull values from
  4415. * @param offset the offset into the array to start at
  4416. * @param result the vector to store the result in
  4417. */
  4418. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4419. Vector4.FromArrayToRef(array, offset, result);
  4420. };
  4421. /**
  4422. * Updates the given vector "result" coordinates from the given floats.
  4423. * @param x float to set from
  4424. * @param y float to set from
  4425. * @param z float to set from
  4426. * @param w float to set from
  4427. * @param result the vector to the floats in
  4428. */
  4429. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4430. result.x = x;
  4431. result.y = y;
  4432. result.z = z;
  4433. result.w = w;
  4434. };
  4435. /**
  4436. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4437. * @returns the new vector
  4438. */
  4439. Vector4.Zero = function () {
  4440. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4441. };
  4442. /**
  4443. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4444. * @returns the new vector
  4445. */
  4446. Vector4.One = function () {
  4447. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4448. };
  4449. /**
  4450. * Returns a new normalized Vector4 from the given one.
  4451. * @param vector the vector to normalize
  4452. * @returns the vector
  4453. */
  4454. Vector4.Normalize = function (vector) {
  4455. var result = Vector4.Zero();
  4456. Vector4.NormalizeToRef(vector, result);
  4457. return result;
  4458. };
  4459. /**
  4460. * Updates the given vector "result" from the normalization of the given one.
  4461. * @param vector the vector to normalize
  4462. * @param result the vector to store the result in
  4463. */
  4464. Vector4.NormalizeToRef = function (vector, result) {
  4465. result.copyFrom(vector);
  4466. result.normalize();
  4467. };
  4468. /**
  4469. * Returns a vector with the minimum values from the left and right vectors
  4470. * @param left left vector to minimize
  4471. * @param right right vector to minimize
  4472. * @returns a new vector with the minimum of the left and right vector values
  4473. */
  4474. Vector4.Minimize = function (left, right) {
  4475. var min = left.clone();
  4476. min.minimizeInPlace(right);
  4477. return min;
  4478. };
  4479. /**
  4480. * Returns a vector with the maximum values from the left and right vectors
  4481. * @param left left vector to maximize
  4482. * @param right right vector to maximize
  4483. * @returns a new vector with the maximum of the left and right vector values
  4484. */
  4485. Vector4.Maximize = function (left, right) {
  4486. var max = left.clone();
  4487. max.maximizeInPlace(right);
  4488. return max;
  4489. };
  4490. /**
  4491. * Returns the distance (float) between the vectors "value1" and "value2".
  4492. * @param value1 value to calulate the distance between
  4493. * @param value2 value to calulate the distance between
  4494. * @return the distance between the two vectors
  4495. */
  4496. Vector4.Distance = function (value1, value2) {
  4497. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4498. };
  4499. /**
  4500. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4501. * @param value1 value to calulate the distance between
  4502. * @param value2 value to calulate the distance between
  4503. * @return the distance between the two vectors squared
  4504. */
  4505. Vector4.DistanceSquared = function (value1, value2) {
  4506. var x = value1.x - value2.x;
  4507. var y = value1.y - value2.y;
  4508. var z = value1.z - value2.z;
  4509. var w = value1.w - value2.w;
  4510. return (x * x) + (y * y) + (z * z) + (w * w);
  4511. };
  4512. /**
  4513. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4514. * @param value1 value to calulate the center between
  4515. * @param value2 value to calulate the center between
  4516. * @return the center between the two vectors
  4517. */
  4518. Vector4.Center = function (value1, value2) {
  4519. var center = value1.add(value2);
  4520. center.scaleInPlace(0.5);
  4521. return center;
  4522. };
  4523. /**
  4524. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4525. * This methods computes transformed normalized direction vectors only.
  4526. * @param vector the vector to transform
  4527. * @param transformation the transformation matrix to apply
  4528. * @returns the new vector
  4529. */
  4530. Vector4.TransformNormal = function (vector, transformation) {
  4531. var result = Vector4.Zero();
  4532. Vector4.TransformNormalToRef(vector, transformation, result);
  4533. return result;
  4534. };
  4535. /**
  4536. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4537. * This methods computes transformed normalized direction vectors only.
  4538. * @param vector the vector to transform
  4539. * @param transformation the transformation matrix to apply
  4540. * @param result the vector to store the result in
  4541. */
  4542. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4543. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4544. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4545. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4546. result.x = x;
  4547. result.y = y;
  4548. result.z = z;
  4549. result.w = vector.w;
  4550. };
  4551. /**
  4552. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4553. * This methods computes transformed normalized direction vectors only.
  4554. * @param x value to transform
  4555. * @param y value to transform
  4556. * @param z value to transform
  4557. * @param w value to transform
  4558. * @param transformation the transformation matrix to apply
  4559. * @param result the vector to store the results in
  4560. */
  4561. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4562. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4563. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4564. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4565. result.w = w;
  4566. };
  4567. return Vector4;
  4568. }());
  4569. BABYLON.Vector4 = Vector4;
  4570. /**
  4571. * Size containing widht and height
  4572. */
  4573. var Size = /** @class */ (function () {
  4574. /**
  4575. * Creates a Size object from the given width and height (floats).
  4576. * @param width width of the new size
  4577. * @param height height of the new size
  4578. */
  4579. function Size(width, height) {
  4580. this.width = width;
  4581. this.height = height;
  4582. }
  4583. /**
  4584. * Returns a string with the Size width and height
  4585. * @returns a string with the Size width and height
  4586. */
  4587. Size.prototype.toString = function () {
  4588. return "{W: " + this.width + ", H: " + this.height + "}";
  4589. };
  4590. /**
  4591. * "Size"
  4592. * @returns the string "Size"
  4593. */
  4594. Size.prototype.getClassName = function () {
  4595. return "Size";
  4596. };
  4597. /**
  4598. * Returns the Size hash code.
  4599. * @returns a hash code for a unique width and height
  4600. */
  4601. Size.prototype.getHashCode = function () {
  4602. var hash = this.width || 0;
  4603. hash = (hash * 397) ^ (this.height || 0);
  4604. return hash;
  4605. };
  4606. /**
  4607. * Updates the current size from the given one.
  4608. * @param src the given size
  4609. */
  4610. Size.prototype.copyFrom = function (src) {
  4611. this.width = src.width;
  4612. this.height = src.height;
  4613. };
  4614. /**
  4615. * Updates in place the current Size from the given floats.
  4616. * @param width width of the new size
  4617. * @param height height of the new size
  4618. * @returns the updated Size.
  4619. */
  4620. Size.prototype.copyFromFloats = function (width, height) {
  4621. this.width = width;
  4622. this.height = height;
  4623. return this;
  4624. };
  4625. /**
  4626. * Updates in place the current Size from the given floats.
  4627. * @param width width to set
  4628. * @param height height to set
  4629. * @returns the updated Size.
  4630. */
  4631. Size.prototype.set = function (width, height) {
  4632. return this.copyFromFloats(width, height);
  4633. };
  4634. /**
  4635. * Multiplies the width and height by numbers
  4636. * @param w factor to multiple the width by
  4637. * @param h factor to multiple the height by
  4638. * @returns a new Size set with the multiplication result of the current Size and the given floats.
  4639. */
  4640. Size.prototype.multiplyByFloats = function (w, h) {
  4641. return new Size(this.width * w, this.height * h);
  4642. };
  4643. /**
  4644. * Clones the size
  4645. * @returns a new Size copied from the given one.
  4646. */
  4647. Size.prototype.clone = function () {
  4648. return new Size(this.width, this.height);
  4649. };
  4650. /**
  4651. * True if the current Size and the given one width and height are strictly equal.
  4652. * @param other the other size to compare against
  4653. * @returns True if the current Size and the given one width and height are strictly equal.
  4654. */
  4655. Size.prototype.equals = function (other) {
  4656. if (!other) {
  4657. return false;
  4658. }
  4659. return (this.width === other.width) && (this.height === other.height);
  4660. };
  4661. Object.defineProperty(Size.prototype, "surface", {
  4662. /**
  4663. * The surface of the Size : width * height (float).
  4664. */
  4665. get: function () {
  4666. return this.width * this.height;
  4667. },
  4668. enumerable: true,
  4669. configurable: true
  4670. });
  4671. /**
  4672. * Create a new size of zero
  4673. * @returns a new Size set to (0.0, 0.0)
  4674. */
  4675. Size.Zero = function () {
  4676. return new Size(0.0, 0.0);
  4677. };
  4678. /**
  4679. * Sums the width and height of two sizes
  4680. * @param otherSize size to add to this size
  4681. * @returns a new Size set as the addition result of the current Size and the given one.
  4682. */
  4683. Size.prototype.add = function (otherSize) {
  4684. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4685. return r;
  4686. };
  4687. /**
  4688. * Subtracts the width and height of two
  4689. * @param otherSize size to subtract to this size
  4690. * @returns a new Size set as the subtraction result of the given one from the current Size.
  4691. */
  4692. Size.prototype.subtract = function (otherSize) {
  4693. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4694. return r;
  4695. };
  4696. /**
  4697. * Creates a new Size set at the linear interpolation "amount" between "start" and "end"
  4698. * @param start starting size to lerp between
  4699. * @param end end size to lerp between
  4700. * @param amount amount to lerp between the start and end values
  4701. * @returns a new Size set at the linear interpolation "amount" between "start" and "end"
  4702. */
  4703. Size.Lerp = function (start, end, amount) {
  4704. var w = start.width + ((end.width - start.width) * amount);
  4705. var h = start.height + ((end.height - start.height) * amount);
  4706. return new Size(w, h);
  4707. };
  4708. return Size;
  4709. }());
  4710. BABYLON.Size = Size;
  4711. /**
  4712. * Class used to store quaternion data
  4713. * @see https://en.wikipedia.org/wiki/Quaternion
  4714. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4715. */
  4716. var Quaternion = /** @class */ (function () {
  4717. /**
  4718. * Creates a new Quaternion from the given floats
  4719. * @param x defines the first component (0 by default)
  4720. * @param y defines the second component (0 by default)
  4721. * @param z defines the third component (0 by default)
  4722. * @param w defines the fourth component (1.0 by default)
  4723. */
  4724. function Quaternion(
  4725. /** defines the first component (0 by default) */
  4726. x,
  4727. /** defines the second component (0 by default) */
  4728. y,
  4729. /** defines the third component (0 by default) */
  4730. z,
  4731. /** defines the fourth component (1.0 by default) */
  4732. w) {
  4733. if (x === void 0) { x = 0.0; }
  4734. if (y === void 0) { y = 0.0; }
  4735. if (z === void 0) { z = 0.0; }
  4736. if (w === void 0) { w = 1.0; }
  4737. this.x = x;
  4738. this.y = y;
  4739. this.z = z;
  4740. this.w = w;
  4741. }
  4742. /**
  4743. * Gets a string representation for the current quaternion
  4744. * @returns a string with the Quaternion coordinates
  4745. */
  4746. Quaternion.prototype.toString = function () {
  4747. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4748. };
  4749. /**
  4750. * Gets the class name of the quaternion
  4751. * @returns the string "Quaternion"
  4752. */
  4753. Quaternion.prototype.getClassName = function () {
  4754. return "Quaternion";
  4755. };
  4756. /**
  4757. * Gets a hash code for this quaternion
  4758. * @returns the quaternion hash code
  4759. */
  4760. Quaternion.prototype.getHashCode = function () {
  4761. var hash = this.x || 0;
  4762. hash = (hash * 397) ^ (this.y || 0);
  4763. hash = (hash * 397) ^ (this.z || 0);
  4764. hash = (hash * 397) ^ (this.w || 0);
  4765. return hash;
  4766. };
  4767. /**
  4768. * Copy the quaternion to an array
  4769. * @returns a new array populated with 4 elements from the quaternion coordinates
  4770. */
  4771. Quaternion.prototype.asArray = function () {
  4772. return [this.x, this.y, this.z, this.w];
  4773. };
  4774. /**
  4775. * Check if two quaternions are equals
  4776. * @param otherQuaternion defines the second operand
  4777. * @return true if the current quaternion and the given one coordinates are strictly equals
  4778. */
  4779. Quaternion.prototype.equals = function (otherQuaternion) {
  4780. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4781. };
  4782. /**
  4783. * Clone the current quaternion
  4784. * @returns a new quaternion copied from the current one
  4785. */
  4786. Quaternion.prototype.clone = function () {
  4787. return new Quaternion(this.x, this.y, this.z, this.w);
  4788. };
  4789. /**
  4790. * Copy a quaternion to the current one
  4791. * @param other defines the other quaternion
  4792. * @returns the updated current quaternion
  4793. */
  4794. Quaternion.prototype.copyFrom = function (other) {
  4795. this.x = other.x;
  4796. this.y = other.y;
  4797. this.z = other.z;
  4798. this.w = other.w;
  4799. return this;
  4800. };
  4801. /**
  4802. * Updates the current quaternion with the given float coordinates
  4803. * @param x defines the x coordinate
  4804. * @param y defines the y coordinate
  4805. * @param z defines the z coordinate
  4806. * @param w defines the w coordinate
  4807. * @returns the updated current quaternion
  4808. */
  4809. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4810. this.x = x;
  4811. this.y = y;
  4812. this.z = z;
  4813. this.w = w;
  4814. return this;
  4815. };
  4816. /**
  4817. * Updates the current quaternion from the given float coordinates
  4818. * @param x defines the x coordinate
  4819. * @param y defines the y coordinate
  4820. * @param z defines the z coordinate
  4821. * @param w defines the w coordinate
  4822. * @returns the updated current quaternion
  4823. */
  4824. Quaternion.prototype.set = function (x, y, z, w) {
  4825. return this.copyFromFloats(x, y, z, w);
  4826. };
  4827. /**
  4828. * Adds two quaternions
  4829. * @param other defines the second operand
  4830. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4831. */
  4832. Quaternion.prototype.add = function (other) {
  4833. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4834. };
  4835. /**
  4836. * Add a quaternion to the current one
  4837. * @param other defines the quaternion to add
  4838. * @returns the current quaternion
  4839. */
  4840. Quaternion.prototype.addInPlace = function (other) {
  4841. this.x += other.x;
  4842. this.y += other.y;
  4843. this.z += other.z;
  4844. this.w += other.w;
  4845. return this;
  4846. };
  4847. /**
  4848. * Subtract two quaternions
  4849. * @param other defines the second operand
  4850. * @returns a new quaternion as the subtraction result of the given one from the current one
  4851. */
  4852. Quaternion.prototype.subtract = function (other) {
  4853. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4854. };
  4855. /**
  4856. * Multiplies the current quaternion by a scale factor
  4857. * @param value defines the scale factor
  4858. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4859. */
  4860. Quaternion.prototype.scale = function (value) {
  4861. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4862. };
  4863. /**
  4864. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4865. * @param scale defines the scale factor
  4866. * @param result defines the Quaternion object where to store the result
  4867. * @returns the unmodified current quaternion
  4868. */
  4869. Quaternion.prototype.scaleToRef = function (scale, result) {
  4870. result.x = this.x * scale;
  4871. result.y = this.y * scale;
  4872. result.z = this.z * scale;
  4873. result.w = this.w * scale;
  4874. return this;
  4875. };
  4876. /**
  4877. * Multiplies in place the current quaternion by a scale factor
  4878. * @param value defines the scale factor
  4879. * @returns the current modified quaternion
  4880. */
  4881. Quaternion.prototype.scaleInPlace = function (value) {
  4882. this.x *= value;
  4883. this.y *= value;
  4884. this.z *= value;
  4885. this.w *= value;
  4886. return this;
  4887. };
  4888. /**
  4889. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4890. * @param scale defines the scale factor
  4891. * @param result defines the Quaternion object where to store the result
  4892. * @returns the unmodified current quaternion
  4893. */
  4894. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4895. result.x += this.x * scale;
  4896. result.y += this.y * scale;
  4897. result.z += this.z * scale;
  4898. result.w += this.w * scale;
  4899. return this;
  4900. };
  4901. /**
  4902. * Multiplies two quaternions
  4903. * @param q1 defines the second operand
  4904. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4905. */
  4906. Quaternion.prototype.multiply = function (q1) {
  4907. var result = new Quaternion(0, 0, 0, 1.0);
  4908. this.multiplyToRef(q1, result);
  4909. return result;
  4910. };
  4911. /**
  4912. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4913. * @param q1 defines the second operand
  4914. * @param result defines the target quaternion
  4915. * @returns the current quaternion
  4916. */
  4917. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4918. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4919. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4920. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4921. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4922. result.copyFromFloats(x, y, z, w);
  4923. return this;
  4924. };
  4925. /**
  4926. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4927. * @param q1 defines the second operand
  4928. * @returns the currentupdated quaternion
  4929. */
  4930. Quaternion.prototype.multiplyInPlace = function (q1) {
  4931. this.multiplyToRef(q1, this);
  4932. return this;
  4933. };
  4934. /**
  4935. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4936. * @param ref defines the target quaternion
  4937. * @returns the current quaternion
  4938. */
  4939. Quaternion.prototype.conjugateToRef = function (ref) {
  4940. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4941. return this;
  4942. };
  4943. /**
  4944. * Conjugates in place (1-q) the current quaternion
  4945. * @returns the current updated quaternion
  4946. */
  4947. Quaternion.prototype.conjugateInPlace = function () {
  4948. this.x *= -1;
  4949. this.y *= -1;
  4950. this.z *= -1;
  4951. return this;
  4952. };
  4953. /**
  4954. * Conjugates in place (1-q) the current quaternion
  4955. * @returns a new quaternion
  4956. */
  4957. Quaternion.prototype.conjugate = function () {
  4958. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4959. return result;
  4960. };
  4961. /**
  4962. * Gets length of current quaternion
  4963. * @returns the quaternion length (float)
  4964. */
  4965. Quaternion.prototype.length = function () {
  4966. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4967. };
  4968. /**
  4969. * Normalize in place the current quaternion
  4970. * @returns the current updated quaternion
  4971. */
  4972. Quaternion.prototype.normalize = function () {
  4973. var length = 1.0 / this.length();
  4974. this.x *= length;
  4975. this.y *= length;
  4976. this.z *= length;
  4977. this.w *= length;
  4978. return this;
  4979. };
  4980. /**
  4981. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4982. * @param order is a reserved parameter and is ignore for now
  4983. * @returns a new Vector3 containing the Euler angles
  4984. */
  4985. Quaternion.prototype.toEulerAngles = function (order) {
  4986. if (order === void 0) { order = "YZX"; }
  4987. var result = Vector3.Zero();
  4988. this.toEulerAnglesToRef(result, order);
  4989. return result;
  4990. };
  4991. /**
  4992. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4993. * @param result defines the vector which will be filled with the Euler angles
  4994. * @param order is a reserved parameter and is ignore for now
  4995. * @returns the current unchanged quaternion
  4996. */
  4997. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4998. if (order === void 0) { order = "YZX"; }
  4999. var qz = this.z;
  5000. var qx = this.x;
  5001. var qy = this.y;
  5002. var qw = this.w;
  5003. var sqw = qw * qw;
  5004. var sqz = qz * qz;
  5005. var sqx = qx * qx;
  5006. var sqy = qy * qy;
  5007. var zAxisY = qy * qz - qx * qw;
  5008. var limit = .4999999;
  5009. if (zAxisY < -limit) {
  5010. result.y = 2 * Math.atan2(qy, qw);
  5011. result.x = Math.PI / 2;
  5012. result.z = 0;
  5013. }
  5014. else if (zAxisY > limit) {
  5015. result.y = 2 * Math.atan2(qy, qw);
  5016. result.x = -Math.PI / 2;
  5017. result.z = 0;
  5018. }
  5019. else {
  5020. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  5021. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  5022. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  5023. }
  5024. return this;
  5025. };
  5026. /**
  5027. * Updates the given rotation matrix with the current quaternion values
  5028. * @param result defines the target matrix
  5029. * @returns the current unchanged quaternion
  5030. */
  5031. Quaternion.prototype.toRotationMatrix = function (result) {
  5032. var xx = this.x * this.x;
  5033. var yy = this.y * this.y;
  5034. var zz = this.z * this.z;
  5035. var xy = this.x * this.y;
  5036. var zw = this.z * this.w;
  5037. var zx = this.z * this.x;
  5038. var yw = this.y * this.w;
  5039. var yz = this.y * this.z;
  5040. var xw = this.x * this.w;
  5041. result.m[0] = 1.0 - (2.0 * (yy + zz));
  5042. result.m[1] = 2.0 * (xy + zw);
  5043. result.m[2] = 2.0 * (zx - yw);
  5044. result.m[3] = 0;
  5045. result.m[4] = 2.0 * (xy - zw);
  5046. result.m[5] = 1.0 - (2.0 * (zz + xx));
  5047. result.m[6] = 2.0 * (yz + xw);
  5048. result.m[7] = 0;
  5049. result.m[8] = 2.0 * (zx + yw);
  5050. result.m[9] = 2.0 * (yz - xw);
  5051. result.m[10] = 1.0 - (2.0 * (yy + xx));
  5052. result.m[11] = 0;
  5053. result.m[12] = 0;
  5054. result.m[13] = 0;
  5055. result.m[14] = 0;
  5056. result.m[15] = 1.0;
  5057. result._markAsUpdated();
  5058. return this;
  5059. };
  5060. /**
  5061. * Updates the current quaternion from the given rotation matrix values
  5062. * @param matrix defines the source matrix
  5063. * @returns the current updated quaternion
  5064. */
  5065. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  5066. Quaternion.FromRotationMatrixToRef(matrix, this);
  5067. return this;
  5068. };
  5069. // Statics
  5070. /**
  5071. * Creates a new quaternion from a rotation matrix
  5072. * @param matrix defines the source matrix
  5073. * @returns a new quaternion created from the given rotation matrix values
  5074. */
  5075. Quaternion.FromRotationMatrix = function (matrix) {
  5076. var result = new Quaternion();
  5077. Quaternion.FromRotationMatrixToRef(matrix, result);
  5078. return result;
  5079. };
  5080. /**
  5081. * Updates the given quaternion with the given rotation matrix values
  5082. * @param matrix defines the source matrix
  5083. * @param result defines the target quaternion
  5084. */
  5085. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  5086. var data = matrix.m;
  5087. var m11 = data[0], m12 = data[4], m13 = data[8];
  5088. var m21 = data[1], m22 = data[5], m23 = data[9];
  5089. var m31 = data[2], m32 = data[6], m33 = data[10];
  5090. var trace = m11 + m22 + m33;
  5091. var s;
  5092. if (trace > 0) {
  5093. s = 0.5 / Math.sqrt(trace + 1.0);
  5094. result.w = 0.25 / s;
  5095. result.x = (m32 - m23) * s;
  5096. result.y = (m13 - m31) * s;
  5097. result.z = (m21 - m12) * s;
  5098. }
  5099. else if (m11 > m22 && m11 > m33) {
  5100. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  5101. result.w = (m32 - m23) / s;
  5102. result.x = 0.25 * s;
  5103. result.y = (m12 + m21) / s;
  5104. result.z = (m13 + m31) / s;
  5105. }
  5106. else if (m22 > m33) {
  5107. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  5108. result.w = (m13 - m31) / s;
  5109. result.x = (m12 + m21) / s;
  5110. result.y = 0.25 * s;
  5111. result.z = (m23 + m32) / s;
  5112. }
  5113. else {
  5114. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  5115. result.w = (m21 - m12) / s;
  5116. result.x = (m13 + m31) / s;
  5117. result.y = (m23 + m32) / s;
  5118. result.z = 0.25 * s;
  5119. }
  5120. };
  5121. /**
  5122. * Returns the dot product (float) between the quaternions "left" and "right"
  5123. * @param left defines the left operand
  5124. * @param right defines the right operand
  5125. * @returns the dot product
  5126. */
  5127. Quaternion.Dot = function (left, right) {
  5128. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  5129. };
  5130. /**
  5131. * Checks if the two quaternions are close to each other
  5132. * @param quat0 defines the first quaternion to check
  5133. * @param quat1 defines the second quaternion to check
  5134. * @returns true if the two quaternions are close to each other
  5135. */
  5136. Quaternion.AreClose = function (quat0, quat1) {
  5137. var dot = Quaternion.Dot(quat0, quat1);
  5138. return dot >= 0;
  5139. };
  5140. /**
  5141. * Creates an empty quaternion
  5142. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  5143. */
  5144. Quaternion.Zero = function () {
  5145. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  5146. };
  5147. /**
  5148. * Inverse a given quaternion
  5149. * @param q defines the source quaternion
  5150. * @returns a new quaternion as the inverted current quaternion
  5151. */
  5152. Quaternion.Inverse = function (q) {
  5153. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  5154. };
  5155. /**
  5156. * Creates an identity quaternion
  5157. * @returns the identity quaternion
  5158. */
  5159. Quaternion.Identity = function () {
  5160. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  5161. };
  5162. /**
  5163. * Gets a boolean indicating if the given quaternion is identity
  5164. * @param quaternion defines the quaternion to check
  5165. * @returns true if the quaternion is identity
  5166. */
  5167. Quaternion.IsIdentity = function (quaternion) {
  5168. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  5169. };
  5170. /**
  5171. * Creates a quaternion from a rotation around an axis
  5172. * @param axis defines the axis to use
  5173. * @param angle defines the angle to use
  5174. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  5175. */
  5176. Quaternion.RotationAxis = function (axis, angle) {
  5177. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  5178. };
  5179. /**
  5180. * Creates a rotation around an axis and stores it into the given quaternion
  5181. * @param axis defines the axis to use
  5182. * @param angle defines the angle to use
  5183. * @param result defines the target quaternion
  5184. * @returns the target quaternion
  5185. */
  5186. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  5187. var sin = Math.sin(angle / 2);
  5188. axis.normalize();
  5189. result.w = Math.cos(angle / 2);
  5190. result.x = axis.x * sin;
  5191. result.y = axis.y * sin;
  5192. result.z = axis.z * sin;
  5193. return result;
  5194. };
  5195. /**
  5196. * Creates a new quaternion from data stored into an array
  5197. * @param array defines the data source
  5198. * @param offset defines the offset in the source array where the data starts
  5199. * @returns a new quaternion
  5200. */
  5201. Quaternion.FromArray = function (array, offset) {
  5202. if (!offset) {
  5203. offset = 0;
  5204. }
  5205. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  5206. };
  5207. /**
  5208. * Creates a new quaternion from the given Euler float angles (y, x, z)
  5209. * @param yaw defines the rotation around Y axis
  5210. * @param pitch defines the rotation around X axis
  5211. * @param roll defines the rotation around Z axis
  5212. * @returns the new quaternion
  5213. */
  5214. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  5215. var q = new Quaternion();
  5216. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  5217. return q;
  5218. };
  5219. /**
  5220. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  5221. * @param yaw defines the rotation around Y axis
  5222. * @param pitch defines the rotation around X axis
  5223. * @param roll defines the rotation around Z axis
  5224. * @param result defines the target quaternion
  5225. */
  5226. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  5227. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  5228. var halfRoll = roll * 0.5;
  5229. var halfPitch = pitch * 0.5;
  5230. var halfYaw = yaw * 0.5;
  5231. var sinRoll = Math.sin(halfRoll);
  5232. var cosRoll = Math.cos(halfRoll);
  5233. var sinPitch = Math.sin(halfPitch);
  5234. var cosPitch = Math.cos(halfPitch);
  5235. var sinYaw = Math.sin(halfYaw);
  5236. var cosYaw = Math.cos(halfYaw);
  5237. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  5238. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  5239. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  5240. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  5241. };
  5242. /**
  5243. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  5244. * @param alpha defines the rotation around first axis
  5245. * @param beta defines the rotation around second axis
  5246. * @param gamma defines the rotation around third axis
  5247. * @returns the new quaternion
  5248. */
  5249. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  5250. var result = new Quaternion();
  5251. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5252. return result;
  5253. };
  5254. /**
  5255. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5256. * @param alpha defines the rotation around first axis
  5257. * @param beta defines the rotation around second axis
  5258. * @param gamma defines the rotation around third axis
  5259. * @param result defines the target quaternion
  5260. */
  5261. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5262. // Produces a quaternion from Euler angles in the z-x-z orientation
  5263. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5264. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5265. var halfBeta = beta * 0.5;
  5266. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5267. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5268. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5269. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5270. };
  5271. /**
  5272. * 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)
  5273. * @param axis1 defines the first axis
  5274. * @param axis2 defines the second axis
  5275. * @param axis3 defines the third axis
  5276. * @returns the new quaternion
  5277. */
  5278. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5279. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5280. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5281. return quat;
  5282. };
  5283. /**
  5284. * 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
  5285. * @param axis1 defines the first axis
  5286. * @param axis2 defines the second axis
  5287. * @param axis3 defines the third axis
  5288. * @param ref defines the target quaternion
  5289. */
  5290. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5291. var rotMat = MathTmp.Matrix[0];
  5292. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5293. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5294. };
  5295. /**
  5296. * Interpolates between two quaternions
  5297. * @param left defines first quaternion
  5298. * @param right defines second quaternion
  5299. * @param amount defines the gradient to use
  5300. * @returns the new interpolated quaternion
  5301. */
  5302. Quaternion.Slerp = function (left, right, amount) {
  5303. var result = Quaternion.Identity();
  5304. Quaternion.SlerpToRef(left, right, amount, result);
  5305. return result;
  5306. };
  5307. /**
  5308. * Interpolates between two quaternions and stores it into a target quaternion
  5309. * @param left defines first quaternion
  5310. * @param right defines second quaternion
  5311. * @param amount defines the gradient to use
  5312. * @param result defines the target quaternion
  5313. */
  5314. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5315. var num2;
  5316. var num3;
  5317. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5318. var flag = false;
  5319. if (num4 < 0) {
  5320. flag = true;
  5321. num4 = -num4;
  5322. }
  5323. if (num4 > 0.999999) {
  5324. num3 = 1 - amount;
  5325. num2 = flag ? -amount : amount;
  5326. }
  5327. else {
  5328. var num5 = Math.acos(num4);
  5329. var num6 = (1.0 / Math.sin(num5));
  5330. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5331. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5332. }
  5333. result.x = (num3 * left.x) + (num2 * right.x);
  5334. result.y = (num3 * left.y) + (num2 * right.y);
  5335. result.z = (num3 * left.z) + (num2 * right.z);
  5336. result.w = (num3 * left.w) + (num2 * right.w);
  5337. };
  5338. /**
  5339. * Interpolate between two quaternions using Hermite interpolation
  5340. * @param value1 defines first quaternion
  5341. * @param tangent1 defines the incoming tangent
  5342. * @param value2 defines second quaternion
  5343. * @param tangent2 defines the outgoing tangent
  5344. * @param amount defines the target quaternion
  5345. * @returns the new interpolated quaternion
  5346. */
  5347. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5348. var squared = amount * amount;
  5349. var cubed = amount * squared;
  5350. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5351. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5352. var part3 = (cubed - (2.0 * squared)) + amount;
  5353. var part4 = cubed - squared;
  5354. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5355. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5356. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5357. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5358. return new Quaternion(x, y, z, w);
  5359. };
  5360. return Quaternion;
  5361. }());
  5362. BABYLON.Quaternion = Quaternion;
  5363. /**
  5364. * Class used to store matrix data (4x4)
  5365. */
  5366. var Matrix = /** @class */ (function () {
  5367. /**
  5368. * Creates an empty matrix (filled with zeros)
  5369. */
  5370. function Matrix() {
  5371. this._isIdentity = false;
  5372. this._isIdentityDirty = true;
  5373. /**
  5374. * Gets or sets the internal data of the matrix
  5375. */
  5376. this.m = new Float32Array(16);
  5377. this._markAsUpdated();
  5378. }
  5379. /** @hidden */
  5380. Matrix.prototype._markAsUpdated = function () {
  5381. this.updateFlag = Matrix._updateFlagSeed++;
  5382. this._isIdentityDirty = true;
  5383. };
  5384. // Properties
  5385. /**
  5386. * Check if the current matrix is indentity
  5387. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5388. * @returns true is the matrix is the identity matrix
  5389. */
  5390. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5391. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5392. if (this._isIdentityDirty) {
  5393. this._isIdentityDirty = false;
  5394. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5395. this._isIdentity = false;
  5396. }
  5397. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5398. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5399. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5400. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5401. this._isIdentity = false;
  5402. }
  5403. else {
  5404. this._isIdentity = true;
  5405. }
  5406. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5407. this._isIdentity = false;
  5408. }
  5409. }
  5410. return this._isIdentity;
  5411. };
  5412. /**
  5413. * Gets the determinant of the matrix
  5414. * @returns the matrix determinant
  5415. */
  5416. Matrix.prototype.determinant = function () {
  5417. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5418. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5419. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5420. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5421. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5422. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5423. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5424. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5425. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5426. };
  5427. // Methods
  5428. /**
  5429. * Returns the matrix as a Float32Array
  5430. * @returns the matrix underlying array
  5431. */
  5432. Matrix.prototype.toArray = function () {
  5433. return this.m;
  5434. };
  5435. /**
  5436. * Returns the matrix as a Float32Array
  5437. * @returns the matrix underlying array.
  5438. */
  5439. Matrix.prototype.asArray = function () {
  5440. return this.toArray();
  5441. };
  5442. /**
  5443. * Inverts the current matrix in place
  5444. * @returns the current inverted matrix
  5445. */
  5446. Matrix.prototype.invert = function () {
  5447. this.invertToRef(this);
  5448. return this;
  5449. };
  5450. /**
  5451. * Sets all the matrix elements to zero
  5452. * @returns the current matrix
  5453. */
  5454. Matrix.prototype.reset = function () {
  5455. for (var index = 0; index < 16; index++) {
  5456. this.m[index] = 0.0;
  5457. }
  5458. this._markAsUpdated();
  5459. return this;
  5460. };
  5461. /**
  5462. * Adds the current matrix with a second one
  5463. * @param other defines the matrix to add
  5464. * @returns a new matrix as the addition of the current matrix and the given one
  5465. */
  5466. Matrix.prototype.add = function (other) {
  5467. var result = new Matrix();
  5468. this.addToRef(other, result);
  5469. return result;
  5470. };
  5471. /**
  5472. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5473. * @param other defines the matrix to add
  5474. * @param result defines the target matrix
  5475. * @returns the current matrix
  5476. */
  5477. Matrix.prototype.addToRef = function (other, result) {
  5478. for (var index = 0; index < 16; index++) {
  5479. result.m[index] = this.m[index] + other.m[index];
  5480. }
  5481. result._markAsUpdated();
  5482. return this;
  5483. };
  5484. /**
  5485. * Adds in place the given matrix to the current matrix
  5486. * @param other defines the second operand
  5487. * @returns the current updated matrix
  5488. */
  5489. Matrix.prototype.addToSelf = function (other) {
  5490. for (var index = 0; index < 16; index++) {
  5491. this.m[index] += other.m[index];
  5492. }
  5493. this._markAsUpdated();
  5494. return this;
  5495. };
  5496. /**
  5497. * Sets the given matrix to the current inverted Matrix
  5498. * @param other defines the target matrix
  5499. * @returns the unmodified current matrix
  5500. */
  5501. Matrix.prototype.invertToRef = function (other) {
  5502. var l1 = this.m[0];
  5503. var l2 = this.m[1];
  5504. var l3 = this.m[2];
  5505. var l4 = this.m[3];
  5506. var l5 = this.m[4];
  5507. var l6 = this.m[5];
  5508. var l7 = this.m[6];
  5509. var l8 = this.m[7];
  5510. var l9 = this.m[8];
  5511. var l10 = this.m[9];
  5512. var l11 = this.m[10];
  5513. var l12 = this.m[11];
  5514. var l13 = this.m[12];
  5515. var l14 = this.m[13];
  5516. var l15 = this.m[14];
  5517. var l16 = this.m[15];
  5518. var l17 = (l11 * l16) - (l12 * l15);
  5519. var l18 = (l10 * l16) - (l12 * l14);
  5520. var l19 = (l10 * l15) - (l11 * l14);
  5521. var l20 = (l9 * l16) - (l12 * l13);
  5522. var l21 = (l9 * l15) - (l11 * l13);
  5523. var l22 = (l9 * l14) - (l10 * l13);
  5524. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5525. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5526. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5527. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5528. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5529. var l28 = (l7 * l16) - (l8 * l15);
  5530. var l29 = (l6 * l16) - (l8 * l14);
  5531. var l30 = (l6 * l15) - (l7 * l14);
  5532. var l31 = (l5 * l16) - (l8 * l13);
  5533. var l32 = (l5 * l15) - (l7 * l13);
  5534. var l33 = (l5 * l14) - (l6 * l13);
  5535. var l34 = (l7 * l12) - (l8 * l11);
  5536. var l35 = (l6 * l12) - (l8 * l10);
  5537. var l36 = (l6 * l11) - (l7 * l10);
  5538. var l37 = (l5 * l12) - (l8 * l9);
  5539. var l38 = (l5 * l11) - (l7 * l9);
  5540. var l39 = (l5 * l10) - (l6 * l9);
  5541. other.m[0] = l23 * l27;
  5542. other.m[4] = l24 * l27;
  5543. other.m[8] = l25 * l27;
  5544. other.m[12] = l26 * l27;
  5545. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5546. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5547. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5548. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5549. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5550. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5551. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5552. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5553. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5554. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5555. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5556. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5557. other._markAsUpdated();
  5558. return this;
  5559. };
  5560. /**
  5561. * Inserts the translation vector (using 3 floats) in the current matrix
  5562. * @param x defines the 1st component of the translation
  5563. * @param y defines the 2nd component of the translation
  5564. * @param z defines the 3rd component of the translation
  5565. * @returns the current updated matrix
  5566. */
  5567. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5568. this.m[12] = x;
  5569. this.m[13] = y;
  5570. this.m[14] = z;
  5571. this._markAsUpdated();
  5572. return this;
  5573. };
  5574. /**
  5575. * Inserts the translation vector in the current matrix
  5576. * @param vector3 defines the translation to insert
  5577. * @returns the current updated matrix
  5578. */
  5579. Matrix.prototype.setTranslation = function (vector3) {
  5580. this.m[12] = vector3.x;
  5581. this.m[13] = vector3.y;
  5582. this.m[14] = vector3.z;
  5583. this._markAsUpdated();
  5584. return this;
  5585. };
  5586. /**
  5587. * Gets the translation value of the current matrix
  5588. * @returns a new Vector3 as the extracted translation from the matrix
  5589. */
  5590. Matrix.prototype.getTranslation = function () {
  5591. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5592. };
  5593. /**
  5594. * Fill a Vector3 with the extracted translation from the matrix
  5595. * @param result defines the Vector3 where to store the translation
  5596. * @returns the current matrix
  5597. */
  5598. Matrix.prototype.getTranslationToRef = function (result) {
  5599. result.x = this.m[12];
  5600. result.y = this.m[13];
  5601. result.z = this.m[14];
  5602. return this;
  5603. };
  5604. /**
  5605. * Remove rotation and scaling part from the matrix
  5606. * @returns the updated matrix
  5607. */
  5608. Matrix.prototype.removeRotationAndScaling = function () {
  5609. this.setRowFromFloats(0, 1, 0, 0, 0);
  5610. this.setRowFromFloats(1, 0, 1, 0, 0);
  5611. this.setRowFromFloats(2, 0, 0, 1, 0);
  5612. return this;
  5613. };
  5614. /**
  5615. * Multiply two matrices
  5616. * @param other defines the second operand
  5617. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5618. */
  5619. Matrix.prototype.multiply = function (other) {
  5620. var result = new Matrix();
  5621. this.multiplyToRef(other, result);
  5622. return result;
  5623. };
  5624. /**
  5625. * Copy the current matrix from the given one
  5626. * @param other defines the source matrix
  5627. * @returns the current updated matrix
  5628. */
  5629. Matrix.prototype.copyFrom = function (other) {
  5630. for (var index = 0; index < 16; index++) {
  5631. this.m[index] = other.m[index];
  5632. }
  5633. this._markAsUpdated();
  5634. return this;
  5635. };
  5636. /**
  5637. * Populates the given array from the starting index with the current matrix values
  5638. * @param array defines the target array
  5639. * @param offset defines the offset in the target array where to start storing values
  5640. * @returns the current matrix
  5641. */
  5642. Matrix.prototype.copyToArray = function (array, offset) {
  5643. if (offset === void 0) { offset = 0; }
  5644. for (var index = 0; index < 16; index++) {
  5645. array[offset + index] = this.m[index];
  5646. }
  5647. return this;
  5648. };
  5649. /**
  5650. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5651. * @param other defines the second operand
  5652. * @param result defines the matrix where to store the multiplication
  5653. * @returns the current matrix
  5654. */
  5655. Matrix.prototype.multiplyToRef = function (other, result) {
  5656. this.multiplyToArray(other, result.m, 0);
  5657. result._markAsUpdated();
  5658. return this;
  5659. };
  5660. /**
  5661. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5662. * @param other defines the second operand
  5663. * @param result defines the array where to store the multiplication
  5664. * @param offset defines the offset in the target array where to start storing values
  5665. * @returns the current matrix
  5666. */
  5667. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5668. var tm0 = this.m[0];
  5669. var tm1 = this.m[1];
  5670. var tm2 = this.m[2];
  5671. var tm3 = this.m[3];
  5672. var tm4 = this.m[4];
  5673. var tm5 = this.m[5];
  5674. var tm6 = this.m[6];
  5675. var tm7 = this.m[7];
  5676. var tm8 = this.m[8];
  5677. var tm9 = this.m[9];
  5678. var tm10 = this.m[10];
  5679. var tm11 = this.m[11];
  5680. var tm12 = this.m[12];
  5681. var tm13 = this.m[13];
  5682. var tm14 = this.m[14];
  5683. var tm15 = this.m[15];
  5684. var om0 = other.m[0];
  5685. var om1 = other.m[1];
  5686. var om2 = other.m[2];
  5687. var om3 = other.m[3];
  5688. var om4 = other.m[4];
  5689. var om5 = other.m[5];
  5690. var om6 = other.m[6];
  5691. var om7 = other.m[7];
  5692. var om8 = other.m[8];
  5693. var om9 = other.m[9];
  5694. var om10 = other.m[10];
  5695. var om11 = other.m[11];
  5696. var om12 = other.m[12];
  5697. var om13 = other.m[13];
  5698. var om14 = other.m[14];
  5699. var om15 = other.m[15];
  5700. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5701. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5702. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5703. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5704. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5705. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5706. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5707. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5708. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5709. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5710. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5711. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5712. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5713. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5714. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5715. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5716. return this;
  5717. };
  5718. /**
  5719. * Check equality between this matrix and a second one
  5720. * @param value defines the second matrix to compare
  5721. * @returns true is the current matrix and the given one values are strictly equal
  5722. */
  5723. Matrix.prototype.equals = function (value) {
  5724. return value &&
  5725. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5726. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5727. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5728. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5729. };
  5730. /**
  5731. * Clone the current matrix
  5732. * @returns a new matrix from the current matrix
  5733. */
  5734. Matrix.prototype.clone = function () {
  5735. 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]);
  5736. };
  5737. /**
  5738. * Returns the name of the current matrix class
  5739. * @returns the string "Matrix"
  5740. */
  5741. Matrix.prototype.getClassName = function () {
  5742. return "Matrix";
  5743. };
  5744. /**
  5745. * Gets the hash code of the current matrix
  5746. * @returns the hash code
  5747. */
  5748. Matrix.prototype.getHashCode = function () {
  5749. var hash = this.m[0] || 0;
  5750. for (var i = 1; i < 16; i++) {
  5751. hash = (hash * 397) ^ (this.m[i] || 0);
  5752. }
  5753. return hash;
  5754. };
  5755. /**
  5756. * Decomposes the current Matrix into a translation, rotation and scaling components
  5757. * @param scale defines the scale vector3 given as a reference to update
  5758. * @param rotation defines the rotation quaternion given as a reference to update
  5759. * @param translation defines the translation vector3 given as a reference to update
  5760. * @returns true if operation was successful
  5761. */
  5762. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5763. if (translation) {
  5764. translation.x = this.m[12];
  5765. translation.y = this.m[13];
  5766. translation.z = this.m[14];
  5767. }
  5768. scale = scale || MathTmp.Vector3[0];
  5769. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5770. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5771. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5772. if (this.determinant() <= 0) {
  5773. scale.y *= -1;
  5774. }
  5775. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5776. if (rotation) {
  5777. rotation.x = 0;
  5778. rotation.y = 0;
  5779. rotation.z = 0;
  5780. rotation.w = 1;
  5781. }
  5782. return false;
  5783. }
  5784. if (rotation) {
  5785. 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]);
  5786. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5787. }
  5788. return true;
  5789. };
  5790. /**
  5791. * Gets specific row of the matrix
  5792. * @param index defines the number of the row to get
  5793. * @returns the index-th row of the current matrix as a new Vector4
  5794. */
  5795. Matrix.prototype.getRow = function (index) {
  5796. if (index < 0 || index > 3) {
  5797. return null;
  5798. }
  5799. var i = index * 4;
  5800. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5801. };
  5802. /**
  5803. * Sets the index-th row of the current matrix to the vector4 values
  5804. * @param index defines the number of the row to set
  5805. * @param row defines the target vector4
  5806. * @returns the updated current matrix
  5807. */
  5808. Matrix.prototype.setRow = function (index, row) {
  5809. if (index < 0 || index > 3) {
  5810. return this;
  5811. }
  5812. var i = index * 4;
  5813. this.m[i + 0] = row.x;
  5814. this.m[i + 1] = row.y;
  5815. this.m[i + 2] = row.z;
  5816. this.m[i + 3] = row.w;
  5817. this._markAsUpdated();
  5818. return this;
  5819. };
  5820. /**
  5821. * Compute the transpose of the matrix
  5822. * @returns the new transposed matrix
  5823. */
  5824. Matrix.prototype.transpose = function () {
  5825. return Matrix.Transpose(this);
  5826. };
  5827. /**
  5828. * Compute the transpose of the matrix and store it in a given matrix
  5829. * @param result defines the target matrix
  5830. * @returns the current matrix
  5831. */
  5832. Matrix.prototype.transposeToRef = function (result) {
  5833. Matrix.TransposeToRef(this, result);
  5834. return this;
  5835. };
  5836. /**
  5837. * Sets the index-th row of the current matrix with the given 4 x float values
  5838. * @param index defines the row index
  5839. * @param x defines the x component to set
  5840. * @param y defines the y component to set
  5841. * @param z defines the z component to set
  5842. * @param w defines the w component to set
  5843. * @returns the updated current matrix
  5844. */
  5845. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5846. if (index < 0 || index > 3) {
  5847. return this;
  5848. }
  5849. var i = index * 4;
  5850. this.m[i + 0] = x;
  5851. this.m[i + 1] = y;
  5852. this.m[i + 2] = z;
  5853. this.m[i + 3] = w;
  5854. this._markAsUpdated();
  5855. return this;
  5856. };
  5857. /**
  5858. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5859. * @param scale defines the scale factor
  5860. * @returns a new matrix
  5861. */
  5862. Matrix.prototype.scale = function (scale) {
  5863. var result = new Matrix();
  5864. this.scaleToRef(scale, result);
  5865. return result;
  5866. };
  5867. /**
  5868. * Scale the current matrix values by a factor to a given result matrix
  5869. * @param scale defines the scale factor
  5870. * @param result defines the matrix to store the result
  5871. * @returns the current matrix
  5872. */
  5873. Matrix.prototype.scaleToRef = function (scale, result) {
  5874. for (var index = 0; index < 16; index++) {
  5875. result.m[index] = this.m[index] * scale;
  5876. }
  5877. result._markAsUpdated();
  5878. return this;
  5879. };
  5880. /**
  5881. * Scale the current matrix values by a factor and add the result to a given matrix
  5882. * @param scale defines the scale factor
  5883. * @param result defines the Matrix to store the result
  5884. * @returns the current matrix
  5885. */
  5886. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5887. for (var index = 0; index < 16; index++) {
  5888. result.m[index] += this.m[index] * scale;
  5889. }
  5890. result._markAsUpdated();
  5891. return this;
  5892. };
  5893. /**
  5894. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5895. * @param ref matrix to store the result
  5896. */
  5897. Matrix.prototype.toNormalMatrix = function (ref) {
  5898. this.invertToRef(ref);
  5899. ref.transpose();
  5900. var m = ref.m;
  5901. 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);
  5902. };
  5903. /**
  5904. * Gets only rotation part of the current matrix
  5905. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5906. */
  5907. Matrix.prototype.getRotationMatrix = function () {
  5908. var result = Matrix.Identity();
  5909. this.getRotationMatrixToRef(result);
  5910. return result;
  5911. };
  5912. /**
  5913. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5914. * @param result defines the target matrix to store data to
  5915. * @returns the current matrix
  5916. */
  5917. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5918. var m = this.m;
  5919. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5920. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5921. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5922. if (this.determinant() <= 0) {
  5923. sy *= -1;
  5924. }
  5925. if (sx === 0 || sy === 0 || sz === 0) {
  5926. Matrix.IdentityToRef(result);
  5927. }
  5928. else {
  5929. 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);
  5930. }
  5931. return this;
  5932. };
  5933. // Statics
  5934. /**
  5935. * Creates a matrix from an array
  5936. * @param array defines the source array
  5937. * @param offset defines an offset in the source array
  5938. * @returns a new Matrix set from the starting index of the given array
  5939. */
  5940. Matrix.FromArray = function (array, offset) {
  5941. var result = new Matrix();
  5942. if (!offset) {
  5943. offset = 0;
  5944. }
  5945. Matrix.FromArrayToRef(array, offset, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Copy the content of an array into a given matrix
  5950. * @param array defines the source array
  5951. * @param offset defines an offset in the source array
  5952. * @param result defines the target matrix
  5953. */
  5954. Matrix.FromArrayToRef = function (array, offset, result) {
  5955. for (var index = 0; index < 16; index++) {
  5956. result.m[index] = array[index + offset];
  5957. }
  5958. result._markAsUpdated();
  5959. };
  5960. /**
  5961. * Stores an array into a matrix after having multiplied each component by a given factor
  5962. * @param array defines the source array
  5963. * @param offset defines the offset in the source array
  5964. * @param scale defines the scaling factor
  5965. * @param result defines the target matrix
  5966. */
  5967. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5968. for (var index = 0; index < 16; index++) {
  5969. result.m[index] = array[index + offset] * scale;
  5970. }
  5971. result._markAsUpdated();
  5972. };
  5973. /**
  5974. * Stores a list of values (16) inside a given matrix
  5975. * @param initialM11 defines 1st value of 1st row
  5976. * @param initialM12 defines 2nd value of 1st row
  5977. * @param initialM13 defines 3rd value of 1st row
  5978. * @param initialM14 defines 4th value of 1st row
  5979. * @param initialM21 defines 1st value of 2nd row
  5980. * @param initialM22 defines 2nd value of 2nd row
  5981. * @param initialM23 defines 3rd value of 2nd row
  5982. * @param initialM24 defines 4th value of 2nd row
  5983. * @param initialM31 defines 1st value of 3rd row
  5984. * @param initialM32 defines 2nd value of 3rd row
  5985. * @param initialM33 defines 3rd value of 3rd row
  5986. * @param initialM34 defines 4th value of 3rd row
  5987. * @param initialM41 defines 1st value of 4th row
  5988. * @param initialM42 defines 2nd value of 4th row
  5989. * @param initialM43 defines 3rd value of 4th row
  5990. * @param initialM44 defines 4th value of 4th row
  5991. * @param result defines the target matrix
  5992. */
  5993. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5994. result.m[0] = initialM11;
  5995. result.m[1] = initialM12;
  5996. result.m[2] = initialM13;
  5997. result.m[3] = initialM14;
  5998. result.m[4] = initialM21;
  5999. result.m[5] = initialM22;
  6000. result.m[6] = initialM23;
  6001. result.m[7] = initialM24;
  6002. result.m[8] = initialM31;
  6003. result.m[9] = initialM32;
  6004. result.m[10] = initialM33;
  6005. result.m[11] = initialM34;
  6006. result.m[12] = initialM41;
  6007. result.m[13] = initialM42;
  6008. result.m[14] = initialM43;
  6009. result.m[15] = initialM44;
  6010. result._markAsUpdated();
  6011. };
  6012. Object.defineProperty(Matrix, "IdentityReadOnly", {
  6013. /**
  6014. * Gets an identity matrix that must not be updated
  6015. */
  6016. get: function () {
  6017. return Matrix._identityReadOnly;
  6018. },
  6019. enumerable: true,
  6020. configurable: true
  6021. });
  6022. /**
  6023. * Creates new matrix from a list of values (16)
  6024. * @param initialM11 defines 1st value of 1st row
  6025. * @param initialM12 defines 2nd value of 1st row
  6026. * @param initialM13 defines 3rd value of 1st row
  6027. * @param initialM14 defines 4th value of 1st row
  6028. * @param initialM21 defines 1st value of 2nd row
  6029. * @param initialM22 defines 2nd value of 2nd row
  6030. * @param initialM23 defines 3rd value of 2nd row
  6031. * @param initialM24 defines 4th value of 2nd row
  6032. * @param initialM31 defines 1st value of 3rd row
  6033. * @param initialM32 defines 2nd value of 3rd row
  6034. * @param initialM33 defines 3rd value of 3rd row
  6035. * @param initialM34 defines 4th value of 3rd row
  6036. * @param initialM41 defines 1st value of 4th row
  6037. * @param initialM42 defines 2nd value of 4th row
  6038. * @param initialM43 defines 3rd value of 4th row
  6039. * @param initialM44 defines 4th value of 4th row
  6040. * @returns the new matrix
  6041. */
  6042. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  6043. var result = new Matrix();
  6044. result.m[0] = initialM11;
  6045. result.m[1] = initialM12;
  6046. result.m[2] = initialM13;
  6047. result.m[3] = initialM14;
  6048. result.m[4] = initialM21;
  6049. result.m[5] = initialM22;
  6050. result.m[6] = initialM23;
  6051. result.m[7] = initialM24;
  6052. result.m[8] = initialM31;
  6053. result.m[9] = initialM32;
  6054. result.m[10] = initialM33;
  6055. result.m[11] = initialM34;
  6056. result.m[12] = initialM41;
  6057. result.m[13] = initialM42;
  6058. result.m[14] = initialM43;
  6059. result.m[15] = initialM44;
  6060. return result;
  6061. };
  6062. /**
  6063. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6064. * @param scale defines the scale vector3
  6065. * @param rotation defines the rotation quaternion
  6066. * @param translation defines the translation vector3
  6067. * @returns a new matrix
  6068. */
  6069. Matrix.Compose = function (scale, rotation, translation) {
  6070. var result = Matrix.Identity();
  6071. Matrix.ComposeToRef(scale, rotation, translation, result);
  6072. return result;
  6073. };
  6074. /**
  6075. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  6076. * @param scale defines the scale vector3
  6077. * @param rotation defines the rotation quaternion
  6078. * @param translation defines the translation vector3
  6079. * @param result defines the target matrix
  6080. */
  6081. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  6082. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  6083. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  6084. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  6085. result.setTranslation(translation);
  6086. };
  6087. /**
  6088. * Creates a new identity matrix
  6089. * @returns a new identity matrix
  6090. */
  6091. Matrix.Identity = function () {
  6092. 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);
  6093. };
  6094. /**
  6095. * Creates a new identity matrix and stores the result in a given matrix
  6096. * @param result defines the target matrix
  6097. */
  6098. Matrix.IdentityToRef = function (result) {
  6099. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  6100. };
  6101. /**
  6102. * Creates a new zero matrix
  6103. * @returns a new zero matrix
  6104. */
  6105. Matrix.Zero = function () {
  6106. 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);
  6107. };
  6108. /**
  6109. * Creates a new rotation matrix for "angle" radians around the X axis
  6110. * @param angle defines the angle (in radians) to use
  6111. * @return the new matrix
  6112. */
  6113. Matrix.RotationX = function (angle) {
  6114. var result = new Matrix();
  6115. Matrix.RotationXToRef(angle, result);
  6116. return result;
  6117. };
  6118. /**
  6119. * Creates a new matrix as the invert of a given matrix
  6120. * @param source defines the source matrix
  6121. * @returns the new matrix
  6122. */
  6123. Matrix.Invert = function (source) {
  6124. var result = new Matrix();
  6125. source.invertToRef(result);
  6126. return result;
  6127. };
  6128. /**
  6129. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  6130. * @param angle defines the angle (in radians) to use
  6131. * @param result defines the target matrix
  6132. */
  6133. Matrix.RotationXToRef = function (angle, result) {
  6134. var s = Math.sin(angle);
  6135. var c = Math.cos(angle);
  6136. result.m[0] = 1.0;
  6137. result.m[15] = 1.0;
  6138. result.m[5] = c;
  6139. result.m[10] = c;
  6140. result.m[9] = -s;
  6141. result.m[6] = s;
  6142. result.m[1] = 0.0;
  6143. result.m[2] = 0.0;
  6144. result.m[3] = 0.0;
  6145. result.m[4] = 0.0;
  6146. result.m[7] = 0.0;
  6147. result.m[8] = 0.0;
  6148. result.m[11] = 0.0;
  6149. result.m[12] = 0.0;
  6150. result.m[13] = 0.0;
  6151. result.m[14] = 0.0;
  6152. result._markAsUpdated();
  6153. };
  6154. /**
  6155. * Creates a new rotation matrix for "angle" radians around the Y axis
  6156. * @param angle defines the angle (in radians) to use
  6157. * @return the new matrix
  6158. */
  6159. Matrix.RotationY = function (angle) {
  6160. var result = new Matrix();
  6161. Matrix.RotationYToRef(angle, result);
  6162. return result;
  6163. };
  6164. /**
  6165. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  6166. * @param angle defines the angle (in radians) to use
  6167. * @param result defines the target matrix
  6168. */
  6169. Matrix.RotationYToRef = function (angle, result) {
  6170. var s = Math.sin(angle);
  6171. var c = Math.cos(angle);
  6172. result.m[5] = 1.0;
  6173. result.m[15] = 1.0;
  6174. result.m[0] = c;
  6175. result.m[2] = -s;
  6176. result.m[8] = s;
  6177. result.m[10] = c;
  6178. result.m[1] = 0.0;
  6179. result.m[3] = 0.0;
  6180. result.m[4] = 0.0;
  6181. result.m[6] = 0.0;
  6182. result.m[7] = 0.0;
  6183. result.m[9] = 0.0;
  6184. result.m[11] = 0.0;
  6185. result.m[12] = 0.0;
  6186. result.m[13] = 0.0;
  6187. result.m[14] = 0.0;
  6188. result._markAsUpdated();
  6189. };
  6190. /**
  6191. * Creates a new rotation matrix for "angle" radians around the Z axis
  6192. * @param angle defines the angle (in radians) to use
  6193. * @return the new matrix
  6194. */
  6195. Matrix.RotationZ = function (angle) {
  6196. var result = new Matrix();
  6197. Matrix.RotationZToRef(angle, result);
  6198. return result;
  6199. };
  6200. /**
  6201. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  6202. * @param angle defines the angle (in radians) to use
  6203. * @param result defines the target matrix
  6204. */
  6205. Matrix.RotationZToRef = function (angle, result) {
  6206. var s = Math.sin(angle);
  6207. var c = Math.cos(angle);
  6208. result.m[10] = 1.0;
  6209. result.m[15] = 1.0;
  6210. result.m[0] = c;
  6211. result.m[1] = s;
  6212. result.m[4] = -s;
  6213. result.m[5] = c;
  6214. result.m[2] = 0.0;
  6215. result.m[3] = 0.0;
  6216. result.m[6] = 0.0;
  6217. result.m[7] = 0.0;
  6218. result.m[8] = 0.0;
  6219. result.m[9] = 0.0;
  6220. result.m[11] = 0.0;
  6221. result.m[12] = 0.0;
  6222. result.m[13] = 0.0;
  6223. result.m[14] = 0.0;
  6224. result._markAsUpdated();
  6225. };
  6226. /**
  6227. * Creates a new rotation matrix for "angle" radians around the given axis
  6228. * @param axis defines the axis to use
  6229. * @param angle defines the angle (in radians) to use
  6230. * @return the new matrix
  6231. */
  6232. Matrix.RotationAxis = function (axis, angle) {
  6233. var result = Matrix.Zero();
  6234. Matrix.RotationAxisToRef(axis, angle, result);
  6235. return result;
  6236. };
  6237. /**
  6238. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  6239. * @param axis defines the axis to use
  6240. * @param angle defines the angle (in radians) to use
  6241. * @param result defines the target matrix
  6242. */
  6243. Matrix.RotationAxisToRef = function (axis, angle, result) {
  6244. var s = Math.sin(-angle);
  6245. var c = Math.cos(-angle);
  6246. var c1 = 1 - c;
  6247. axis.normalize();
  6248. result.m[0] = (axis.x * axis.x) * c1 + c;
  6249. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  6250. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  6251. result.m[3] = 0.0;
  6252. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6253. result.m[5] = (axis.y * axis.y) * c1 + c;
  6254. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6255. result.m[7] = 0.0;
  6256. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6257. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6258. result.m[10] = (axis.z * axis.z) * c1 + c;
  6259. result.m[11] = 0.0;
  6260. result.m[15] = 1.0;
  6261. result._markAsUpdated();
  6262. };
  6263. /**
  6264. * Creates a rotation matrix
  6265. * @param yaw defines the yaw angle in radians (Y axis)
  6266. * @param pitch defines the pitch angle in radians (X axis)
  6267. * @param roll defines the roll angle in radians (X axis)
  6268. * @returns the new rotation matrix
  6269. */
  6270. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6271. var result = new Matrix();
  6272. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6273. return result;
  6274. };
  6275. /**
  6276. * Creates a rotation matrix and stores it in a given matrix
  6277. * @param yaw defines the yaw angle in radians (Y axis)
  6278. * @param pitch defines the pitch angle in radians (X axis)
  6279. * @param roll defines the roll angle in radians (X axis)
  6280. * @param result defines the target matrix
  6281. */
  6282. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6283. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6284. this._tempQuaternion.toRotationMatrix(result);
  6285. };
  6286. /**
  6287. * Creates a scaling matrix
  6288. * @param x defines the scale factor on X axis
  6289. * @param y defines the scale factor on Y axis
  6290. * @param z defines the scale factor on Z axis
  6291. * @returns the new matrix
  6292. */
  6293. Matrix.Scaling = function (x, y, z) {
  6294. var result = Matrix.Zero();
  6295. Matrix.ScalingToRef(x, y, z, result);
  6296. return result;
  6297. };
  6298. /**
  6299. * Creates a scaling matrix and stores it in a given matrix
  6300. * @param x defines the scale factor on X axis
  6301. * @param y defines the scale factor on Y axis
  6302. * @param z defines the scale factor on Z axis
  6303. * @param result defines the target matrix
  6304. */
  6305. Matrix.ScalingToRef = function (x, y, z, result) {
  6306. result.m[0] = x;
  6307. result.m[1] = 0.0;
  6308. result.m[2] = 0.0;
  6309. result.m[3] = 0.0;
  6310. result.m[4] = 0.0;
  6311. result.m[5] = y;
  6312. result.m[6] = 0.0;
  6313. result.m[7] = 0.0;
  6314. result.m[8] = 0.0;
  6315. result.m[9] = 0.0;
  6316. result.m[10] = z;
  6317. result.m[11] = 0.0;
  6318. result.m[12] = 0.0;
  6319. result.m[13] = 0.0;
  6320. result.m[14] = 0.0;
  6321. result.m[15] = 1.0;
  6322. result._markAsUpdated();
  6323. };
  6324. /**
  6325. * Creates a translation matrix
  6326. * @param x defines the translation on X axis
  6327. * @param y defines the translation on Y axis
  6328. * @param z defines the translationon Z axis
  6329. * @returns the new matrix
  6330. */
  6331. Matrix.Translation = function (x, y, z) {
  6332. var result = Matrix.Identity();
  6333. Matrix.TranslationToRef(x, y, z, result);
  6334. return result;
  6335. };
  6336. /**
  6337. * Creates a translation matrix and stores it in a given matrix
  6338. * @param x defines the translation on X axis
  6339. * @param y defines the translation on Y axis
  6340. * @param z defines the translationon Z axis
  6341. * @param result defines the target matrix
  6342. */
  6343. Matrix.TranslationToRef = function (x, y, z, result) {
  6344. 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);
  6345. };
  6346. /**
  6347. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6348. * @param startValue defines the start value
  6349. * @param endValue defines the end value
  6350. * @param gradient defines the gradient factor
  6351. * @returns the new matrix
  6352. */
  6353. Matrix.Lerp = function (startValue, endValue, gradient) {
  6354. var result = Matrix.Zero();
  6355. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6356. return result;
  6357. };
  6358. /**
  6359. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6360. * @param startValue defines the start value
  6361. * @param endValue defines the end value
  6362. * @param gradient defines the gradient factor
  6363. * @param result defines the Matrix object where to store data
  6364. */
  6365. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6366. for (var index = 0; index < 16; index++) {
  6367. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6368. }
  6369. result._markAsUpdated();
  6370. };
  6371. /**
  6372. * Builds a new matrix whose values are computed by:
  6373. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6374. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6375. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6376. * @param startValue defines the first matrix
  6377. * @param endValue defines the second matrix
  6378. * @param gradient defines the gradient between the two matrices
  6379. * @returns the new matrix
  6380. */
  6381. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6382. var result = Matrix.Zero();
  6383. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6384. return result;
  6385. };
  6386. /**
  6387. * Update a matrix to values which are computed by:
  6388. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6389. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6390. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6391. * @param startValue defines the first matrix
  6392. * @param endValue defines the second matrix
  6393. * @param gradient defines the gradient between the two matrices
  6394. * @param result defines the target matrix
  6395. */
  6396. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6397. var startScale = MathTmp.Vector3[0];
  6398. var startRotation = MathTmp.Quaternion[0];
  6399. var startTranslation = MathTmp.Vector3[1];
  6400. startValue.decompose(startScale, startRotation, startTranslation);
  6401. var endScale = MathTmp.Vector3[2];
  6402. var endRotation = MathTmp.Quaternion[1];
  6403. var endTranslation = MathTmp.Vector3[3];
  6404. endValue.decompose(endScale, endRotation, endTranslation);
  6405. var resultScale = MathTmp.Vector3[4];
  6406. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6407. var resultRotation = MathTmp.Quaternion[2];
  6408. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6409. var resultTranslation = MathTmp.Vector3[5];
  6410. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6411. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6412. };
  6413. /**
  6414. * 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"
  6415. * This function works in left handed mode
  6416. * @param eye defines the final position of the entity
  6417. * @param target defines where the entity should look at
  6418. * @param up defines the up vector for the entity
  6419. * @returns the new matrix
  6420. */
  6421. Matrix.LookAtLH = function (eye, target, up) {
  6422. var result = Matrix.Zero();
  6423. Matrix.LookAtLHToRef(eye, target, up, result);
  6424. return result;
  6425. };
  6426. /**
  6427. * 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".
  6428. * This function works in left handed mode
  6429. * @param eye defines the final position of the entity
  6430. * @param target defines where the entity should look at
  6431. * @param up defines the up vector for the entity
  6432. * @param result defines the target matrix
  6433. */
  6434. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6435. // Z axis
  6436. target.subtractToRef(eye, this._zAxis);
  6437. this._zAxis.normalize();
  6438. // X axis
  6439. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6440. if (this._xAxis.lengthSquared() === 0) {
  6441. this._xAxis.x = 1.0;
  6442. }
  6443. else {
  6444. this._xAxis.normalize();
  6445. }
  6446. // Y axis
  6447. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6448. this._yAxis.normalize();
  6449. // Eye angles
  6450. var ex = -Vector3.Dot(this._xAxis, eye);
  6451. var ey = -Vector3.Dot(this._yAxis, eye);
  6452. var ez = -Vector3.Dot(this._zAxis, eye);
  6453. 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);
  6454. };
  6455. /**
  6456. * 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"
  6457. * This function works in right handed mode
  6458. * @param eye defines the final position of the entity
  6459. * @param target defines where the entity should look at
  6460. * @param up defines the up vector for the entity
  6461. * @returns the new matrix
  6462. */
  6463. Matrix.LookAtRH = function (eye, target, up) {
  6464. var result = Matrix.Zero();
  6465. Matrix.LookAtRHToRef(eye, target, up, result);
  6466. return result;
  6467. };
  6468. /**
  6469. * 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".
  6470. * This function works in right handed mode
  6471. * @param eye defines the final position of the entity
  6472. * @param target defines where the entity should look at
  6473. * @param up defines the up vector for the entity
  6474. * @param result defines the target matrix
  6475. */
  6476. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6477. // Z axis
  6478. eye.subtractToRef(target, this._zAxis);
  6479. this._zAxis.normalize();
  6480. // X axis
  6481. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6482. if (this._xAxis.lengthSquared() === 0) {
  6483. this._xAxis.x = 1.0;
  6484. }
  6485. else {
  6486. this._xAxis.normalize();
  6487. }
  6488. // Y axis
  6489. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6490. this._yAxis.normalize();
  6491. // Eye angles
  6492. var ex = -Vector3.Dot(this._xAxis, eye);
  6493. var ey = -Vector3.Dot(this._yAxis, eye);
  6494. var ez = -Vector3.Dot(this._zAxis, eye);
  6495. 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);
  6496. };
  6497. /**
  6498. * Create a left-handed orthographic projection matrix
  6499. * @param width defines the viewport width
  6500. * @param height defines the viewport height
  6501. * @param znear defines the near clip plane
  6502. * @param zfar defines the far clip plane
  6503. * @returns a new matrix as a left-handed orthographic projection matrix
  6504. */
  6505. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6506. var matrix = Matrix.Zero();
  6507. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6508. return matrix;
  6509. };
  6510. /**
  6511. * Store a left-handed orthographic projection to a given matrix
  6512. * @param width defines the viewport width
  6513. * @param height defines the viewport height
  6514. * @param znear defines the near clip plane
  6515. * @param zfar defines the far clip plane
  6516. * @param result defines the target matrix
  6517. */
  6518. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6519. var n = znear;
  6520. var f = zfar;
  6521. var a = 2.0 / width;
  6522. var b = 2.0 / height;
  6523. var c = 2.0 / (f - n);
  6524. var d = -(f + n) / (f - n);
  6525. 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);
  6526. };
  6527. /**
  6528. * Create a left-handed orthographic projection matrix
  6529. * @param left defines the viewport left coordinate
  6530. * @param right defines the viewport right coordinate
  6531. * @param bottom defines the viewport bottom coordinate
  6532. * @param top defines the viewport top coordinate
  6533. * @param znear defines the near clip plane
  6534. * @param zfar defines the far clip plane
  6535. * @returns a new matrix as a left-handed orthographic projection matrix
  6536. */
  6537. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6538. var matrix = Matrix.Zero();
  6539. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6540. return matrix;
  6541. };
  6542. /**
  6543. * Stores a left-handed orthographic projection into a given matrix
  6544. * @param left defines the viewport left coordinate
  6545. * @param right defines the viewport right coordinate
  6546. * @param bottom defines the viewport bottom coordinate
  6547. * @param top defines the viewport top coordinate
  6548. * @param znear defines the near clip plane
  6549. * @param zfar defines the far clip plane
  6550. * @param result defines the target matrix
  6551. */
  6552. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6553. var n = znear;
  6554. var f = zfar;
  6555. var a = 2.0 / (right - left);
  6556. var b = 2.0 / (top - bottom);
  6557. var c = 2.0 / (f - n);
  6558. var d = -(f + n) / (f - n);
  6559. var i0 = (left + right) / (left - right);
  6560. var i1 = (top + bottom) / (bottom - top);
  6561. 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);
  6562. };
  6563. /**
  6564. * Creates a right-handed orthographic projection matrix
  6565. * @param left defines the viewport left coordinate
  6566. * @param right defines the viewport right coordinate
  6567. * @param bottom defines the viewport bottom coordinate
  6568. * @param top defines the viewport top coordinate
  6569. * @param znear defines the near clip plane
  6570. * @param zfar defines the far clip plane
  6571. * @returns a new matrix as a right-handed orthographic projection matrix
  6572. */
  6573. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6574. var matrix = Matrix.Zero();
  6575. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6576. return matrix;
  6577. };
  6578. /**
  6579. * Stores a right-handed orthographic projection into a given matrix
  6580. * @param left defines the viewport left coordinate
  6581. * @param right defines the viewport right coordinate
  6582. * @param bottom defines the viewport bottom coordinate
  6583. * @param top defines the viewport top coordinate
  6584. * @param znear defines the near clip plane
  6585. * @param zfar defines the far clip plane
  6586. * @param result defines the target matrix
  6587. */
  6588. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6589. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6590. result.m[10] *= -1.0;
  6591. };
  6592. /**
  6593. * Creates a left-handed perspective projection matrix
  6594. * @param width defines the viewport width
  6595. * @param height defines the viewport height
  6596. * @param znear defines the near clip plane
  6597. * @param zfar defines the far clip plane
  6598. * @returns a new matrix as a left-handed perspective projection matrix
  6599. */
  6600. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6601. var matrix = Matrix.Zero();
  6602. var n = znear;
  6603. var f = zfar;
  6604. var a = 2.0 * n / width;
  6605. var b = 2.0 * n / height;
  6606. var c = (f + n) / (f - n);
  6607. var d = -2.0 * f * n / (f - n);
  6608. 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);
  6609. return matrix;
  6610. };
  6611. /**
  6612. * Creates a left-handed perspective projection matrix
  6613. * @param fov defines the horizontal field of view
  6614. * @param aspect defines the aspect ratio
  6615. * @param znear defines the near clip plane
  6616. * @param zfar defines the far clip plane
  6617. * @returns a new matrix as a left-handed perspective projection matrix
  6618. */
  6619. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6620. var matrix = Matrix.Zero();
  6621. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6622. return matrix;
  6623. };
  6624. /**
  6625. * Stores a left-handed perspective projection into a given matrix
  6626. * @param fov defines the horizontal field of view
  6627. * @param aspect defines the aspect ratio
  6628. * @param znear defines the near clip plane
  6629. * @param zfar defines the far clip plane
  6630. * @param result defines the target matrix
  6631. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6632. */
  6633. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6634. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6635. var n = znear;
  6636. var f = zfar;
  6637. var t = 1.0 / (Math.tan(fov * 0.5));
  6638. var a = isVerticalFovFixed ? (t / aspect) : t;
  6639. var b = isVerticalFovFixed ? t : (t * aspect);
  6640. var c = (f + n) / (f - n);
  6641. var d = -2.0 * f * n / (f - n);
  6642. 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);
  6643. };
  6644. /**
  6645. * Creates a right-handed perspective projection matrix
  6646. * @param fov defines the horizontal field of view
  6647. * @param aspect defines the aspect ratio
  6648. * @param znear defines the near clip plane
  6649. * @param zfar defines the far clip plane
  6650. * @returns a new matrix as a right-handed perspective projection matrix
  6651. */
  6652. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6653. var matrix = Matrix.Zero();
  6654. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6655. return matrix;
  6656. };
  6657. /**
  6658. * Stores a right-handed perspective projection into a given matrix
  6659. * @param fov defines the horizontal field of view
  6660. * @param aspect defines the aspect ratio
  6661. * @param znear defines the near clip plane
  6662. * @param zfar defines the far clip plane
  6663. * @param result defines the target matrix
  6664. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6665. */
  6666. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6667. //alternatively this could be expressed as:
  6668. // m = PerspectiveFovLHToRef
  6669. // m[10] *= -1.0;
  6670. // m[11] *= -1.0;
  6671. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6672. var n = znear;
  6673. var f = zfar;
  6674. var t = 1.0 / (Math.tan(fov * 0.5));
  6675. var a = isVerticalFovFixed ? (t / aspect) : t;
  6676. var b = isVerticalFovFixed ? t : (t * aspect);
  6677. var c = -(f + n) / (f - n);
  6678. var d = -2 * f * n / (f - n);
  6679. 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);
  6680. };
  6681. /**
  6682. * Stores a perspective projection for WebVR info a given matrix
  6683. * @param fov defines the field of view
  6684. * @param znear defines the near clip plane
  6685. * @param zfar defines the far clip plane
  6686. * @param result defines the target matrix
  6687. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6688. */
  6689. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6690. if (rightHanded === void 0) { rightHanded = false; }
  6691. var rightHandedFactor = rightHanded ? -1 : 1;
  6692. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6693. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6694. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6695. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6696. var xScale = 2.0 / (leftTan + rightTan);
  6697. var yScale = 2.0 / (upTan + downTan);
  6698. result.m[0] = xScale;
  6699. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6700. result.m[5] = yScale;
  6701. result.m[6] = result.m[7] = 0.0;
  6702. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6703. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6704. result.m[10] = -zfar / (znear - zfar);
  6705. result.m[11] = 1.0 * rightHandedFactor;
  6706. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6707. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6708. result._markAsUpdated();
  6709. };
  6710. /**
  6711. * Computes a complete transformation matrix
  6712. * @param viewport defines the viewport to use
  6713. * @param world defines the world matrix
  6714. * @param view defines the view matrix
  6715. * @param projection defines the projection matrix
  6716. * @param zmin defines the near clip plane
  6717. * @param zmax defines the far clip plane
  6718. * @returns the transformation matrix
  6719. */
  6720. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6721. var cw = viewport.width;
  6722. var ch = viewport.height;
  6723. var cx = viewport.x;
  6724. var cy = viewport.y;
  6725. 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);
  6726. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6727. };
  6728. /**
  6729. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6730. * @param matrix defines the matrix to use
  6731. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6732. */
  6733. Matrix.GetAsMatrix2x2 = function (matrix) {
  6734. return new Float32Array([
  6735. matrix.m[0], matrix.m[1],
  6736. matrix.m[4], matrix.m[5]
  6737. ]);
  6738. };
  6739. /**
  6740. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6741. * @param matrix defines the matrix to use
  6742. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6743. */
  6744. Matrix.GetAsMatrix3x3 = function (matrix) {
  6745. return new Float32Array([
  6746. matrix.m[0], matrix.m[1], matrix.m[2],
  6747. matrix.m[4], matrix.m[5], matrix.m[6],
  6748. matrix.m[8], matrix.m[9], matrix.m[10]
  6749. ]);
  6750. };
  6751. /**
  6752. * Compute the transpose of a given matrix
  6753. * @param matrix defines the matrix to transpose
  6754. * @returns the new matrix
  6755. */
  6756. Matrix.Transpose = function (matrix) {
  6757. var result = new Matrix();
  6758. Matrix.TransposeToRef(matrix, result);
  6759. return result;
  6760. };
  6761. /**
  6762. * Compute the transpose of a matrix and store it in a target matrix
  6763. * @param matrix defines the matrix to transpose
  6764. * @param result defines the target matrix
  6765. */
  6766. Matrix.TransposeToRef = function (matrix, result) {
  6767. result.m[0] = matrix.m[0];
  6768. result.m[1] = matrix.m[4];
  6769. result.m[2] = matrix.m[8];
  6770. result.m[3] = matrix.m[12];
  6771. result.m[4] = matrix.m[1];
  6772. result.m[5] = matrix.m[5];
  6773. result.m[6] = matrix.m[9];
  6774. result.m[7] = matrix.m[13];
  6775. result.m[8] = matrix.m[2];
  6776. result.m[9] = matrix.m[6];
  6777. result.m[10] = matrix.m[10];
  6778. result.m[11] = matrix.m[14];
  6779. result.m[12] = matrix.m[3];
  6780. result.m[13] = matrix.m[7];
  6781. result.m[14] = matrix.m[11];
  6782. result.m[15] = matrix.m[15];
  6783. };
  6784. /**
  6785. * Computes a reflection matrix from a plane
  6786. * @param plane defines the reflection plane
  6787. * @returns a new matrix
  6788. */
  6789. Matrix.Reflection = function (plane) {
  6790. var matrix = new Matrix();
  6791. Matrix.ReflectionToRef(plane, matrix);
  6792. return matrix;
  6793. };
  6794. /**
  6795. * Computes a reflection matrix from a plane
  6796. * @param plane defines the reflection plane
  6797. * @param result defines the target matrix
  6798. */
  6799. Matrix.ReflectionToRef = function (plane, result) {
  6800. plane.normalize();
  6801. var x = plane.normal.x;
  6802. var y = plane.normal.y;
  6803. var z = plane.normal.z;
  6804. var temp = -2 * x;
  6805. var temp2 = -2 * y;
  6806. var temp3 = -2 * z;
  6807. result.m[0] = (temp * x) + 1;
  6808. result.m[1] = temp2 * x;
  6809. result.m[2] = temp3 * x;
  6810. result.m[3] = 0.0;
  6811. result.m[4] = temp * y;
  6812. result.m[5] = (temp2 * y) + 1;
  6813. result.m[6] = temp3 * y;
  6814. result.m[7] = 0.0;
  6815. result.m[8] = temp * z;
  6816. result.m[9] = temp2 * z;
  6817. result.m[10] = (temp3 * z) + 1;
  6818. result.m[11] = 0.0;
  6819. result.m[12] = temp * plane.d;
  6820. result.m[13] = temp2 * plane.d;
  6821. result.m[14] = temp3 * plane.d;
  6822. result.m[15] = 1.0;
  6823. result._markAsUpdated();
  6824. };
  6825. /**
  6826. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6827. * @param xaxis defines the value of the 1st axis
  6828. * @param yaxis defines the value of the 2nd axis
  6829. * @param zaxis defines the value of the 3rd axis
  6830. * @param result defines the target matrix
  6831. */
  6832. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6833. result.m[0] = xaxis.x;
  6834. result.m[1] = xaxis.y;
  6835. result.m[2] = xaxis.z;
  6836. result.m[3] = 0.0;
  6837. result.m[4] = yaxis.x;
  6838. result.m[5] = yaxis.y;
  6839. result.m[6] = yaxis.z;
  6840. result.m[7] = 0.0;
  6841. result.m[8] = zaxis.x;
  6842. result.m[9] = zaxis.y;
  6843. result.m[10] = zaxis.z;
  6844. result.m[11] = 0.0;
  6845. result.m[12] = 0.0;
  6846. result.m[13] = 0.0;
  6847. result.m[14] = 0.0;
  6848. result.m[15] = 1.0;
  6849. result._markAsUpdated();
  6850. };
  6851. /**
  6852. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6853. * @param quat defines the quaternion to use
  6854. * @param result defines the target matrix
  6855. */
  6856. Matrix.FromQuaternionToRef = function (quat, result) {
  6857. var xx = quat.x * quat.x;
  6858. var yy = quat.y * quat.y;
  6859. var zz = quat.z * quat.z;
  6860. var xy = quat.x * quat.y;
  6861. var zw = quat.z * quat.w;
  6862. var zx = quat.z * quat.x;
  6863. var yw = quat.y * quat.w;
  6864. var yz = quat.y * quat.z;
  6865. var xw = quat.x * quat.w;
  6866. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6867. result.m[1] = 2.0 * (xy + zw);
  6868. result.m[2] = 2.0 * (zx - yw);
  6869. result.m[3] = 0.0;
  6870. result.m[4] = 2.0 * (xy - zw);
  6871. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6872. result.m[6] = 2.0 * (yz + xw);
  6873. result.m[7] = 0.0;
  6874. result.m[8] = 2.0 * (zx + yw);
  6875. result.m[9] = 2.0 * (yz - xw);
  6876. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6877. result.m[11] = 0.0;
  6878. result.m[12] = 0.0;
  6879. result.m[13] = 0.0;
  6880. result.m[14] = 0.0;
  6881. result.m[15] = 1.0;
  6882. result._markAsUpdated();
  6883. };
  6884. Matrix._tempQuaternion = new Quaternion();
  6885. Matrix._xAxis = Vector3.Zero();
  6886. Matrix._yAxis = Vector3.Zero();
  6887. Matrix._zAxis = Vector3.Zero();
  6888. Matrix._updateFlagSeed = 0;
  6889. Matrix._identityReadOnly = Matrix.Identity();
  6890. return Matrix;
  6891. }());
  6892. BABYLON.Matrix = Matrix;
  6893. /**
  6894. * Represens a plane by the equation ax + by + cz + d = 0
  6895. */
  6896. var Plane = /** @class */ (function () {
  6897. /**
  6898. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6899. * @param a a component of the plane
  6900. * @param b b component of the plane
  6901. * @param c c component of the plane
  6902. * @param d d component of the plane
  6903. */
  6904. function Plane(a, b, c, d) {
  6905. this.normal = new Vector3(a, b, c);
  6906. this.d = d;
  6907. }
  6908. /**
  6909. * @returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6910. */
  6911. Plane.prototype.asArray = function () {
  6912. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6913. };
  6914. // Methods
  6915. /**
  6916. * @returns a new plane copied from the current Plane.
  6917. */
  6918. Plane.prototype.clone = function () {
  6919. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6920. };
  6921. /**
  6922. * @returns the string "Plane".
  6923. */
  6924. Plane.prototype.getClassName = function () {
  6925. return "Plane";
  6926. };
  6927. /**
  6928. * @returns the Plane hash code.
  6929. */
  6930. Plane.prototype.getHashCode = function () {
  6931. var hash = this.normal.getHashCode();
  6932. hash = (hash * 397) ^ (this.d || 0);
  6933. return hash;
  6934. };
  6935. /**
  6936. * Normalize the current Plane in place.
  6937. * @returns the updated Plane.
  6938. */
  6939. Plane.prototype.normalize = function () {
  6940. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6941. var magnitude = 0.0;
  6942. if (norm !== 0) {
  6943. magnitude = 1.0 / norm;
  6944. }
  6945. this.normal.x *= magnitude;
  6946. this.normal.y *= magnitude;
  6947. this.normal.z *= magnitude;
  6948. this.d *= magnitude;
  6949. return this;
  6950. };
  6951. /**
  6952. * Applies a transformation the plane and returns the result
  6953. * @param transformation the transformation matrix to be applied to the plane
  6954. * @returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6955. */
  6956. Plane.prototype.transform = function (transformation) {
  6957. var transposedMatrix = Matrix.Transpose(transformation);
  6958. var x = this.normal.x;
  6959. var y = this.normal.y;
  6960. var z = this.normal.z;
  6961. var d = this.d;
  6962. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6963. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6964. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6965. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6966. return new Plane(normalX, normalY, normalZ, finalD);
  6967. };
  6968. /**
  6969. * Calcualtte the dot product between the point and the plane normal
  6970. * @param point point to calculate the dot product with
  6971. * @returns the dot product (float) of the point coordinates and the plane normal.
  6972. */
  6973. Plane.prototype.dotCoordinate = function (point) {
  6974. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6975. };
  6976. /**
  6977. * Updates the current Plane from the plane defined by the three given points.
  6978. * @param point1 one of the points used to contruct the plane
  6979. * @param point2 one of the points used to contruct the plane
  6980. * @param point3 one of the points used to contruct the plane
  6981. * @returns the updated Plane.
  6982. */
  6983. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6984. var x1 = point2.x - point1.x;
  6985. var y1 = point2.y - point1.y;
  6986. var z1 = point2.z - point1.z;
  6987. var x2 = point3.x - point1.x;
  6988. var y2 = point3.y - point1.y;
  6989. var z2 = point3.z - point1.z;
  6990. var yz = (y1 * z2) - (z1 * y2);
  6991. var xz = (z1 * x2) - (x1 * z2);
  6992. var xy = (x1 * y2) - (y1 * x2);
  6993. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6994. var invPyth;
  6995. if (pyth !== 0) {
  6996. invPyth = 1.0 / pyth;
  6997. }
  6998. else {
  6999. invPyth = 0.0;
  7000. }
  7001. this.normal.x = yz * invPyth;
  7002. this.normal.y = xz * invPyth;
  7003. this.normal.z = xy * invPyth;
  7004. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  7005. return this;
  7006. };
  7007. /**
  7008. * Checks if the plane is facing a given direction
  7009. * @param direction the direction to check if the plane is facing
  7010. * @param epsilon value the dot product is compared against (returns true if dot <= epsilon)
  7011. * @returns True is the vector "direction" is the same side than the plane normal.
  7012. */
  7013. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  7014. var dot = Vector3.Dot(this.normal, direction);
  7015. return (dot <= epsilon);
  7016. };
  7017. /**
  7018. * Calculates the distance to a point
  7019. * @param point point to calculate distance to
  7020. * @returns the signed distance (float) from the given point to the Plane.
  7021. */
  7022. Plane.prototype.signedDistanceTo = function (point) {
  7023. return Vector3.Dot(point, this.normal) + this.d;
  7024. };
  7025. // Statics
  7026. /**
  7027. * Creates a plane from an array
  7028. * @param array the array to create a plane from
  7029. * @returns a new Plane from the given array.
  7030. */
  7031. Plane.FromArray = function (array) {
  7032. return new Plane(array[0], array[1], array[2], array[3]);
  7033. };
  7034. /**
  7035. * Creates a plane from three points
  7036. * @param point1 point used to create the plane
  7037. * @param point2 point used to create the plane
  7038. * @param point3 point used to create the plane
  7039. * @returns a new Plane defined by the three given points.
  7040. */
  7041. Plane.FromPoints = function (point1, point2, point3) {
  7042. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7043. result.copyFromPoints(point1, point2, point3);
  7044. return result;
  7045. };
  7046. /**
  7047. * Creates a plane from an origin point and a normal
  7048. * @param origin origin of the plane to be constructed
  7049. * @param normal normal of the plane to be constructed
  7050. * @returns a new Plane the normal vector to this plane at the given origin point.
  7051. * Note : the vector "normal" is updated because normalized.
  7052. */
  7053. Plane.FromPositionAndNormal = function (origin, normal) {
  7054. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  7055. normal.normalize();
  7056. result.normal = normal;
  7057. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7058. return result;
  7059. };
  7060. /**
  7061. * Calculates the distance from a plane and a point
  7062. * @param origin origin of the plane to be constructed
  7063. * @param normal normal of the plane to be constructed
  7064. * @param point point to calculate distance to
  7065. * @returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  7066. */
  7067. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  7068. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  7069. return Vector3.Dot(point, normal) + d;
  7070. };
  7071. return Plane;
  7072. }());
  7073. BABYLON.Plane = Plane;
  7074. /**
  7075. * Class used to represent a viewport on screen
  7076. */
  7077. var Viewport = /** @class */ (function () {
  7078. /**
  7079. * Creates a Viewport object located at (x, y) and sized (width, height)
  7080. * @param x defines viewport left coordinate
  7081. * @param y defines viewport top coordinate
  7082. * @param width defines the viewport width
  7083. * @param height defines the viewport height
  7084. */
  7085. function Viewport(
  7086. /** viewport left coordinate */
  7087. x,
  7088. /** viewport top coordinate */
  7089. y,
  7090. /**viewport width */
  7091. width,
  7092. /** viewport height */
  7093. height) {
  7094. this.x = x;
  7095. this.y = y;
  7096. this.width = width;
  7097. this.height = height;
  7098. }
  7099. /**
  7100. * Creates a new viewport using absolute sizing (from 0-> width, 0-> height instead of 0->1)
  7101. * @param renderWidthOrEngine defines either an engine or the rendering width
  7102. * @param renderHeight defines the rendering height
  7103. * @returns a new Viewport
  7104. */
  7105. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  7106. if (renderWidthOrEngine.getRenderWidth) {
  7107. var engine = renderWidthOrEngine;
  7108. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  7109. }
  7110. var renderWidth = renderWidthOrEngine;
  7111. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  7112. };
  7113. /**
  7114. * Returns a new Viewport copied from the current one
  7115. * @returns a new Viewport
  7116. */
  7117. Viewport.prototype.clone = function () {
  7118. return new Viewport(this.x, this.y, this.width, this.height);
  7119. };
  7120. return Viewport;
  7121. }());
  7122. BABYLON.Viewport = Viewport;
  7123. /**
  7124. * Reprasents a camera frustum
  7125. */
  7126. var Frustum = /** @class */ (function () {
  7127. function Frustum() {
  7128. }
  7129. /**
  7130. * Gets the planes representing the frustum
  7131. * @param transform matrix to be applied to the returned planes
  7132. * @returns a new array of 6 Frustum planes computed by the given transformation matrix.
  7133. */
  7134. Frustum.GetPlanes = function (transform) {
  7135. var frustumPlanes = [];
  7136. for (var index = 0; index < 6; index++) {
  7137. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  7138. }
  7139. Frustum.GetPlanesToRef(transform, frustumPlanes);
  7140. return frustumPlanes;
  7141. };
  7142. /**
  7143. * Gets the near frustum plane transformed by the transform matrix
  7144. * @param transform transformation matrix to be applied to the resulting frustum plane
  7145. * @param frustumPlane the resuling frustum plane
  7146. */
  7147. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  7148. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  7149. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  7150. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  7151. frustumPlane.d = transform.m[15] + transform.m[14];
  7152. frustumPlane.normalize();
  7153. };
  7154. /**
  7155. * Gets the far frustum plane transformed by the transform matrix
  7156. * @param transform transformation matrix to be applied to the resulting frustum plane
  7157. * @param frustumPlane the resuling frustum plane
  7158. */
  7159. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  7160. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  7161. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  7162. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  7163. frustumPlane.d = transform.m[15] - transform.m[14];
  7164. frustumPlane.normalize();
  7165. };
  7166. /**
  7167. * Gets the left frustum plane transformed by the transform matrix
  7168. * @param transform transformation matrix to be applied to the resulting frustum plane
  7169. * @param frustumPlane the resuling frustum plane
  7170. */
  7171. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  7172. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  7173. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  7174. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  7175. frustumPlane.d = transform.m[15] + transform.m[12];
  7176. frustumPlane.normalize();
  7177. };
  7178. /**
  7179. * Gets the right frustum plane transformed by the transform matrix
  7180. * @param transform transformation matrix to be applied to the resulting frustum plane
  7181. * @param frustumPlane the resuling frustum plane
  7182. */
  7183. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  7184. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  7185. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  7186. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  7187. frustumPlane.d = transform.m[15] - transform.m[12];
  7188. frustumPlane.normalize();
  7189. };
  7190. /**
  7191. * Gets the top frustum plane transformed by the transform matrix
  7192. * @param transform transformation matrix to be applied to the resulting frustum plane
  7193. * @param frustumPlane the resuling frustum plane
  7194. */
  7195. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  7196. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  7197. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  7198. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  7199. frustumPlane.d = transform.m[15] - transform.m[13];
  7200. frustumPlane.normalize();
  7201. };
  7202. /**
  7203. * Gets the bottom frustum plane transformed by the transform matrix
  7204. * @param transform transformation matrix to be applied to the resulting frustum plane
  7205. * @param frustumPlane the resuling frustum plane
  7206. */
  7207. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  7208. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  7209. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  7210. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  7211. frustumPlane.d = transform.m[15] + transform.m[13];
  7212. frustumPlane.normalize();
  7213. };
  7214. /**
  7215. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  7216. * @param transform transformation matrix to be applied to the resulting frustum planes
  7217. * @param frustumPlanes the resuling frustum planes
  7218. */
  7219. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  7220. // Near
  7221. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  7222. // Far
  7223. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  7224. // Left
  7225. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  7226. // Right
  7227. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  7228. // Top
  7229. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  7230. // Bottom
  7231. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  7232. };
  7233. return Frustum;
  7234. }());
  7235. BABYLON.Frustum = Frustum;
  7236. /** Defines supported spaces */
  7237. var Space;
  7238. (function (Space) {
  7239. /** Local (object) space */
  7240. Space[Space["LOCAL"] = 0] = "LOCAL";
  7241. /** World space */
  7242. Space[Space["WORLD"] = 1] = "WORLD";
  7243. /** Bone space */
  7244. Space[Space["BONE"] = 2] = "BONE";
  7245. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  7246. /** Defines the 3 main axes */
  7247. var Axis = /** @class */ (function () {
  7248. function Axis() {
  7249. }
  7250. /** X axis */
  7251. Axis.X = new Vector3(1.0, 0.0, 0.0);
  7252. /** Y axis */
  7253. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  7254. /** Z axis */
  7255. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  7256. return Axis;
  7257. }());
  7258. BABYLON.Axis = Axis;
  7259. ;
  7260. /** Class used to represent a Bezier curve */
  7261. var BezierCurve = /** @class */ (function () {
  7262. function BezierCurve() {
  7263. }
  7264. /**
  7265. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats
  7266. * @param t defines the time
  7267. * @param x1 defines the left coordinate on X axis
  7268. * @param y1 defines the left coordinate on Y axis
  7269. * @param x2 defines the right coordinate on X axis
  7270. * @param y2 defines the right coordinate on Y axis
  7271. * @returns the interpolated value
  7272. */
  7273. BezierCurve.Interpolate = function (t, x1, y1, x2, y2) {
  7274. // Extract X (which is equal to time here)
  7275. var f0 = 1 - 3 * x2 + 3 * x1;
  7276. var f1 = 3 * x2 - 6 * x1;
  7277. var f2 = 3 * x1;
  7278. var refinedT = t;
  7279. for (var i = 0; i < 5; i++) {
  7280. var refinedT2 = refinedT * refinedT;
  7281. var refinedT3 = refinedT2 * refinedT;
  7282. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  7283. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  7284. refinedT -= (x - t) * slope;
  7285. refinedT = Math.min(1, Math.max(0, refinedT));
  7286. }
  7287. // Resolve cubic bezier for the given x
  7288. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  7289. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  7290. Math.pow(refinedT, 3);
  7291. };
  7292. return BezierCurve;
  7293. }());
  7294. BABYLON.BezierCurve = BezierCurve;
  7295. /**
  7296. * Defines potential orientation for back face culling
  7297. */
  7298. var Orientation;
  7299. (function (Orientation) {
  7300. /**
  7301. * Clockwise
  7302. */
  7303. Orientation[Orientation["CW"] = 0] = "CW";
  7304. /** Counter clockwise */
  7305. Orientation[Orientation["CCW"] = 1] = "CCW";
  7306. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  7307. /**
  7308. * Defines angle representation
  7309. */
  7310. var Angle = /** @class */ (function () {
  7311. /**
  7312. * Creates an Angle object of "radians" radians (float).
  7313. */
  7314. function Angle(radians) {
  7315. this._radians = radians;
  7316. if (this._radians < 0.0)
  7317. this._radians += (2.0 * Math.PI);
  7318. }
  7319. /**
  7320. * Get value in degrees
  7321. * @returns the Angle value in degrees (float)
  7322. */
  7323. Angle.prototype.degrees = function () {
  7324. return this._radians * 180.0 / Math.PI;
  7325. };
  7326. /**
  7327. * Get value in radians
  7328. * @returns the Angle value in radians (float)
  7329. */
  7330. Angle.prototype.radians = function () {
  7331. return this._radians;
  7332. };
  7333. /**
  7334. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  7335. * @param a defines first vector
  7336. * @param b defines second vector
  7337. * @returns a new Angle
  7338. */
  7339. Angle.BetweenTwoPoints = function (a, b) {
  7340. var delta = b.subtract(a);
  7341. var theta = Math.atan2(delta.y, delta.x);
  7342. return new Angle(theta);
  7343. };
  7344. /**
  7345. * Gets a new Angle object from the given float in radians
  7346. * @param radians defines the angle value in radians
  7347. * @returns a new Angle
  7348. */
  7349. Angle.FromRadians = function (radians) {
  7350. return new Angle(radians);
  7351. };
  7352. /**
  7353. * Gets a new Angle object from the given float in degrees
  7354. * @param degrees defines the angle value in degrees
  7355. * @returns a new Angle
  7356. */
  7357. Angle.FromDegrees = function (degrees) {
  7358. return new Angle(degrees * Math.PI / 180.0);
  7359. };
  7360. return Angle;
  7361. }());
  7362. BABYLON.Angle = Angle;
  7363. /**
  7364. * This represents an arc in a 2d space.
  7365. */
  7366. var Arc2 = /** @class */ (function () {
  7367. /**
  7368. * Creates an Arc object from the three given points : start, middle and end.
  7369. * @param startPoint Defines the start point of the arc
  7370. * @param midPoint Defines the midlle point of the arc
  7371. * @param endPoint Defines the end point of the arc
  7372. */
  7373. function Arc2(
  7374. /** Defines the start point of the arc */
  7375. startPoint,
  7376. /** Defines the mid point of the arc */
  7377. midPoint,
  7378. /** Defines the end point of the arc */
  7379. endPoint) {
  7380. this.startPoint = startPoint;
  7381. this.midPoint = midPoint;
  7382. this.endPoint = endPoint;
  7383. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7384. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7385. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7386. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7387. 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);
  7388. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7389. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7390. var a1 = this.startAngle.degrees();
  7391. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7392. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7393. // angles correction
  7394. if (a2 - a1 > +180.0)
  7395. a2 -= 360.0;
  7396. if (a2 - a1 < -180.0)
  7397. a2 += 360.0;
  7398. if (a3 - a2 > +180.0)
  7399. a3 -= 360.0;
  7400. if (a3 - a2 < -180.0)
  7401. a3 += 360.0;
  7402. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7403. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7404. }
  7405. return Arc2;
  7406. }());
  7407. BABYLON.Arc2 = Arc2;
  7408. /**
  7409. * Represents a 2D path made up of multiple 2D points
  7410. */
  7411. var Path2 = /** @class */ (function () {
  7412. /**
  7413. * Creates a Path2 object from the starting 2D coordinates x and y.
  7414. * @param x the starting points x value
  7415. * @param y the starting points y value
  7416. */
  7417. function Path2(x, y) {
  7418. this._points = new Array();
  7419. this._length = 0.0;
  7420. /**
  7421. * If the path start and end point are the same
  7422. */
  7423. this.closed = false;
  7424. this._points.push(new Vector2(x, y));
  7425. }
  7426. /**
  7427. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7428. * @param x the added points x value
  7429. * @param y the added points y value
  7430. * @returns the updated Path2.
  7431. */
  7432. Path2.prototype.addLineTo = function (x, y) {
  7433. if (this.closed) {
  7434. return this;
  7435. }
  7436. var newPoint = new Vector2(x, y);
  7437. var previousPoint = this._points[this._points.length - 1];
  7438. this._points.push(newPoint);
  7439. this._length += newPoint.subtract(previousPoint).length();
  7440. return this;
  7441. };
  7442. /**
  7443. * 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.
  7444. * @param midX middle point x value
  7445. * @param midY middle point y value
  7446. * @param endX end point x value
  7447. * @param endY end point y value
  7448. * @param numberOfSegments (default: 36)
  7449. * @returns the updated Path2.
  7450. */
  7451. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7452. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7453. if (this.closed) {
  7454. return this;
  7455. }
  7456. var startPoint = this._points[this._points.length - 1];
  7457. var midPoint = new Vector2(midX, midY);
  7458. var endPoint = new Vector2(endX, endY);
  7459. var arc = new Arc2(startPoint, midPoint, endPoint);
  7460. var increment = arc.angle.radians() / numberOfSegments;
  7461. if (arc.orientation === Orientation.CW)
  7462. increment *= -1;
  7463. var currentAngle = arc.startAngle.radians() + increment;
  7464. for (var i = 0; i < numberOfSegments; i++) {
  7465. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7466. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7467. this.addLineTo(x, y);
  7468. currentAngle += increment;
  7469. }
  7470. return this;
  7471. };
  7472. /**
  7473. * Closes the Path2.
  7474. * @returns the Path2.
  7475. */
  7476. Path2.prototype.close = function () {
  7477. this.closed = true;
  7478. return this;
  7479. };
  7480. /**
  7481. * Gets the sum of the distance between each sequential point in the path
  7482. * @returns the Path2 total length (float).
  7483. */
  7484. Path2.prototype.length = function () {
  7485. var result = this._length;
  7486. if (!this.closed) {
  7487. var lastPoint = this._points[this._points.length - 1];
  7488. var firstPoint = this._points[0];
  7489. result += (firstPoint.subtract(lastPoint).length());
  7490. }
  7491. return result;
  7492. };
  7493. /**
  7494. * Gets the points which construct the path
  7495. * @returns the Path2 internal array of points.
  7496. */
  7497. Path2.prototype.getPoints = function () {
  7498. return this._points;
  7499. };
  7500. /**
  7501. * Retreives the point at the distance aways from the starting point
  7502. * @param normalizedLengthPosition the length along the path to retreive the point from
  7503. * @returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7504. */
  7505. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7506. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7507. return Vector2.Zero();
  7508. }
  7509. var lengthPosition = normalizedLengthPosition * this.length();
  7510. var previousOffset = 0;
  7511. for (var i = 0; i < this._points.length; i++) {
  7512. var j = (i + 1) % this._points.length;
  7513. var a = this._points[i];
  7514. var b = this._points[j];
  7515. var bToA = b.subtract(a);
  7516. var nextOffset = (bToA.length() + previousOffset);
  7517. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7518. var dir = bToA.normalize();
  7519. var localOffset = lengthPosition - previousOffset;
  7520. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7521. }
  7522. previousOffset = nextOffset;
  7523. }
  7524. return Vector2.Zero();
  7525. };
  7526. /**
  7527. * Creates a new path starting from an x and y position
  7528. * @param x starting x value
  7529. * @param y starting y value
  7530. * @returns a new Path2 starting at the coordinates (x, y).
  7531. */
  7532. Path2.StartingAt = function (x, y) {
  7533. return new Path2(x, y);
  7534. };
  7535. return Path2;
  7536. }());
  7537. BABYLON.Path2 = Path2;
  7538. /**
  7539. * Represents a 3D path made up of multiple 3D points
  7540. */
  7541. var Path3D = /** @class */ (function () {
  7542. /**
  7543. * new Path3D(path, normal, raw)
  7544. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7545. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7546. * @param path an array of Vector3, the curve axis of the Path3D
  7547. * @param normal (options) Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7548. * @param raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7549. */
  7550. function Path3D(
  7551. /**
  7552. * an array of Vector3, the curve axis of the Path3D
  7553. */
  7554. path, firstNormal, raw) {
  7555. if (firstNormal === void 0) { firstNormal = null; }
  7556. this.path = path;
  7557. this._curve = new Array();
  7558. this._distances = new Array();
  7559. this._tangents = new Array();
  7560. this._normals = new Array();
  7561. this._binormals = new Array();
  7562. for (var p = 0; p < path.length; p++) {
  7563. this._curve[p] = path[p].clone(); // hard copy
  7564. }
  7565. this._raw = raw || false;
  7566. this._compute(firstNormal);
  7567. }
  7568. /**
  7569. * Returns the Path3D array of successive Vector3 designing its curve.
  7570. * @returns the Path3D array of successive Vector3 designing its curve.
  7571. */
  7572. Path3D.prototype.getCurve = function () {
  7573. return this._curve;
  7574. };
  7575. /**
  7576. * Returns an array populated with tangent vectors on each Path3D curve point.
  7577. * @returns an array populated with tangent vectors on each Path3D curve point.
  7578. */
  7579. Path3D.prototype.getTangents = function () {
  7580. return this._tangents;
  7581. };
  7582. /**
  7583. * Returns an array populated with normal vectors on each Path3D curve point.
  7584. * @returns an array populated with normal vectors on each Path3D curve point.
  7585. */
  7586. Path3D.prototype.getNormals = function () {
  7587. return this._normals;
  7588. };
  7589. /**
  7590. * Returns an array populated with binormal vectors on each Path3D curve point.
  7591. * @returns an array populated with binormal vectors on each Path3D curve point.
  7592. */
  7593. Path3D.prototype.getBinormals = function () {
  7594. return this._binormals;
  7595. };
  7596. /**
  7597. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7598. * @returns an array populated with distances (float) of the i-th point from the first curve point.
  7599. */
  7600. Path3D.prototype.getDistances = function () {
  7601. return this._distances;
  7602. };
  7603. /**
  7604. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7605. * @param path path which all values are copied into the curves points
  7606. * @param firstNormal which should be projected onto the curve
  7607. * @returns the same object updated.
  7608. */
  7609. Path3D.prototype.update = function (path, firstNormal) {
  7610. if (firstNormal === void 0) { firstNormal = null; }
  7611. for (var p = 0; p < path.length; p++) {
  7612. this._curve[p].x = path[p].x;
  7613. this._curve[p].y = path[p].y;
  7614. this._curve[p].z = path[p].z;
  7615. }
  7616. this._compute(firstNormal);
  7617. return this;
  7618. };
  7619. // private function compute() : computes tangents, normals and binormals
  7620. Path3D.prototype._compute = function (firstNormal) {
  7621. var l = this._curve.length;
  7622. // first and last tangents
  7623. this._tangents[0] = this._getFirstNonNullVector(0);
  7624. if (!this._raw) {
  7625. this._tangents[0].normalize();
  7626. }
  7627. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7628. if (!this._raw) {
  7629. this._tangents[l - 1].normalize();
  7630. }
  7631. // normals and binormals at first point : arbitrary vector with _normalVector()
  7632. var tg0 = this._tangents[0];
  7633. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7634. this._normals[0] = pp0;
  7635. if (!this._raw) {
  7636. this._normals[0].normalize();
  7637. }
  7638. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7639. if (!this._raw) {
  7640. this._binormals[0].normalize();
  7641. }
  7642. this._distances[0] = 0.0;
  7643. // normals and binormals : next points
  7644. var prev; // previous vector (segment)
  7645. var cur; // current vector (segment)
  7646. var curTang; // current tangent
  7647. // previous normal
  7648. var prevBinor; // previous binormal
  7649. for (var i = 1; i < l; i++) {
  7650. // tangents
  7651. prev = this._getLastNonNullVector(i);
  7652. if (i < l - 1) {
  7653. cur = this._getFirstNonNullVector(i);
  7654. this._tangents[i] = prev.add(cur);
  7655. this._tangents[i].normalize();
  7656. }
  7657. this._distances[i] = this._distances[i - 1] + prev.length();
  7658. // normals and binormals
  7659. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7660. curTang = this._tangents[i];
  7661. prevBinor = this._binormals[i - 1];
  7662. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7663. if (!this._raw) {
  7664. this._normals[i].normalize();
  7665. }
  7666. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7667. if (!this._raw) {
  7668. this._binormals[i].normalize();
  7669. }
  7670. }
  7671. };
  7672. // private function getFirstNonNullVector(index)
  7673. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7674. Path3D.prototype._getFirstNonNullVector = function (index) {
  7675. var i = 1;
  7676. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7677. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7678. i++;
  7679. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7680. }
  7681. return nNVector;
  7682. };
  7683. // private function getLastNonNullVector(index)
  7684. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7685. Path3D.prototype._getLastNonNullVector = function (index) {
  7686. var i = 1;
  7687. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7688. while (nLVector.length() === 0 && index > i + 1) {
  7689. i++;
  7690. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7691. }
  7692. return nLVector;
  7693. };
  7694. // private function normalVector(v0, vt, va) :
  7695. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7696. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7697. Path3D.prototype._normalVector = function (v0, vt, va) {
  7698. var normal0;
  7699. var tgl = vt.length();
  7700. if (tgl === 0.0) {
  7701. tgl = 1.0;
  7702. }
  7703. if (va === undefined || va === null) {
  7704. var point;
  7705. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7706. point = new Vector3(0.0, -1.0, 0.0);
  7707. }
  7708. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7709. point = new Vector3(1.0, 0.0, 0.0);
  7710. }
  7711. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7712. point = new Vector3(0.0, 0.0, 1.0);
  7713. }
  7714. else {
  7715. point = Vector3.Zero();
  7716. }
  7717. normal0 = Vector3.Cross(vt, point);
  7718. }
  7719. else {
  7720. normal0 = Vector3.Cross(vt, va);
  7721. Vector3.CrossToRef(normal0, vt, normal0);
  7722. }
  7723. normal0.normalize();
  7724. return normal0;
  7725. };
  7726. return Path3D;
  7727. }());
  7728. BABYLON.Path3D = Path3D;
  7729. /**
  7730. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7731. * A Curve3 is designed from a series of successive Vector3.
  7732. * @see https://doc.babylonjs.com/how_to/how_to_use_curve3
  7733. */
  7734. var Curve3 = /** @class */ (function () {
  7735. /**
  7736. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7737. * A Curve3 is designed from a series of successive Vector3.
  7738. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7739. * @param points points which make up the curve
  7740. */
  7741. function Curve3(points) {
  7742. this._length = 0.0;
  7743. this._points = points;
  7744. this._length = this._computeLength(points);
  7745. }
  7746. /**
  7747. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7748. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7749. * @param v1 (Vector3) the control point
  7750. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7751. * @param nbPoints (integer) the wanted number of points in the curve
  7752. * @returns the created Curve3
  7753. */
  7754. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7755. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7756. var bez = new Array();
  7757. var equation = function (t, val0, val1, val2) {
  7758. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7759. return res;
  7760. };
  7761. for (var i = 0; i <= nbPoints; i++) {
  7762. 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)));
  7763. }
  7764. return new Curve3(bez);
  7765. };
  7766. /**
  7767. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7768. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7769. * @param v1 (Vector3) the first control point
  7770. * @param v2 (Vector3) the second control point
  7771. * @param v3 (Vector3) the end point of the Cubic Bezier
  7772. * @param nbPoints (integer) the wanted number of points in the curve
  7773. * @returns the created Curve3
  7774. */
  7775. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7776. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7777. var bez = new Array();
  7778. var equation = function (t, val0, val1, val2, val3) {
  7779. 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;
  7780. return res;
  7781. };
  7782. for (var i = 0; i <= nbPoints; i++) {
  7783. 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)));
  7784. }
  7785. return new Curve3(bez);
  7786. };
  7787. /**
  7788. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7789. * @param p1 (Vector3) the origin point of the Hermite Spline
  7790. * @param t1 (Vector3) the tangent vector at the origin point
  7791. * @param p2 (Vector3) the end point of the Hermite Spline
  7792. * @param t2 (Vector3) the tangent vector at the end point
  7793. * @param nbPoints (integer) the wanted number of points in the curve
  7794. * @returns the created Curve3
  7795. */
  7796. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7797. var hermite = new Array();
  7798. var step = 1.0 / nbPoints;
  7799. for (var i = 0; i <= nbPoints; i++) {
  7800. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7801. }
  7802. return new Curve3(hermite);
  7803. };
  7804. /**
  7805. * Returns a Curve3 object along a CatmullRom Spline curve :
  7806. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7807. * @param nbPoints (integer) the wanted number of points between each curve control points
  7808. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7809. * @returns the created Curve3
  7810. */
  7811. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7812. var catmullRom = new Array();
  7813. var step = 1.0 / nbPoints;
  7814. var amount = 0.0;
  7815. if (closed) {
  7816. var pointsCount = points.length;
  7817. for (var i = 0; i < pointsCount; i++) {
  7818. amount = 0;
  7819. for (var c = 0; c < nbPoints; c++) {
  7820. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7821. amount += step;
  7822. }
  7823. }
  7824. catmullRom.push(catmullRom[0]);
  7825. }
  7826. else {
  7827. var totalPoints = new Array();
  7828. totalPoints.push(points[0].clone());
  7829. Array.prototype.push.apply(totalPoints, points);
  7830. totalPoints.push(points[points.length - 1].clone());
  7831. for (var i = 0; i < totalPoints.length - 3; i++) {
  7832. amount = 0;
  7833. for (var c = 0; c < nbPoints; c++) {
  7834. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7835. amount += step;
  7836. }
  7837. }
  7838. i--;
  7839. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7840. }
  7841. return new Curve3(catmullRom);
  7842. };
  7843. /**
  7844. * @returns the Curve3 stored array of successive Vector3
  7845. */
  7846. Curve3.prototype.getPoints = function () {
  7847. return this._points;
  7848. };
  7849. /**
  7850. * @returns the computed length (float) of the curve.
  7851. */
  7852. Curve3.prototype.length = function () {
  7853. return this._length;
  7854. };
  7855. /**
  7856. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7857. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7858. * curveA and curveB keep unchanged.
  7859. * @param curve the curve to continue from this curve
  7860. * @returns the newly constructed curve
  7861. */
  7862. Curve3.prototype.continue = function (curve) {
  7863. var lastPoint = this._points[this._points.length - 1];
  7864. var continuedPoints = this._points.slice();
  7865. var curvePoints = curve.getPoints();
  7866. for (var i = 1; i < curvePoints.length; i++) {
  7867. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7868. }
  7869. var continuedCurve = new Curve3(continuedPoints);
  7870. return continuedCurve;
  7871. };
  7872. Curve3.prototype._computeLength = function (path) {
  7873. var l = 0;
  7874. for (var i = 1; i < path.length; i++) {
  7875. l += (path[i].subtract(path[i - 1])).length();
  7876. }
  7877. return l;
  7878. };
  7879. return Curve3;
  7880. }());
  7881. BABYLON.Curve3 = Curve3;
  7882. // Vertex formats
  7883. /**
  7884. * Contains position and normal vectors for a vertex
  7885. */
  7886. var PositionNormalVertex = /** @class */ (function () {
  7887. /**
  7888. * Creates a PositionNormalVertex
  7889. * @param position the position of the vertex (defaut: 0,0,0)
  7890. * @param normal the normal of the vertex (defaut: 0,1,0)
  7891. */
  7892. function PositionNormalVertex(
  7893. /** the position of the vertex (defaut: 0,0,0) */
  7894. position,
  7895. /** the normal of the vertex (defaut: 0,1,0) */
  7896. normal) {
  7897. if (position === void 0) { position = Vector3.Zero(); }
  7898. if (normal === void 0) { normal = Vector3.Up(); }
  7899. this.position = position;
  7900. this.normal = normal;
  7901. }
  7902. /**
  7903. * Clones the PositionNormalVertex
  7904. * @returns the cloned PositionNormalVertex
  7905. */
  7906. PositionNormalVertex.prototype.clone = function () {
  7907. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7908. };
  7909. return PositionNormalVertex;
  7910. }());
  7911. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7912. /**
  7913. * Contains position, normal and uv vectors for a vertex
  7914. */
  7915. var PositionNormalTextureVertex = /** @class */ (function () {
  7916. /**
  7917. * Creates a PositionNormalTextureVertex
  7918. * @param position the position of the vertex (defaut: 0,0,0)
  7919. * @param normal the normal of the vertex (defaut: 0,1,0)
  7920. * @param uv the uv of the vertex (default: 0,0)
  7921. */
  7922. function PositionNormalTextureVertex(
  7923. /** the position of the vertex (defaut: 0,0,0) */
  7924. position,
  7925. /** the normal of the vertex (defaut: 0,1,0) */
  7926. normal,
  7927. /** the uv of the vertex (default: 0,0) */
  7928. uv) {
  7929. if (position === void 0) { position = Vector3.Zero(); }
  7930. if (normal === void 0) { normal = Vector3.Up(); }
  7931. if (uv === void 0) { uv = Vector2.Zero(); }
  7932. this.position = position;
  7933. this.normal = normal;
  7934. this.uv = uv;
  7935. }
  7936. /**
  7937. * Clones the PositionNormalTextureVertex
  7938. * @returns the cloned PositionNormalTextureVertex
  7939. */
  7940. PositionNormalTextureVertex.prototype.clone = function () {
  7941. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7942. };
  7943. return PositionNormalTextureVertex;
  7944. }());
  7945. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7946. // Temporary pre-allocated objects for engine internal use
  7947. // usage in any internal function :
  7948. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7949. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7950. /**
  7951. * @hidden
  7952. */
  7953. var Tmp = /** @class */ (function () {
  7954. function Tmp() {
  7955. }
  7956. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7957. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7958. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7959. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7960. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7961. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7962. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7963. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7964. Matrix.Zero(), Matrix.Zero(),
  7965. Matrix.Zero(), Matrix.Zero(),
  7966. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7967. return Tmp;
  7968. }());
  7969. BABYLON.Tmp = Tmp;
  7970. /**
  7971. * @hidden
  7972. * Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7973. */
  7974. var MathTmp = /** @class */ (function () {
  7975. function MathTmp() {
  7976. }
  7977. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7978. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7979. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7980. return MathTmp;
  7981. }());
  7982. })(BABYLON || (BABYLON = {}));
  7983. //# sourceMappingURL=babylon.math.js.map
  7984. var BABYLON;
  7985. (function (BABYLON) {
  7986. /**
  7987. * Scalar computation library
  7988. */
  7989. var Scalar = /** @class */ (function () {
  7990. function Scalar() {
  7991. }
  7992. /**
  7993. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7994. * @param a number
  7995. * @param b number
  7996. * @param epsilon (default = 1.401298E-45)
  7997. * @returns true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7998. */
  7999. Scalar.WithinEpsilon = function (a, b, epsilon) {
  8000. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  8001. var num = a - b;
  8002. return -epsilon <= num && num <= epsilon;
  8003. };
  8004. /**
  8005. * Returns a string : the upper case translation of the number i to hexadecimal.
  8006. * @param i number
  8007. * @returns the upper case translation of the number i to hexadecimal.
  8008. */
  8009. Scalar.ToHex = function (i) {
  8010. var str = i.toString(16);
  8011. if (i <= 15) {
  8012. return ("0" + str).toUpperCase();
  8013. }
  8014. return str.toUpperCase();
  8015. };
  8016. /**
  8017. * Returns -1 if value is negative and +1 is value is positive.
  8018. * @param value the value
  8019. * @returns the value itself if it's equal to zero.
  8020. */
  8021. Scalar.Sign = function (value) {
  8022. value = +value; // convert to a number
  8023. if (value === 0 || isNaN(value))
  8024. return value;
  8025. return value > 0 ? 1 : -1;
  8026. };
  8027. /**
  8028. * Returns the value itself if it's between min and max.
  8029. * Returns min if the value is lower than min.
  8030. * Returns max if the value is greater than max.
  8031. * @param value the value to clmap
  8032. * @param min the min value to clamp to (default: 0)
  8033. * @param max the max value to clamp to (default: 1)
  8034. * @returns the clamped value
  8035. */
  8036. Scalar.Clamp = function (value, min, max) {
  8037. if (min === void 0) { min = 0; }
  8038. if (max === void 0) { max = 1; }
  8039. return Math.min(max, Math.max(min, value));
  8040. };
  8041. /**
  8042. * the log2 of value.
  8043. * @param value the value to compute log2 of
  8044. * @returns the log2 of value.
  8045. */
  8046. Scalar.Log2 = function (value) {
  8047. return Math.log(value) * Math.LOG2E;
  8048. };
  8049. /**
  8050. * Loops the value, so that it is never larger than length and never smaller than 0.
  8051. *
  8052. * This is similar to the modulo operator but it works with floating point numbers.
  8053. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  8054. * With t = 5 and length = 2.5, the result would be 0.0.
  8055. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  8056. * @param value the value
  8057. * @param length the length
  8058. * @returns the looped value
  8059. */
  8060. Scalar.Repeat = function (value, length) {
  8061. return value - Math.floor(value / length) * length;
  8062. };
  8063. /**
  8064. * Normalize the value between 0.0 and 1.0 using min and max values
  8065. * @param value value to normalize
  8066. * @param min max to normalize between
  8067. * @param max min to normalize between
  8068. * @returns the normalized value
  8069. */
  8070. Scalar.Normalize = function (value, min, max) {
  8071. return (value - min) / (max - min);
  8072. };
  8073. /**
  8074. * Denormalize the value from 0.0 and 1.0 using min and max values
  8075. * @param normalized value to denormalize
  8076. * @param min max to denormalize between
  8077. * @param max min to denormalize between
  8078. * @returns the denormalized value
  8079. */
  8080. Scalar.Denormalize = function (normalized, min, max) {
  8081. return (normalized * (max - min) + min);
  8082. };
  8083. /**
  8084. * Calculates the shortest difference between two given angles given in degrees.
  8085. * @param current current angle in degrees
  8086. * @param target target angle in degrees
  8087. * @returns the delta
  8088. */
  8089. Scalar.DeltaAngle = function (current, target) {
  8090. var num = Scalar.Repeat(target - current, 360.0);
  8091. if (num > 180.0) {
  8092. num -= 360.0;
  8093. }
  8094. return num;
  8095. };
  8096. /**
  8097. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  8098. * @param tx value
  8099. * @param length length
  8100. * @returns The returned value will move back and forth between 0 and length
  8101. */
  8102. Scalar.PingPong = function (tx, length) {
  8103. var t = Scalar.Repeat(tx, length * 2.0);
  8104. return length - Math.abs(t - length);
  8105. };
  8106. /**
  8107. * Interpolates between min and max with smoothing at the limits.
  8108. *
  8109. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  8110. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  8111. * @param from from
  8112. * @param to to
  8113. * @param tx value
  8114. * @returns the smooth stepped value
  8115. */
  8116. Scalar.SmoothStep = function (from, to, tx) {
  8117. var t = Scalar.Clamp(tx);
  8118. t = -2.0 * t * t * t + 3.0 * t * t;
  8119. return to * t + from * (1.0 - t);
  8120. };
  8121. /**
  8122. * Moves a value current towards target.
  8123. *
  8124. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  8125. * Negative values of maxDelta pushes the value away from target.
  8126. * @param current current value
  8127. * @param target target value
  8128. * @param maxDelta max distance to move
  8129. * @returns resulting value
  8130. */
  8131. Scalar.MoveTowards = function (current, target, maxDelta) {
  8132. var result = 0;
  8133. if (Math.abs(target - current) <= maxDelta) {
  8134. result = target;
  8135. }
  8136. else {
  8137. result = current + Scalar.Sign(target - current) * maxDelta;
  8138. }
  8139. return result;
  8140. };
  8141. /**
  8142. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8143. *
  8144. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  8145. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  8146. * @param current current value
  8147. * @param target target value
  8148. * @param maxDelta max distance to move
  8149. * @returns resulting angle
  8150. */
  8151. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  8152. var num = Scalar.DeltaAngle(current, target);
  8153. var result = 0;
  8154. if (-maxDelta < num && num < maxDelta) {
  8155. result = target;
  8156. }
  8157. else {
  8158. target = current + num;
  8159. result = Scalar.MoveTowards(current, target, maxDelta);
  8160. }
  8161. return result;
  8162. };
  8163. /**
  8164. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  8165. * @param start start value
  8166. * @param end target value
  8167. * @param amount amount to lerp between
  8168. * @returns the lerped value
  8169. */
  8170. Scalar.Lerp = function (start, end, amount) {
  8171. return start + ((end - start) * amount);
  8172. };
  8173. /**
  8174. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  8175. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  8176. * @param start start value
  8177. * @param end target value
  8178. * @param amount amount to lerp between
  8179. * @returns the lerped value
  8180. */
  8181. Scalar.LerpAngle = function (start, end, amount) {
  8182. var num = Scalar.Repeat(end - start, 360.0);
  8183. if (num > 180.0) {
  8184. num -= 360.0;
  8185. }
  8186. return start + num * Scalar.Clamp(amount);
  8187. };
  8188. /**
  8189. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  8190. * @param a start value
  8191. * @param b target value
  8192. * @param value value between a and b
  8193. * @returns the inverseLerp value
  8194. */
  8195. Scalar.InverseLerp = function (a, b, value) {
  8196. var result = 0;
  8197. if (a != b) {
  8198. result = Scalar.Clamp((value - a) / (b - a));
  8199. }
  8200. else {
  8201. result = 0.0;
  8202. }
  8203. return result;
  8204. };
  8205. /**
  8206. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  8207. * @see http://mathworld.wolfram.com/HermitePolynomial.html
  8208. * @param value1 spline value
  8209. * @param tangent1 spline value
  8210. * @param value2 spline value
  8211. * @param tangent2 spline value
  8212. * @param amount input value
  8213. * @returns hermite result
  8214. */
  8215. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  8216. var squared = amount * amount;
  8217. var cubed = amount * squared;
  8218. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  8219. var part2 = (-2.0 * cubed) + (3.0 * squared);
  8220. var part3 = (cubed - (2.0 * squared)) + amount;
  8221. var part4 = cubed - squared;
  8222. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  8223. };
  8224. /**
  8225. * Returns a random float number between and min and max values
  8226. * @param min min value of random
  8227. * @param max max value of random
  8228. * @returns random value
  8229. */
  8230. Scalar.RandomRange = function (min, max) {
  8231. if (min === max)
  8232. return min;
  8233. return ((Math.random() * (max - min)) + min);
  8234. };
  8235. /**
  8236. * This function returns percentage of a number in a given range.
  8237. *
  8238. * RangeToPercent(40,20,60) will return 0.5 (50%)
  8239. * RangeToPercent(34,0,100) will return 0.34 (34%)
  8240. * @param number to convert to percentage
  8241. * @param min min range
  8242. * @param max max range
  8243. * @returns the percentage
  8244. */
  8245. Scalar.RangeToPercent = function (number, min, max) {
  8246. return ((number - min) / (max - min));
  8247. };
  8248. /**
  8249. * This function returns number that corresponds to the percentage in a given range.
  8250. *
  8251. * PercentToRange(0.34,0,100) will return 34.
  8252. * @param percent to convert to number
  8253. * @param min min range
  8254. * @param max max range
  8255. * @returns the number
  8256. */
  8257. Scalar.PercentToRange = function (percent, min, max) {
  8258. return ((max - min) * percent + min);
  8259. };
  8260. /**
  8261. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  8262. * @param angle The angle to normalize in radian.
  8263. * @return The converted angle.
  8264. */
  8265. Scalar.NormalizeRadians = function (angle) {
  8266. // More precise but slower version kept for reference.
  8267. // angle = angle % Tools.TwoPi;
  8268. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  8269. //if (angle > Math.PI) {
  8270. // angle -= Tools.TwoPi;
  8271. //}
  8272. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  8273. return angle;
  8274. };
  8275. /**
  8276. * Two pi constants convenient for computation.
  8277. */
  8278. Scalar.TwoPi = Math.PI * 2;
  8279. return Scalar;
  8280. }());
  8281. BABYLON.Scalar = Scalar;
  8282. })(BABYLON || (BABYLON = {}));
  8283. //# sourceMappingURL=babylon.math.scalar.js.map
  8284. //# sourceMappingURL=babylon.mixins.js.map
  8285. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  8286. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  8287. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  8288. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  8289. //# sourceMappingURL=babylon.webgl2.js.map
  8290. var BABYLON;
  8291. (function (BABYLON) {
  8292. var __decoratorInitialStore = {};
  8293. var __mergedStore = {};
  8294. var _copySource = function (creationFunction, source, instanciate) {
  8295. var destination = creationFunction();
  8296. // Tags
  8297. if (BABYLON.Tags) {
  8298. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8299. }
  8300. var classStore = getMergedStore(destination);
  8301. // Properties
  8302. for (var property in classStore) {
  8303. var propertyDescriptor = classStore[property];
  8304. var sourceProperty = source[property];
  8305. var propertyType = propertyDescriptor.type;
  8306. if (sourceProperty !== undefined && sourceProperty !== null) {
  8307. switch (propertyType) {
  8308. case 0: // Value
  8309. case 6: // Mesh reference
  8310. case 11: // Camera reference
  8311. destination[property] = sourceProperty;
  8312. break;
  8313. case 1: // Texture
  8314. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  8315. break;
  8316. case 2: // Color3
  8317. case 3: // FresnelParameters
  8318. case 4: // Vector2
  8319. case 5: // Vector3
  8320. case 7: // Color Curves
  8321. case 10: // Quaternion
  8322. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  8323. break;
  8324. }
  8325. }
  8326. }
  8327. return destination;
  8328. };
  8329. function getDirectStore(target) {
  8330. var classKey = target.getClassName();
  8331. if (!__decoratorInitialStore[classKey]) {
  8332. __decoratorInitialStore[classKey] = {};
  8333. }
  8334. return __decoratorInitialStore[classKey];
  8335. }
  8336. /**
  8337. * Return the list of properties flagged as serializable
  8338. * @param target: host object
  8339. */
  8340. function getMergedStore(target) {
  8341. var classKey = target.getClassName();
  8342. if (__mergedStore[classKey]) {
  8343. return __mergedStore[classKey];
  8344. }
  8345. __mergedStore[classKey] = {};
  8346. var store = __mergedStore[classKey];
  8347. var currentTarget = target;
  8348. var currentKey = classKey;
  8349. while (currentKey) {
  8350. var initialStore = __decoratorInitialStore[currentKey];
  8351. for (var property in initialStore) {
  8352. store[property] = initialStore[property];
  8353. }
  8354. var parent_1 = void 0;
  8355. var done = false;
  8356. do {
  8357. parent_1 = Object.getPrototypeOf(currentTarget);
  8358. if (!parent_1.getClassName) {
  8359. done = true;
  8360. break;
  8361. }
  8362. if (parent_1.getClassName() !== currentKey) {
  8363. break;
  8364. }
  8365. currentTarget = parent_1;
  8366. } while (parent_1);
  8367. if (done) {
  8368. break;
  8369. }
  8370. currentKey = parent_1.getClassName();
  8371. currentTarget = parent_1;
  8372. }
  8373. return store;
  8374. }
  8375. function generateSerializableMember(type, sourceName) {
  8376. return function (target, propertyKey) {
  8377. var classStore = getDirectStore(target);
  8378. if (!classStore[propertyKey]) {
  8379. classStore[propertyKey] = { type: type, sourceName: sourceName };
  8380. }
  8381. };
  8382. }
  8383. function generateExpandMember(setCallback, targetKey) {
  8384. if (targetKey === void 0) { targetKey = null; }
  8385. return function (target, propertyKey) {
  8386. var key = targetKey || ("_" + propertyKey);
  8387. Object.defineProperty(target, propertyKey, {
  8388. get: function () {
  8389. return this[key];
  8390. },
  8391. set: function (value) {
  8392. if (this[key] === value) {
  8393. return;
  8394. }
  8395. this[key] = value;
  8396. target[setCallback].apply(this);
  8397. },
  8398. enumerable: true,
  8399. configurable: true
  8400. });
  8401. };
  8402. }
  8403. function expandToProperty(callback, targetKey) {
  8404. if (targetKey === void 0) { targetKey = null; }
  8405. return generateExpandMember(callback, targetKey);
  8406. }
  8407. BABYLON.expandToProperty = expandToProperty;
  8408. function serialize(sourceName) {
  8409. return generateSerializableMember(0, sourceName); // value member
  8410. }
  8411. BABYLON.serialize = serialize;
  8412. function serializeAsTexture(sourceName) {
  8413. return generateSerializableMember(1, sourceName); // texture member
  8414. }
  8415. BABYLON.serializeAsTexture = serializeAsTexture;
  8416. function serializeAsColor3(sourceName) {
  8417. return generateSerializableMember(2, sourceName); // color3 member
  8418. }
  8419. BABYLON.serializeAsColor3 = serializeAsColor3;
  8420. function serializeAsFresnelParameters(sourceName) {
  8421. return generateSerializableMember(3, sourceName); // fresnel parameters member
  8422. }
  8423. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  8424. function serializeAsVector2(sourceName) {
  8425. return generateSerializableMember(4, sourceName); // vector2 member
  8426. }
  8427. BABYLON.serializeAsVector2 = serializeAsVector2;
  8428. function serializeAsVector3(sourceName) {
  8429. return generateSerializableMember(5, sourceName); // vector3 member
  8430. }
  8431. BABYLON.serializeAsVector3 = serializeAsVector3;
  8432. function serializeAsMeshReference(sourceName) {
  8433. return generateSerializableMember(6, sourceName); // mesh reference member
  8434. }
  8435. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  8436. function serializeAsColorCurves(sourceName) {
  8437. return generateSerializableMember(7, sourceName); // color curves
  8438. }
  8439. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  8440. function serializeAsColor4(sourceName) {
  8441. return generateSerializableMember(8, sourceName); // color 4
  8442. }
  8443. BABYLON.serializeAsColor4 = serializeAsColor4;
  8444. function serializeAsImageProcessingConfiguration(sourceName) {
  8445. return generateSerializableMember(9, sourceName); // image processing
  8446. }
  8447. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  8448. function serializeAsQuaternion(sourceName) {
  8449. return generateSerializableMember(10, sourceName); // quaternion member
  8450. }
  8451. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  8452. /**
  8453. * Decorator used to define property that can be serialized as reference to a camera
  8454. * @param sourceName defines the name of the property to decorate
  8455. */
  8456. function serializeAsCameraReference(sourceName) {
  8457. return generateSerializableMember(11, sourceName); // camera reference member
  8458. }
  8459. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  8460. /**
  8461. * Class used to help serialization objects
  8462. */
  8463. var SerializationHelper = /** @class */ (function () {
  8464. function SerializationHelper() {
  8465. }
  8466. /**
  8467. * Static function used to serialized a specific entity
  8468. * @param entity defines the entity to serialize
  8469. * @param serializationObject defines the optional target obecjt where serialization data will be stored
  8470. * @returns a JSON compatible object representing the serialization of the entity
  8471. */
  8472. SerializationHelper.Serialize = function (entity, serializationObject) {
  8473. if (!serializationObject) {
  8474. serializationObject = {};
  8475. }
  8476. // Tags
  8477. if (BABYLON.Tags) {
  8478. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  8479. }
  8480. var serializedProperties = getMergedStore(entity);
  8481. // Properties
  8482. for (var property in serializedProperties) {
  8483. var propertyDescriptor = serializedProperties[property];
  8484. var targetPropertyName = propertyDescriptor.sourceName || property;
  8485. var propertyType = propertyDescriptor.type;
  8486. var sourceProperty = entity[property];
  8487. if (sourceProperty !== undefined && sourceProperty !== null) {
  8488. switch (propertyType) {
  8489. case 0: // Value
  8490. serializationObject[targetPropertyName] = sourceProperty;
  8491. break;
  8492. case 1: // Texture
  8493. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8494. break;
  8495. case 2: // Color3
  8496. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8497. break;
  8498. case 3: // FresnelParameters
  8499. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8500. break;
  8501. case 4: // Vector2
  8502. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8503. break;
  8504. case 5: // Vector3
  8505. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8506. break;
  8507. case 6: // Mesh reference
  8508. serializationObject[targetPropertyName] = sourceProperty.id;
  8509. break;
  8510. case 7: // Color Curves
  8511. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8512. break;
  8513. case 8: // Color 4
  8514. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8515. break;
  8516. case 9: // Image Processing
  8517. serializationObject[targetPropertyName] = sourceProperty.serialize();
  8518. break;
  8519. case 10: // Quaternion
  8520. serializationObject[targetPropertyName] = sourceProperty.asArray();
  8521. break;
  8522. case 11: // Camera reference
  8523. serializationObject[targetPropertyName] = sourceProperty.id;
  8524. break;
  8525. }
  8526. }
  8527. }
  8528. return serializationObject;
  8529. };
  8530. /**
  8531. * Creates a new entity from a serialization data object
  8532. * @param creationFunction defines a function used to instanciated the new entity
  8533. * @param source defines the source serialization data
  8534. * @param scene defines the hosting scene
  8535. * @param rootUrl defines the root url for resources
  8536. * @returns a new entity
  8537. */
  8538. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  8539. if (rootUrl === void 0) { rootUrl = null; }
  8540. var destination = creationFunction();
  8541. if (!rootUrl) {
  8542. rootUrl = "";
  8543. }
  8544. // Tags
  8545. if (BABYLON.Tags) {
  8546. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8547. }
  8548. var classStore = getMergedStore(destination);
  8549. // Properties
  8550. for (var property in classStore) {
  8551. var propertyDescriptor = classStore[property];
  8552. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8553. var propertyType = propertyDescriptor.type;
  8554. if (sourceProperty !== undefined && sourceProperty !== null) {
  8555. var dest = destination;
  8556. switch (propertyType) {
  8557. case 0: // Value
  8558. dest[property] = sourceProperty;
  8559. break;
  8560. case 1: // Texture
  8561. if (scene) {
  8562. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8563. }
  8564. break;
  8565. case 2: // Color3
  8566. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8567. break;
  8568. case 3: // FresnelParameters
  8569. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8570. break;
  8571. case 4: // Vector2
  8572. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8573. break;
  8574. case 5: // Vector3
  8575. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8576. break;
  8577. case 6: // Mesh reference
  8578. if (scene) {
  8579. dest[property] = scene.getLastMeshByID(sourceProperty);
  8580. }
  8581. break;
  8582. case 7: // Color Curves
  8583. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8584. break;
  8585. case 8: // Color 4
  8586. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8587. break;
  8588. case 9: // Image Processing
  8589. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8590. break;
  8591. case 10: // Quaternion
  8592. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8593. break;
  8594. case 11: // Camera reference
  8595. if (scene) {
  8596. dest[property] = scene.getCameraByID(sourceProperty);
  8597. }
  8598. break;
  8599. }
  8600. }
  8601. }
  8602. return destination;
  8603. };
  8604. /**
  8605. * Clones an object
  8606. * @param creationFunction defines the function used to instanciate the new object
  8607. * @param source defines the source object
  8608. * @returns the cloned object
  8609. */
  8610. SerializationHelper.Clone = function (creationFunction, source) {
  8611. return _copySource(creationFunction, source, false);
  8612. };
  8613. /**
  8614. * Instanciates a new object based on a source one (some data will be shared between both object)
  8615. * @param creationFunction defines the function used to instanciate the new object
  8616. * @param source defines the source object
  8617. * @returns the new object
  8618. */
  8619. SerializationHelper.Instanciate = function (creationFunction, source) {
  8620. return _copySource(creationFunction, source, true);
  8621. };
  8622. return SerializationHelper;
  8623. }());
  8624. BABYLON.SerializationHelper = SerializationHelper;
  8625. })(BABYLON || (BABYLON = {}));
  8626. //# sourceMappingURL=babylon.decorators.js.map
  8627. var BABYLON;
  8628. (function (BABYLON) {
  8629. /**
  8630. * Wrapper class for promise with external resolve and reject.
  8631. */
  8632. var Deferred = /** @class */ (function () {
  8633. /**
  8634. * Constructor for this deferred object.
  8635. */
  8636. function Deferred() {
  8637. var _this = this;
  8638. this.promise = new Promise(function (resolve, reject) {
  8639. _this._resolve = resolve;
  8640. _this._reject = reject;
  8641. });
  8642. }
  8643. Object.defineProperty(Deferred.prototype, "resolve", {
  8644. /**
  8645. * The resolve method of the promise associated with this deferred object.
  8646. */
  8647. get: function () {
  8648. return this._resolve;
  8649. },
  8650. enumerable: true,
  8651. configurable: true
  8652. });
  8653. Object.defineProperty(Deferred.prototype, "reject", {
  8654. /**
  8655. * The reject method of the promise associated with this deferred object.
  8656. */
  8657. get: function () {
  8658. return this._reject;
  8659. },
  8660. enumerable: true,
  8661. configurable: true
  8662. });
  8663. return Deferred;
  8664. }());
  8665. BABYLON.Deferred = Deferred;
  8666. })(BABYLON || (BABYLON = {}));
  8667. //# sourceMappingURL=babylon.deferred.js.map
  8668. var BABYLON;
  8669. (function (BABYLON) {
  8670. /**
  8671. * A class serves as a medium between the observable and its observers
  8672. */
  8673. var EventState = /** @class */ (function () {
  8674. /**
  8675. * Create a new EventState
  8676. * @param mask defines the mask associated with this state
  8677. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8678. * @param target defines the original target of the state
  8679. * @param currentTarget defines the current target of the state
  8680. */
  8681. function EventState(mask, skipNextObservers, target, currentTarget) {
  8682. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8683. this.initalize(mask, skipNextObservers, target, currentTarget);
  8684. }
  8685. /**
  8686. * Initialize the current event state
  8687. * @param mask defines the mask associated with this state
  8688. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8689. * @param target defines the original target of the state
  8690. * @param currentTarget defines the current target of the state
  8691. * @returns the current event state
  8692. */
  8693. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8694. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8695. this.mask = mask;
  8696. this.skipNextObservers = skipNextObservers;
  8697. this.target = target;
  8698. this.currentTarget = currentTarget;
  8699. return this;
  8700. };
  8701. return EventState;
  8702. }());
  8703. BABYLON.EventState = EventState;
  8704. /**
  8705. * Represent an Observer registered to a given Observable object.
  8706. */
  8707. var Observer = /** @class */ (function () {
  8708. /**
  8709. * Creates a new observer
  8710. * @param callback defines the callback to call when the observer is notified
  8711. * @param mask defines the mask of the observer (used to filter notifications)
  8712. * @param scope defines the current scope used to restore the JS context
  8713. */
  8714. function Observer(
  8715. /**
  8716. * Defines the callback to call when the observer is notified
  8717. */
  8718. callback,
  8719. /**
  8720. * Defines the mask of the observer (used to filter notifications)
  8721. */
  8722. mask,
  8723. /**
  8724. * Defines the current scope used to restore the JS context
  8725. */
  8726. scope) {
  8727. if (scope === void 0) { scope = null; }
  8728. this.callback = callback;
  8729. this.mask = mask;
  8730. this.scope = scope;
  8731. /** @hidden */
  8732. this._willBeUnregistered = false;
  8733. /**
  8734. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8735. */
  8736. this.unregisterOnNextCall = false;
  8737. }
  8738. return Observer;
  8739. }());
  8740. BABYLON.Observer = Observer;
  8741. /**
  8742. * Represent a list of observers registered to multiple Observables object.
  8743. */
  8744. var MultiObserver = /** @class */ (function () {
  8745. function MultiObserver() {
  8746. }
  8747. /**
  8748. * Release associated resources
  8749. */
  8750. MultiObserver.prototype.dispose = function () {
  8751. if (this._observers && this._observables) {
  8752. for (var index = 0; index < this._observers.length; index++) {
  8753. this._observables[index].remove(this._observers[index]);
  8754. }
  8755. }
  8756. this._observers = null;
  8757. this._observables = null;
  8758. };
  8759. /**
  8760. * Raise a callback when one of the observable will notify
  8761. * @param observables defines a list of observables to watch
  8762. * @param callback defines the callback to call on notification
  8763. * @param mask defines the mask used to filter notifications
  8764. * @param scope defines the current scope used to restore the JS context
  8765. * @returns the new MultiObserver
  8766. */
  8767. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8768. if (mask === void 0) { mask = -1; }
  8769. if (scope === void 0) { scope = null; }
  8770. var result = new MultiObserver();
  8771. result._observers = new Array();
  8772. result._observables = observables;
  8773. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8774. var observable = observables_1[_i];
  8775. var observer = observable.add(callback, mask, false, scope);
  8776. if (observer) {
  8777. result._observers.push(observer);
  8778. }
  8779. }
  8780. return result;
  8781. };
  8782. return MultiObserver;
  8783. }());
  8784. BABYLON.MultiObserver = MultiObserver;
  8785. /**
  8786. * The Observable class is a simple implementation of the Observable pattern.
  8787. *
  8788. * 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.
  8789. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8790. * 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).
  8791. * 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.
  8792. */
  8793. var Observable = /** @class */ (function () {
  8794. /**
  8795. * Creates a new observable
  8796. * @param onObserverAdded defines a callback to call when a new observer is added
  8797. */
  8798. function Observable(onObserverAdded) {
  8799. this._observers = new Array();
  8800. this._eventState = new EventState(0);
  8801. if (onObserverAdded) {
  8802. this._onObserverAdded = onObserverAdded;
  8803. }
  8804. }
  8805. /**
  8806. * Create a new Observer with the specified callback
  8807. * @param callback the callback that will be executed for that Observer
  8808. * @param mask the mask used to filter observers
  8809. * @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.
  8810. * @param scope optional scope for the callback to be called from
  8811. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8812. * @returns the new observer created for the callback
  8813. */
  8814. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8815. if (mask === void 0) { mask = -1; }
  8816. if (insertFirst === void 0) { insertFirst = false; }
  8817. if (scope === void 0) { scope = null; }
  8818. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8819. if (!callback) {
  8820. return null;
  8821. }
  8822. var observer = new Observer(callback, mask, scope);
  8823. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8824. if (insertFirst) {
  8825. this._observers.unshift(observer);
  8826. }
  8827. else {
  8828. this._observers.push(observer);
  8829. }
  8830. if (this._onObserverAdded) {
  8831. this._onObserverAdded(observer);
  8832. }
  8833. return observer;
  8834. };
  8835. /**
  8836. * Create a new Observer with the specified callback and unregisters after the next notification
  8837. * @param callback the callback that will be executed for that Observer
  8838. * @returns the new observer created for the callback
  8839. */
  8840. Observable.prototype.addOnce = function (callback) {
  8841. return this.add(callback, undefined, undefined, undefined, true);
  8842. };
  8843. /**
  8844. * Remove an Observer from the Observable object
  8845. * @param observer the instance of the Observer to remove
  8846. * @returns false if it doesn't belong to this Observable
  8847. */
  8848. Observable.prototype.remove = function (observer) {
  8849. if (!observer) {
  8850. return false;
  8851. }
  8852. var index = this._observers.indexOf(observer);
  8853. if (index !== -1) {
  8854. this._deferUnregister(observer);
  8855. return true;
  8856. }
  8857. return false;
  8858. };
  8859. /**
  8860. * Remove a callback from the Observable object
  8861. * @param callback the callback to remove
  8862. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8863. * @returns false if it doesn't belong to this Observable
  8864. */
  8865. Observable.prototype.removeCallback = function (callback, scope) {
  8866. for (var index = 0; index < this._observers.length; index++) {
  8867. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8868. this._deferUnregister(this._observers[index]);
  8869. return true;
  8870. }
  8871. }
  8872. return false;
  8873. };
  8874. Observable.prototype._deferUnregister = function (observer) {
  8875. var _this = this;
  8876. observer.unregisterOnNextCall = false;
  8877. observer._willBeUnregistered = true;
  8878. BABYLON.Tools.SetImmediate(function () {
  8879. _this._remove(observer);
  8880. });
  8881. };
  8882. // This should only be called when not iterating over _observers to avoid callback skipping.
  8883. // Removes an observer from the _observer Array.
  8884. Observable.prototype._remove = function (observer) {
  8885. if (!observer) {
  8886. return false;
  8887. }
  8888. var index = this._observers.indexOf(observer);
  8889. if (index !== -1) {
  8890. this._observers.splice(index, 1);
  8891. return true;
  8892. }
  8893. return false;
  8894. };
  8895. /**
  8896. * Notify all Observers by calling their respective callback with the given data
  8897. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8898. * @param eventData defines the data to send to all observers
  8899. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8900. * @param target defines the original target of the state
  8901. * @param currentTarget defines the current target of the state
  8902. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8903. */
  8904. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8905. if (mask === void 0) { mask = -1; }
  8906. if (!this._observers.length) {
  8907. return true;
  8908. }
  8909. var state = this._eventState;
  8910. state.mask = mask;
  8911. state.target = target;
  8912. state.currentTarget = currentTarget;
  8913. state.skipNextObservers = false;
  8914. state.lastReturnValue = eventData;
  8915. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8916. var obs = _a[_i];
  8917. if (obs._willBeUnregistered) {
  8918. continue;
  8919. }
  8920. if (obs.mask & mask) {
  8921. if (obs.scope) {
  8922. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8923. }
  8924. else {
  8925. state.lastReturnValue = obs.callback(eventData, state);
  8926. }
  8927. if (obs.unregisterOnNextCall) {
  8928. this._deferUnregister(obs);
  8929. }
  8930. }
  8931. if (state.skipNextObservers) {
  8932. return false;
  8933. }
  8934. }
  8935. return true;
  8936. };
  8937. /**
  8938. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8939. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8940. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8941. * and it is crucial that all callbacks will be executed.
  8942. * The order of the callbacks is kept, callbacks are not executed parallel.
  8943. *
  8944. * @param eventData The data to be sent to each callback
  8945. * @param mask is used to filter observers defaults to -1
  8946. * @param target defines the callback target (see EventState)
  8947. * @param currentTarget defines he current object in the bubbling phase
  8948. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8949. */
  8950. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8951. var _this = this;
  8952. if (mask === void 0) { mask = -1; }
  8953. // create an empty promise
  8954. var p = Promise.resolve(eventData);
  8955. // no observers? return this promise.
  8956. if (!this._observers.length) {
  8957. return p;
  8958. }
  8959. var state = this._eventState;
  8960. state.mask = mask;
  8961. state.target = target;
  8962. state.currentTarget = currentTarget;
  8963. state.skipNextObservers = false;
  8964. // execute one callback after another (not using Promise.all, the order is important)
  8965. this._observers.forEach(function (obs) {
  8966. if (state.skipNextObservers) {
  8967. return;
  8968. }
  8969. if (obs._willBeUnregistered) {
  8970. return;
  8971. }
  8972. if (obs.mask & mask) {
  8973. if (obs.scope) {
  8974. p = p.then(function (lastReturnedValue) {
  8975. state.lastReturnValue = lastReturnedValue;
  8976. return obs.callback.apply(obs.scope, [eventData, state]);
  8977. });
  8978. }
  8979. else {
  8980. p = p.then(function (lastReturnedValue) {
  8981. state.lastReturnValue = lastReturnedValue;
  8982. return obs.callback(eventData, state);
  8983. });
  8984. }
  8985. if (obs.unregisterOnNextCall) {
  8986. _this._deferUnregister(obs);
  8987. }
  8988. }
  8989. });
  8990. // return the eventData
  8991. return p.then(function () { return eventData; });
  8992. };
  8993. /**
  8994. * Notify a specific observer
  8995. * @param observer defines the observer to notify
  8996. * @param eventData defines the data to be sent to each callback
  8997. * @param mask is used to filter observers defaults to -1
  8998. */
  8999. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  9000. if (mask === void 0) { mask = -1; }
  9001. var state = this._eventState;
  9002. state.mask = mask;
  9003. state.skipNextObservers = false;
  9004. observer.callback(eventData, state);
  9005. };
  9006. /**
  9007. * Gets a boolean indicating if the observable has at least one observer
  9008. * @returns true is the Observable has at least one Observer registered
  9009. */
  9010. Observable.prototype.hasObservers = function () {
  9011. return this._observers.length > 0;
  9012. };
  9013. /**
  9014. * Clear the list of observers
  9015. */
  9016. Observable.prototype.clear = function () {
  9017. this._observers = new Array();
  9018. this._onObserverAdded = null;
  9019. };
  9020. /**
  9021. * Clone the current observable
  9022. * @returns a new observable
  9023. */
  9024. Observable.prototype.clone = function () {
  9025. var result = new Observable();
  9026. result._observers = this._observers.slice(0);
  9027. return result;
  9028. };
  9029. /**
  9030. * Does this observable handles observer registered with a given mask
  9031. * @param mask defines the mask to be tested
  9032. * @return whether or not one observer registered with the given mask is handeled
  9033. **/
  9034. Observable.prototype.hasSpecificMask = function (mask) {
  9035. if (mask === void 0) { mask = -1; }
  9036. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  9037. var obs = _a[_i];
  9038. if (obs.mask & mask || obs.mask === mask) {
  9039. return true;
  9040. }
  9041. }
  9042. return false;
  9043. };
  9044. return Observable;
  9045. }());
  9046. BABYLON.Observable = Observable;
  9047. })(BABYLON || (BABYLON = {}));
  9048. //# sourceMappingURL=babylon.observable.js.map
  9049. var BABYLON;
  9050. (function (BABYLON) {
  9051. /**
  9052. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9053. */
  9054. var SmartArray = /** @class */ (function () {
  9055. /**
  9056. * Instantiates a Smart Array.
  9057. * @param capacity defines the default capacity of the array.
  9058. */
  9059. function SmartArray(capacity) {
  9060. /**
  9061. * The active length of the array.
  9062. */
  9063. this.length = 0;
  9064. this.data = new Array(capacity);
  9065. this._id = SmartArray._GlobalId++;
  9066. }
  9067. /**
  9068. * Pushes a value at the end of the active data.
  9069. * @param value defines the object to push in the array.
  9070. */
  9071. SmartArray.prototype.push = function (value) {
  9072. this.data[this.length++] = value;
  9073. if (this.length > this.data.length) {
  9074. this.data.length *= 2;
  9075. }
  9076. };
  9077. /**
  9078. * Iterates over the active data and apply the lambda to them.
  9079. * @param func defines the action to apply on each value.
  9080. */
  9081. SmartArray.prototype.forEach = function (func) {
  9082. for (var index = 0; index < this.length; index++) {
  9083. func(this.data[index]);
  9084. }
  9085. };
  9086. /**
  9087. * Sorts the full sets of data.
  9088. * @param compareFn defines the comparison function to apply.
  9089. */
  9090. SmartArray.prototype.sort = function (compareFn) {
  9091. this.data.sort(compareFn);
  9092. };
  9093. /**
  9094. * Resets the active data to an empty array.
  9095. */
  9096. SmartArray.prototype.reset = function () {
  9097. this.length = 0;
  9098. };
  9099. /**
  9100. * Releases all the data from the array as well as the array.
  9101. */
  9102. SmartArray.prototype.dispose = function () {
  9103. this.reset();
  9104. if (this.data) {
  9105. this.data.length = 0;
  9106. this.data = [];
  9107. }
  9108. };
  9109. /**
  9110. * Concats the active data with a given array.
  9111. * @param array defines the data to concatenate with.
  9112. */
  9113. SmartArray.prototype.concat = function (array) {
  9114. if (array.length === 0) {
  9115. return;
  9116. }
  9117. if (this.length + array.length > this.data.length) {
  9118. this.data.length = (this.length + array.length) * 2;
  9119. }
  9120. for (var index = 0; index < array.length; index++) {
  9121. this.data[this.length++] = (array.data || array)[index];
  9122. }
  9123. };
  9124. /**
  9125. * Returns the position of a value in the active data.
  9126. * @param value defines the value to find the index for
  9127. * @returns the index if found in the active data otherwise -1
  9128. */
  9129. SmartArray.prototype.indexOf = function (value) {
  9130. var position = this.data.indexOf(value);
  9131. if (position >= this.length) {
  9132. return -1;
  9133. }
  9134. return position;
  9135. };
  9136. /**
  9137. * Returns whether an element is part of the active data.
  9138. * @param value defines the value to look for
  9139. * @returns true if found in the active data otherwise false
  9140. */
  9141. SmartArray.prototype.contains = function (value) {
  9142. return this.indexOf(value) !== -1;
  9143. };
  9144. // Statics
  9145. SmartArray._GlobalId = 0;
  9146. return SmartArray;
  9147. }());
  9148. BABYLON.SmartArray = SmartArray;
  9149. /**
  9150. * Defines an GC Friendly array where the backfield array do not shrink to prevent over allocations.
  9151. * The data in this array can only be present once
  9152. */
  9153. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  9154. __extends(SmartArrayNoDuplicate, _super);
  9155. function SmartArrayNoDuplicate() {
  9156. var _this = _super !== null && _super.apply(this, arguments) || this;
  9157. _this._duplicateId = 0;
  9158. return _this;
  9159. }
  9160. /**
  9161. * Pushes a value at the end of the active data.
  9162. * THIS DOES NOT PREVENT DUPPLICATE DATA
  9163. * @param value defines the object to push in the array.
  9164. */
  9165. SmartArrayNoDuplicate.prototype.push = function (value) {
  9166. _super.prototype.push.call(this, value);
  9167. if (!value.__smartArrayFlags) {
  9168. value.__smartArrayFlags = {};
  9169. }
  9170. value.__smartArrayFlags[this._id] = this._duplicateId;
  9171. };
  9172. /**
  9173. * Pushes a value at the end of the active data.
  9174. * If the data is already present, it won t be added again
  9175. * @param value defines the object to push in the array.
  9176. * @returns true if added false if it was already present
  9177. */
  9178. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  9179. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  9180. return false;
  9181. }
  9182. this.push(value);
  9183. return true;
  9184. };
  9185. /**
  9186. * Resets the active data to an empty array.
  9187. */
  9188. SmartArrayNoDuplicate.prototype.reset = function () {
  9189. _super.prototype.reset.call(this);
  9190. this._duplicateId++;
  9191. };
  9192. /**
  9193. * Concats the active data with a given array.
  9194. * This ensures no dupplicate will be present in the result.
  9195. * @param array defines the data to concatenate with.
  9196. */
  9197. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  9198. if (array.length === 0) {
  9199. return;
  9200. }
  9201. if (this.length + array.length > this.data.length) {
  9202. this.data.length = (this.length + array.length) * 2;
  9203. }
  9204. for (var index = 0; index < array.length; index++) {
  9205. var item = (array.data || array)[index];
  9206. this.pushNoDuplicate(item);
  9207. }
  9208. };
  9209. return SmartArrayNoDuplicate;
  9210. }(SmartArray));
  9211. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  9212. })(BABYLON || (BABYLON = {}));
  9213. //# sourceMappingURL=babylon.smartArray.js.map
  9214. var BABYLON;
  9215. (function (BABYLON) {
  9216. /** Class used to store color4 gradient */
  9217. var ColorGradient = /** @class */ (function () {
  9218. function ColorGradient() {
  9219. }
  9220. /**
  9221. * Will get a color picked randomly between color1 and color2.
  9222. * If color2 is undefined then color1 will be used
  9223. * @param result defines the target Color4 to store the result in
  9224. */
  9225. ColorGradient.prototype.getColorToRef = function (result) {
  9226. if (!this.color2) {
  9227. result.copyFrom(this.color1);
  9228. return;
  9229. }
  9230. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  9231. };
  9232. return ColorGradient;
  9233. }());
  9234. BABYLON.ColorGradient = ColorGradient;
  9235. /** Class used to store color 3 gradient */
  9236. var Color3Gradient = /** @class */ (function () {
  9237. function Color3Gradient() {
  9238. }
  9239. return Color3Gradient;
  9240. }());
  9241. BABYLON.Color3Gradient = Color3Gradient;
  9242. /** Class used to store factor gradient */
  9243. var FactorGradient = /** @class */ (function () {
  9244. function FactorGradient() {
  9245. }
  9246. /**
  9247. * Will get a number picked randomly between factor1 and factor2.
  9248. * If factor2 is undefined then factor1 will be used
  9249. * @returns the picked number
  9250. */
  9251. FactorGradient.prototype.getFactor = function () {
  9252. if (this.factor2 === undefined) {
  9253. return this.factor1;
  9254. }
  9255. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  9256. };
  9257. return FactorGradient;
  9258. }());
  9259. BABYLON.FactorGradient = FactorGradient;
  9260. /**
  9261. * @ignore
  9262. * Application error to support additional information when loading a file
  9263. */
  9264. var LoadFileError = /** @class */ (function (_super) {
  9265. __extends(LoadFileError, _super);
  9266. /**
  9267. * Creates a new LoadFileError
  9268. * @param message defines the message of the error
  9269. * @param request defines the optional XHR request
  9270. */
  9271. function LoadFileError(message,
  9272. /** defines the optional XHR request */
  9273. request) {
  9274. var _this = _super.call(this, message) || this;
  9275. _this.request = request;
  9276. _this.name = "LoadFileError";
  9277. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  9278. return _this;
  9279. }
  9280. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  9281. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  9282. // Polyfill for Object.setPrototypeOf if necessary.
  9283. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  9284. return LoadFileError;
  9285. }(Error));
  9286. BABYLON.LoadFileError = LoadFileError;
  9287. /**
  9288. * Class used to define a retry strategy when error happens while loading assets
  9289. */
  9290. var RetryStrategy = /** @class */ (function () {
  9291. function RetryStrategy() {
  9292. }
  9293. /**
  9294. * Function used to defines an exponential back off strategy
  9295. * @param maxRetries defines the maximum number of retries (3 by default)
  9296. * @param baseInterval defines the interval between retries
  9297. * @returns the strategy function to use
  9298. */
  9299. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  9300. if (maxRetries === void 0) { maxRetries = 3; }
  9301. if (baseInterval === void 0) { baseInterval = 500; }
  9302. return function (url, request, retryIndex) {
  9303. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  9304. return -1;
  9305. }
  9306. return Math.pow(2, retryIndex) * baseInterval;
  9307. };
  9308. };
  9309. return RetryStrategy;
  9310. }());
  9311. BABYLON.RetryStrategy = RetryStrategy;
  9312. // Screenshots
  9313. var screenshotCanvas;
  9314. var cloneValue = function (source, destinationObject) {
  9315. if (!source)
  9316. return null;
  9317. if (source instanceof BABYLON.Mesh) {
  9318. return null;
  9319. }
  9320. if (source instanceof BABYLON.SubMesh) {
  9321. return source.clone(destinationObject);
  9322. }
  9323. else if (source.clone) {
  9324. return source.clone();
  9325. }
  9326. return null;
  9327. };
  9328. /**
  9329. * Class containing a set of static utilities functions
  9330. */
  9331. var Tools = /** @class */ (function () {
  9332. function Tools() {
  9333. }
  9334. /**
  9335. * Read the content of a byte array at a specified coordinates (taking in account wrapping)
  9336. * @param u defines the coordinate on X axis
  9337. * @param v defines the coordinate on Y axis
  9338. * @param width defines the width of the source data
  9339. * @param height defines the height of the source data
  9340. * @param pixels defines the source byte array
  9341. * @param color defines the output color
  9342. */
  9343. Tools.FetchToRef = function (u, v, width, height, pixels, color) {
  9344. var wrappedU = ((Math.abs(u) * width) % width) | 0;
  9345. var wrappedV = ((Math.abs(v) * height) % height) | 0;
  9346. var position = (wrappedU + wrappedV * width) * 4;
  9347. color.r = pixels[position] / 255;
  9348. color.g = pixels[position + 1] / 255;
  9349. color.b = pixels[position + 2] / 255;
  9350. color.a = pixels[position + 3] / 255;
  9351. };
  9352. /**
  9353. * Interpolates between a and b via alpha
  9354. * @param a The lower value (returned when alpha = 0)
  9355. * @param b The upper value (returned when alpha = 1)
  9356. * @param alpha The interpolation-factor
  9357. * @return The mixed value
  9358. */
  9359. Tools.Mix = function (a, b, alpha) {
  9360. return a * (1 - alpha) + b * alpha;
  9361. };
  9362. /**
  9363. * Tries to instantiate a new object from a given class name
  9364. * @param className defines the class name to instantiate
  9365. * @returns the new object or null if the system was not able to do the instantiation
  9366. */
  9367. Tools.Instantiate = function (className) {
  9368. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  9369. return Tools.RegisteredExternalClasses[className];
  9370. }
  9371. var arr = className.split(".");
  9372. var fn = (window || this);
  9373. for (var i = 0, len = arr.length; i < len; i++) {
  9374. fn = fn[arr[i]];
  9375. }
  9376. if (typeof fn !== "function") {
  9377. return null;
  9378. }
  9379. return fn;
  9380. };
  9381. /**
  9382. * Provides a slice function that will work even on IE
  9383. * @param data defines the array to slice
  9384. * @param start defines the start of the data (optional)
  9385. * @param end defines the end of the data (optional)
  9386. * @returns the new sliced array
  9387. */
  9388. Tools.Slice = function (data, start, end) {
  9389. if (data.slice) {
  9390. return data.slice(start, end);
  9391. }
  9392. return Array.prototype.slice.call(data, start, end);
  9393. };
  9394. /**
  9395. * Polyfill for setImmediate
  9396. * @param action defines the action to execute after the current execution block
  9397. */
  9398. Tools.SetImmediate = function (action) {
  9399. if (Tools.IsWindowObjectExist() && window.setImmediate) {
  9400. window.setImmediate(action);
  9401. }
  9402. else {
  9403. setTimeout(action, 1);
  9404. }
  9405. };
  9406. /**
  9407. * Function indicating if a number is an exponent of 2
  9408. * @param value defines the value to test
  9409. * @returns true if the value is an exponent of 2
  9410. */
  9411. Tools.IsExponentOfTwo = function (value) {
  9412. var count = 1;
  9413. do {
  9414. count *= 2;
  9415. } while (count < value);
  9416. return count === value;
  9417. };
  9418. /**
  9419. * Returns the nearest 32-bit single precision float representation of a Number
  9420. * @param value A Number. If the parameter is of a different type, it will get converted
  9421. * to a number or to NaN if it cannot be converted
  9422. * @returns number
  9423. */
  9424. Tools.FloatRound = function (value) {
  9425. if (Math.fround) {
  9426. return Math.fround(value);
  9427. }
  9428. return (Tools._tmpFloatArray[0] = value);
  9429. };
  9430. /**
  9431. * Find the next highest power of two.
  9432. * @param x Number to start search from.
  9433. * @return Next highest power of two.
  9434. */
  9435. Tools.CeilingPOT = function (x) {
  9436. x--;
  9437. x |= x >> 1;
  9438. x |= x >> 2;
  9439. x |= x >> 4;
  9440. x |= x >> 8;
  9441. x |= x >> 16;
  9442. x++;
  9443. return x;
  9444. };
  9445. /**
  9446. * Find the next lowest power of two.
  9447. * @param x Number to start search from.
  9448. * @return Next lowest power of two.
  9449. */
  9450. Tools.FloorPOT = function (x) {
  9451. x = x | (x >> 1);
  9452. x = x | (x >> 2);
  9453. x = x | (x >> 4);
  9454. x = x | (x >> 8);
  9455. x = x | (x >> 16);
  9456. return x - (x >> 1);
  9457. };
  9458. /**
  9459. * Find the nearest power of two.
  9460. * @param x Number to start search from.
  9461. * @return Next nearest power of two.
  9462. */
  9463. Tools.NearestPOT = function (x) {
  9464. var c = Tools.CeilingPOT(x);
  9465. var f = Tools.FloorPOT(x);
  9466. return (c - x) > (x - f) ? f : c;
  9467. };
  9468. /**
  9469. * Get the closest exponent of two
  9470. * @param value defines the value to approximate
  9471. * @param max defines the maximum value to return
  9472. * @param mode defines how to define the closest value
  9473. * @returns closest exponent of two of the given value
  9474. */
  9475. Tools.GetExponentOfTwo = function (value, max, mode) {
  9476. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  9477. var pot;
  9478. switch (mode) {
  9479. case BABYLON.Engine.SCALEMODE_FLOOR:
  9480. pot = Tools.FloorPOT(value);
  9481. break;
  9482. case BABYLON.Engine.SCALEMODE_NEAREST:
  9483. pot = Tools.NearestPOT(value);
  9484. break;
  9485. case BABYLON.Engine.SCALEMODE_CEILING:
  9486. default:
  9487. pot = Tools.CeilingPOT(value);
  9488. break;
  9489. }
  9490. return Math.min(pot, max);
  9491. };
  9492. /**
  9493. * Extracts the filename from a path
  9494. * @param path defines the path to use
  9495. * @returns the filename
  9496. */
  9497. Tools.GetFilename = function (path) {
  9498. var index = path.lastIndexOf("/");
  9499. if (index < 0)
  9500. return path;
  9501. return path.substring(index + 1);
  9502. };
  9503. /**
  9504. * Extracts the "folder" part of a path (everything before the filename).
  9505. * @param uri The URI to extract the info from
  9506. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  9507. * @returns The "folder" part of the path
  9508. */
  9509. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  9510. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  9511. var index = uri.lastIndexOf("/");
  9512. if (index < 0) {
  9513. if (returnUnchangedIfNoSlash) {
  9514. return uri;
  9515. }
  9516. return "";
  9517. }
  9518. return uri.substring(0, index + 1);
  9519. };
  9520. /**
  9521. * Extracts text content from a DOM element hierarchy
  9522. * @param element defines the root element
  9523. * @returns a string
  9524. */
  9525. Tools.GetDOMTextContent = function (element) {
  9526. var result = "";
  9527. var child = element.firstChild;
  9528. while (child) {
  9529. if (child.nodeType === 3) {
  9530. result += child.textContent;
  9531. }
  9532. child = child.nextSibling;
  9533. }
  9534. return result;
  9535. };
  9536. /**
  9537. * Convert an angle in radians to degrees
  9538. * @param angle defines the angle to convert
  9539. * @returns the angle in degrees
  9540. */
  9541. Tools.ToDegrees = function (angle) {
  9542. return angle * 180 / Math.PI;
  9543. };
  9544. /**
  9545. * Convert an angle in degrees to radians
  9546. * @param angle defines the angle to convert
  9547. * @returns the angle in radians
  9548. */
  9549. Tools.ToRadians = function (angle) {
  9550. return angle * Math.PI / 180;
  9551. };
  9552. /**
  9553. * Encode a buffer to a base64 string
  9554. * @param buffer defines the buffer to encode
  9555. * @returns the encoded string
  9556. */
  9557. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  9558. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  9559. var output = "";
  9560. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  9561. var i = 0;
  9562. var bytes = new Uint8Array(buffer);
  9563. while (i < bytes.length) {
  9564. chr1 = bytes[i++];
  9565. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  9566. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  9567. enc1 = chr1 >> 2;
  9568. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  9569. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  9570. enc4 = chr3 & 63;
  9571. if (isNaN(chr2)) {
  9572. enc3 = enc4 = 64;
  9573. }
  9574. else if (isNaN(chr3)) {
  9575. enc4 = 64;
  9576. }
  9577. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  9578. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  9579. }
  9580. return "data:image/png;base64," + output;
  9581. };
  9582. /**
  9583. * Extracts minimum and maximum values from a list of indexed positions
  9584. * @param positions defines the positions to use
  9585. * @param indices defines the indices to the positions
  9586. * @param indexStart defines the start index
  9587. * @param indexCount defines the end index
  9588. * @param bias defines bias value to add to the result
  9589. * @return minimum and maximum values
  9590. */
  9591. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  9592. if (bias === void 0) { bias = null; }
  9593. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9594. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9595. for (var index = indexStart; index < indexStart + indexCount; index++) {
  9596. var offset = indices[index] * 3;
  9597. var x = positions[offset];
  9598. var y = positions[offset + 1];
  9599. var z = positions[offset + 2];
  9600. minimum.minimizeInPlaceFromFloats(x, y, z);
  9601. maximum.maximizeInPlaceFromFloats(x, y, z);
  9602. }
  9603. if (bias) {
  9604. minimum.x -= minimum.x * bias.x + bias.y;
  9605. minimum.y -= minimum.y * bias.x + bias.y;
  9606. minimum.z -= minimum.z * bias.x + bias.y;
  9607. maximum.x += maximum.x * bias.x + bias.y;
  9608. maximum.y += maximum.y * bias.x + bias.y;
  9609. maximum.z += maximum.z * bias.x + bias.y;
  9610. }
  9611. return {
  9612. minimum: minimum,
  9613. maximum: maximum
  9614. };
  9615. };
  9616. /**
  9617. * Extracts minimum and maximum values from a list of positions
  9618. * @param positions defines the positions to use
  9619. * @param start defines the start index in the positions array
  9620. * @param count defines the number of positions to handle
  9621. * @param bias defines bias value to add to the result
  9622. * @param stride defines the stride size to use (distance between two positions in the positions array)
  9623. * @return minimum and maximum values
  9624. */
  9625. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  9626. if (bias === void 0) { bias = null; }
  9627. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  9628. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  9629. if (!stride) {
  9630. stride = 3;
  9631. }
  9632. for (var index = start, offset = start * stride; index < start + count; index++, offset += stride) {
  9633. var x = positions[offset];
  9634. var y = positions[offset + 1];
  9635. var z = positions[offset + 2];
  9636. minimum.minimizeInPlaceFromFloats(x, y, z);
  9637. maximum.maximizeInPlaceFromFloats(x, y, z);
  9638. }
  9639. if (bias) {
  9640. minimum.x -= minimum.x * bias.x + bias.y;
  9641. minimum.y -= minimum.y * bias.x + bias.y;
  9642. minimum.z -= minimum.z * bias.x + bias.y;
  9643. maximum.x += maximum.x * bias.x + bias.y;
  9644. maximum.y += maximum.y * bias.x + bias.y;
  9645. maximum.z += maximum.z * bias.x + bias.y;
  9646. }
  9647. return {
  9648. minimum: minimum,
  9649. maximum: maximum
  9650. };
  9651. };
  9652. /**
  9653. * Returns an array if obj is not an array
  9654. * @param obj defines the object to evaluate as an array
  9655. * @param allowsNullUndefined defines a boolean indicating if obj is allowed to be null or undefined
  9656. * @returns either obj directly if obj is an array or a new array containing obj
  9657. */
  9658. Tools.MakeArray = function (obj, allowsNullUndefined) {
  9659. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  9660. return null;
  9661. return Array.isArray(obj) ? obj : [obj];
  9662. };
  9663. /**
  9664. * Gets the pointer prefix to use
  9665. * @returns "pointer" if touch is enabled. Else returns "mouse"
  9666. */
  9667. Tools.GetPointerPrefix = function () {
  9668. var eventPrefix = "pointer";
  9669. // Check if pointer events are supported
  9670. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  9671. eventPrefix = "mouse";
  9672. }
  9673. return eventPrefix;
  9674. };
  9675. /**
  9676. * Queue a new function into the requested animation frame pool (ie. this function will be executed byt the browser for the next frame)
  9677. * @param func - the function to be called
  9678. * @param requester - the object that will request the next frame. Falls back to window.
  9679. * @returns frame number
  9680. */
  9681. Tools.QueueNewFrame = function (func, requester) {
  9682. if (!Tools.IsWindowObjectExist()) {
  9683. return setTimeout(func, 16);
  9684. }
  9685. if (!requester) {
  9686. requester = window;
  9687. }
  9688. if (requester.requestAnimationFrame) {
  9689. return requester.requestAnimationFrame(func);
  9690. }
  9691. else if (requester.msRequestAnimationFrame) {
  9692. return requester.msRequestAnimationFrame(func);
  9693. }
  9694. else if (requester.webkitRequestAnimationFrame) {
  9695. return requester.webkitRequestAnimationFrame(func);
  9696. }
  9697. else if (requester.mozRequestAnimationFrame) {
  9698. return requester.mozRequestAnimationFrame(func);
  9699. }
  9700. else if (requester.oRequestAnimationFrame) {
  9701. return requester.oRequestAnimationFrame(func);
  9702. }
  9703. else {
  9704. return window.setTimeout(func, 16);
  9705. }
  9706. };
  9707. /**
  9708. * Ask the browser to promote the current element to fullscreen rendering mode
  9709. * @param element defines the DOM element to promote
  9710. */
  9711. Tools.RequestFullscreen = function (element) {
  9712. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  9713. if (!requestFunction)
  9714. return;
  9715. requestFunction.call(element);
  9716. };
  9717. /**
  9718. * Asks the browser to exit fullscreen mode
  9719. */
  9720. Tools.ExitFullscreen = function () {
  9721. if (document.exitFullscreen) {
  9722. document.exitFullscreen();
  9723. }
  9724. else if (document.mozCancelFullScreen) {
  9725. document.mozCancelFullScreen();
  9726. }
  9727. else if (document.webkitCancelFullScreen) {
  9728. document.webkitCancelFullScreen();
  9729. }
  9730. else if (document.msCancelFullScreen) {
  9731. document.msCancelFullScreen();
  9732. }
  9733. };
  9734. /**
  9735. * Sets the cors behavior on a dom element. This will add the required Tools.CorsBehavior to the element.
  9736. * @param url define the url we are trying
  9737. * @param element define the dom element where to configure the cors policy
  9738. */
  9739. Tools.SetCorsBehavior = function (url, element) {
  9740. if (url && url.indexOf("data:") === 0) {
  9741. return;
  9742. }
  9743. if (Tools.CorsBehavior) {
  9744. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9745. element.crossOrigin = Tools.CorsBehavior;
  9746. }
  9747. else {
  9748. var result = Tools.CorsBehavior(url);
  9749. if (result) {
  9750. element.crossOrigin = result;
  9751. }
  9752. }
  9753. }
  9754. };
  9755. // External files
  9756. /**
  9757. * Removes unwanted characters from an url
  9758. * @param url defines the url to clean
  9759. * @returns the cleaned url
  9760. */
  9761. Tools.CleanUrl = function (url) {
  9762. url = url.replace(/#/mg, "%23");
  9763. return url;
  9764. };
  9765. /**
  9766. * Loads an image as an HTMLImageElement.
  9767. * @param input url string, ArrayBuffer, or Blob to load
  9768. * @param onLoad callback called when the image successfully loads
  9769. * @param onError callback called when the image fails to load
  9770. * @param database database for caching
  9771. * @returns the HTMLImageElement of the loaded image
  9772. */
  9773. Tools.LoadImage = function (input, onLoad, onError, database) {
  9774. var url;
  9775. var usingObjectURL = false;
  9776. if (input instanceof ArrayBuffer) {
  9777. url = URL.createObjectURL(new Blob([input]));
  9778. usingObjectURL = true;
  9779. }
  9780. else if (input instanceof Blob) {
  9781. url = URL.createObjectURL(input);
  9782. usingObjectURL = true;
  9783. }
  9784. else {
  9785. url = Tools.CleanUrl(input);
  9786. url = Tools.PreprocessUrl(input);
  9787. }
  9788. var img = new Image();
  9789. Tools.SetCorsBehavior(url, img);
  9790. var loadHandler = function () {
  9791. if (usingObjectURL && img.src) {
  9792. URL.revokeObjectURL(img.src);
  9793. }
  9794. img.removeEventListener("load", loadHandler);
  9795. img.removeEventListener("error", errorHandler);
  9796. onLoad(img);
  9797. };
  9798. var errorHandler = function (err) {
  9799. if (usingObjectURL && img.src) {
  9800. URL.revokeObjectURL(img.src);
  9801. }
  9802. img.removeEventListener("load", loadHandler);
  9803. img.removeEventListener("error", errorHandler);
  9804. Tools.Error("Error while trying to load image: " + input);
  9805. if (onError) {
  9806. onError("Error while trying to load image: " + input, err);
  9807. }
  9808. };
  9809. img.addEventListener("load", loadHandler);
  9810. img.addEventListener("error", errorHandler);
  9811. var noIndexedDB = function () {
  9812. img.src = url;
  9813. };
  9814. var loadFromIndexedDB = function () {
  9815. if (database) {
  9816. database.loadImageFromDB(url, img);
  9817. }
  9818. };
  9819. //ANY database to do!
  9820. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9821. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9822. }
  9823. else {
  9824. if (url.indexOf("file:") !== -1) {
  9825. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9826. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9827. try {
  9828. var blobURL;
  9829. try {
  9830. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9831. }
  9832. catch (ex) {
  9833. // Chrome doesn't support oneTimeOnly parameter
  9834. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9835. }
  9836. img.src = blobURL;
  9837. usingObjectURL = true;
  9838. }
  9839. catch (e) {
  9840. img.src = "";
  9841. }
  9842. return img;
  9843. }
  9844. }
  9845. noIndexedDB();
  9846. }
  9847. return img;
  9848. };
  9849. /**
  9850. * Loads a file
  9851. * @param url url string, ArrayBuffer, or Blob to load
  9852. * @param onSuccess callback called when the file successfully loads
  9853. * @param onProgress callback called while file is loading (if the server supports this mode)
  9854. * @param database database for caching
  9855. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer
  9856. * @param onError callback called when the file fails to load
  9857. * @returns a file request object
  9858. */
  9859. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9860. url = Tools.CleanUrl(url);
  9861. url = Tools.PreprocessUrl(url);
  9862. // If file and file input are set
  9863. if (url.indexOf("file:") !== -1) {
  9864. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9865. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9866. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9867. }
  9868. }
  9869. var loadUrl = Tools.BaseUrl + url;
  9870. var aborted = false;
  9871. var fileRequest = {
  9872. onCompleteObservable: new BABYLON.Observable(),
  9873. abort: function () { return aborted = true; },
  9874. };
  9875. var requestFile = function () {
  9876. var request = new XMLHttpRequest();
  9877. var retryHandle = null;
  9878. fileRequest.abort = function () {
  9879. aborted = true;
  9880. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9881. request.abort();
  9882. }
  9883. if (retryHandle !== null) {
  9884. clearTimeout(retryHandle);
  9885. retryHandle = null;
  9886. }
  9887. };
  9888. var retryLoop = function (retryIndex) {
  9889. request.open('GET', loadUrl, true);
  9890. if (useArrayBuffer) {
  9891. request.responseType = "arraybuffer";
  9892. }
  9893. if (onProgress) {
  9894. request.addEventListener("progress", onProgress);
  9895. }
  9896. var onLoadEnd = function () {
  9897. request.removeEventListener("loadend", onLoadEnd);
  9898. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9899. fileRequest.onCompleteObservable.clear();
  9900. };
  9901. request.addEventListener("loadend", onLoadEnd);
  9902. var onReadyStateChange = function () {
  9903. if (aborted) {
  9904. return;
  9905. }
  9906. // In case of undefined state in some browsers.
  9907. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9908. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9909. request.removeEventListener("readystatechange", onReadyStateChange);
  9910. if ((request.status >= 200 && request.status < 300) || (request.status === 0 && (!Tools.IsWindowObjectExist() || Tools.IsFileURL()))) {
  9911. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9912. return;
  9913. }
  9914. var retryStrategy = Tools.DefaultRetryStrategy;
  9915. if (retryStrategy) {
  9916. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9917. if (waitTime !== -1) {
  9918. // Prevent the request from completing for retry.
  9919. request.removeEventListener("loadend", onLoadEnd);
  9920. request = new XMLHttpRequest();
  9921. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9922. return;
  9923. }
  9924. }
  9925. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9926. if (onError) {
  9927. onError(request, e);
  9928. }
  9929. else {
  9930. throw e;
  9931. }
  9932. }
  9933. };
  9934. request.addEventListener("readystatechange", onReadyStateChange);
  9935. request.send();
  9936. };
  9937. retryLoop(0);
  9938. };
  9939. // Caching all files
  9940. if (database && database.enableSceneOffline) {
  9941. var noIndexedDB_1 = function (request) {
  9942. if (request && request.status > 400) {
  9943. if (onError) {
  9944. onError(request);
  9945. }
  9946. }
  9947. else {
  9948. if (!aborted) {
  9949. requestFile();
  9950. }
  9951. }
  9952. };
  9953. var loadFromIndexedDB = function () {
  9954. // TODO: database needs to support aborting and should return a IFileRequest
  9955. if (aborted) {
  9956. return;
  9957. }
  9958. if (database) {
  9959. database.loadFileFromDB(url, function (data) {
  9960. if (!aborted) {
  9961. onSuccess(data);
  9962. }
  9963. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9964. }, onProgress ? function (event) {
  9965. if (!aborted) {
  9966. onProgress(event);
  9967. }
  9968. } : undefined, noIndexedDB_1, useArrayBuffer);
  9969. }
  9970. };
  9971. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9972. }
  9973. else {
  9974. requestFile();
  9975. }
  9976. return fileRequest;
  9977. };
  9978. /**
  9979. * Load a script (identified by an url). When the url returns, the
  9980. * content of this file is added into a new script element, attached to the DOM (body element)
  9981. * @param scriptUrl defines the url of the script to laod
  9982. * @param onSuccess defines the callback called when the script is loaded
  9983. * @param onError defines the callback to call if an error occurs
  9984. */
  9985. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9986. if (!Tools.IsWindowObjectExist()) {
  9987. return;
  9988. }
  9989. var head = document.getElementsByTagName('head')[0];
  9990. var script = document.createElement('script');
  9991. script.type = 'text/javascript';
  9992. script.src = scriptUrl;
  9993. script.onload = function () {
  9994. if (onSuccess) {
  9995. onSuccess();
  9996. }
  9997. };
  9998. script.onerror = function (e) {
  9999. if (onError) {
  10000. onError("Unable to load script '" + scriptUrl + "'", e);
  10001. }
  10002. };
  10003. head.appendChild(script);
  10004. };
  10005. /**
  10006. * Loads a file from a blob
  10007. * @param fileToLoad defines the blob to use
  10008. * @param callback defines the callback to call when data is loaded
  10009. * @param progressCallback defines the callback to call during loading process
  10010. * @returns a file request object
  10011. */
  10012. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  10013. var reader = new FileReader();
  10014. var request = {
  10015. onCompleteObservable: new BABYLON.Observable(),
  10016. abort: function () { return reader.abort(); },
  10017. };
  10018. reader.onloadend = function (e) {
  10019. request.onCompleteObservable.notifyObservers(request);
  10020. };
  10021. reader.onload = function (e) {
  10022. //target doesn't have result from ts 1.3
  10023. callback(e.target['result']);
  10024. };
  10025. reader.onprogress = progressCallback;
  10026. reader.readAsDataURL(fileToLoad);
  10027. return request;
  10028. };
  10029. /**
  10030. * Loads a file
  10031. * @param fileToLoad defines the file to load
  10032. * @param callback defines the callback to call when data is loaded
  10033. * @param progressCallBack defines the callback to call during loading process
  10034. * @param useArrayBuffer defines a boolean indicating that data must be returned as an ArrayBuffer
  10035. * @returns a file request object
  10036. */
  10037. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  10038. var reader = new FileReader();
  10039. var request = {
  10040. onCompleteObservable: new BABYLON.Observable(),
  10041. abort: function () { return reader.abort(); },
  10042. };
  10043. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  10044. reader.onerror = function (e) {
  10045. Tools.Log("Error while reading file: " + fileToLoad.name);
  10046. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  10047. };
  10048. reader.onload = function (e) {
  10049. //target doesn't have result from ts 1.3
  10050. callback(e.target['result']);
  10051. };
  10052. if (progressCallBack) {
  10053. reader.onprogress = progressCallBack;
  10054. }
  10055. if (!useArrayBuffer) {
  10056. // Asynchronous read
  10057. reader.readAsText(fileToLoad);
  10058. }
  10059. else {
  10060. reader.readAsArrayBuffer(fileToLoad);
  10061. }
  10062. return request;
  10063. };
  10064. /**
  10065. * Creates a data url from a given string content
  10066. * @param content defines the content to convert
  10067. * @returns the new data url link
  10068. */
  10069. Tools.FileAsURL = function (content) {
  10070. var fileBlob = new Blob([content]);
  10071. var url = window.URL || window.webkitURL;
  10072. var link = url.createObjectURL(fileBlob);
  10073. return link;
  10074. };
  10075. /**
  10076. * Format the given number to a specific decimal format
  10077. * @param value defines the number to format
  10078. * @param decimals defines the number of decimals to use
  10079. * @returns the formatted string
  10080. */
  10081. Tools.Format = function (value, decimals) {
  10082. if (decimals === void 0) { decimals = 2; }
  10083. return value.toFixed(decimals);
  10084. };
  10085. /**
  10086. * Checks if a given vector is inside a specific range
  10087. * @param v defines the vector to test
  10088. * @param min defines the minimum range
  10089. * @param max defines the maximum range
  10090. */
  10091. Tools.CheckExtends = function (v, min, max) {
  10092. if (v.x < min.x)
  10093. min.x = v.x;
  10094. if (v.y < min.y)
  10095. min.y = v.y;
  10096. if (v.z < min.z)
  10097. min.z = v.z;
  10098. if (v.x > max.x)
  10099. max.x = v.x;
  10100. if (v.y > max.y)
  10101. max.y = v.y;
  10102. if (v.z > max.z)
  10103. max.z = v.z;
  10104. };
  10105. /**
  10106. * Tries to copy an object by duplicating every property
  10107. * @param source defines the source object
  10108. * @param destination defines the target object
  10109. * @param doNotCopyList defines a list of properties to avoid
  10110. * @param mustCopyList defines a list of properties to copy (even if they start with _)
  10111. */
  10112. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  10113. for (var prop in source) {
  10114. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  10115. continue;
  10116. }
  10117. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  10118. continue;
  10119. }
  10120. var sourceValue = source[prop];
  10121. var typeOfSourceValue = typeof sourceValue;
  10122. if (typeOfSourceValue === "function") {
  10123. continue;
  10124. }
  10125. try {
  10126. if (typeOfSourceValue === "object") {
  10127. if (sourceValue instanceof Array) {
  10128. destination[prop] = [];
  10129. if (sourceValue.length > 0) {
  10130. if (typeof sourceValue[0] == "object") {
  10131. for (var index = 0; index < sourceValue.length; index++) {
  10132. var clonedValue = cloneValue(sourceValue[index], destination);
  10133. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  10134. destination[prop].push(clonedValue);
  10135. }
  10136. }
  10137. }
  10138. else {
  10139. destination[prop] = sourceValue.slice(0);
  10140. }
  10141. }
  10142. }
  10143. else {
  10144. destination[prop] = cloneValue(sourceValue, destination);
  10145. }
  10146. }
  10147. else {
  10148. destination[prop] = sourceValue;
  10149. }
  10150. }
  10151. catch (e) {
  10152. // Just ignore error (it could be because of a read-only property)
  10153. }
  10154. }
  10155. };
  10156. /**
  10157. * Gets a boolean indicating if the given object has no own property
  10158. * @param obj defines the object to test
  10159. * @returns true if object has no own property
  10160. */
  10161. Tools.IsEmpty = function (obj) {
  10162. for (var i in obj) {
  10163. if (obj.hasOwnProperty(i)) {
  10164. return false;
  10165. }
  10166. }
  10167. return true;
  10168. };
  10169. /**
  10170. * Function used to register events at window level
  10171. * @param events defines the events to register
  10172. */
  10173. Tools.RegisterTopRootEvents = function (events) {
  10174. for (var index = 0; index < events.length; index++) {
  10175. var event = events[index];
  10176. window.addEventListener(event.name, event.handler, false);
  10177. try {
  10178. if (window.parent) {
  10179. window.parent.addEventListener(event.name, event.handler, false);
  10180. }
  10181. }
  10182. catch (e) {
  10183. // Silently fails...
  10184. }
  10185. }
  10186. };
  10187. /**
  10188. * Function used to unregister events from window level
  10189. * @param events defines the events to unregister
  10190. */
  10191. Tools.UnregisterTopRootEvents = function (events) {
  10192. for (var index = 0; index < events.length; index++) {
  10193. var event = events[index];
  10194. window.removeEventListener(event.name, event.handler);
  10195. try {
  10196. if (window.parent) {
  10197. window.parent.removeEventListener(event.name, event.handler);
  10198. }
  10199. }
  10200. catch (e) {
  10201. // Silently fails...
  10202. }
  10203. }
  10204. };
  10205. /**
  10206. * Dumps the current bound framebuffer
  10207. * @param width defines the rendering width
  10208. * @param height defines the rendering height
  10209. * @param engine defines the hosting engine
  10210. * @param successCallback defines the callback triggered once the data are available
  10211. * @param mimeType defines the mime type of the result
  10212. * @param fileName defines the filename to download. If present, the result will automatically be downloaded
  10213. */
  10214. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  10215. if (mimeType === void 0) { mimeType = "image/png"; }
  10216. // Read the contents of the framebuffer
  10217. var numberOfChannelsByLine = width * 4;
  10218. var halfHeight = height / 2;
  10219. //Reading datas from WebGL
  10220. var data = engine.readPixels(0, 0, width, height);
  10221. //To flip image on Y axis.
  10222. for (var i = 0; i < halfHeight; i++) {
  10223. for (var j = 0; j < numberOfChannelsByLine; j++) {
  10224. var currentCell = j + i * numberOfChannelsByLine;
  10225. var targetLine = height - i - 1;
  10226. var targetCell = j + targetLine * numberOfChannelsByLine;
  10227. var temp = data[currentCell];
  10228. data[currentCell] = data[targetCell];
  10229. data[targetCell] = temp;
  10230. }
  10231. }
  10232. // Create a 2D canvas to store the result
  10233. if (!screenshotCanvas) {
  10234. screenshotCanvas = document.createElement('canvas');
  10235. }
  10236. screenshotCanvas.width = width;
  10237. screenshotCanvas.height = height;
  10238. var context = screenshotCanvas.getContext('2d');
  10239. if (context) {
  10240. // Copy the pixels to a 2D canvas
  10241. var imageData = context.createImageData(width, height);
  10242. var castData = (imageData.data);
  10243. castData.set(data);
  10244. context.putImageData(imageData, 0, 0);
  10245. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  10246. }
  10247. };
  10248. /**
  10249. * Converts the canvas data to blob.
  10250. * This acts as a polyfill for browsers not supporting the to blob function.
  10251. * @param canvas Defines the canvas to extract the data from
  10252. * @param successCallback Defines the callback triggered once the data are available
  10253. * @param mimeType Defines the mime type of the result
  10254. */
  10255. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  10256. if (mimeType === void 0) { mimeType = "image/png"; }
  10257. // We need HTMLCanvasElement.toBlob for HD screenshots
  10258. if (!canvas.toBlob) {
  10259. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  10260. canvas.toBlob = function (callback, type, quality) {
  10261. var _this = this;
  10262. setTimeout(function () {
  10263. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  10264. for (var i = 0; i < len; i++) {
  10265. arr[i] = binStr.charCodeAt(i);
  10266. }
  10267. callback(new Blob([arr]));
  10268. });
  10269. };
  10270. }
  10271. canvas.toBlob(function (blob) {
  10272. successCallback(blob);
  10273. }, mimeType);
  10274. };
  10275. /**
  10276. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  10277. * @param successCallback defines the callback triggered once the data are available
  10278. * @param mimeType defines the mime type of the result
  10279. * @param fileName defines he filename to download. If present, the result will automatically be downloaded
  10280. */
  10281. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  10282. if (mimeType === void 0) { mimeType = "image/png"; }
  10283. if (successCallback) {
  10284. var base64Image = screenshotCanvas.toDataURL(mimeType);
  10285. successCallback(base64Image);
  10286. }
  10287. else {
  10288. this.ToBlob(screenshotCanvas, function (blob) {
  10289. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  10290. if (("download" in document.createElement("a"))) {
  10291. if (!fileName) {
  10292. var date = new Date();
  10293. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  10294. fileName = "screenshot_" + stringDate + ".png";
  10295. }
  10296. Tools.Download(blob, fileName);
  10297. }
  10298. else {
  10299. var url = URL.createObjectURL(blob);
  10300. var newWindow = window.open("");
  10301. if (!newWindow)
  10302. return;
  10303. var img = newWindow.document.createElement("img");
  10304. img.onload = function () {
  10305. // no longer need to read the blob so it's revoked
  10306. URL.revokeObjectURL(url);
  10307. };
  10308. img.src = url;
  10309. newWindow.document.body.appendChild(img);
  10310. }
  10311. }, mimeType);
  10312. }
  10313. };
  10314. /**
  10315. * Downloads a blob in the browser
  10316. * @param blob defines the blob to download
  10317. * @param fileName defines the name of the downloaded file
  10318. */
  10319. Tools.Download = function (blob, fileName) {
  10320. if (navigator && navigator.msSaveBlob) {
  10321. navigator.msSaveBlob(blob, fileName);
  10322. return;
  10323. }
  10324. var url = window.URL.createObjectURL(blob);
  10325. var a = document.createElement("a");
  10326. document.body.appendChild(a);
  10327. a.style.display = "none";
  10328. a.href = url;
  10329. a.download = fileName;
  10330. a.addEventListener("click", function () {
  10331. if (a.parentElement) {
  10332. a.parentElement.removeChild(a);
  10333. }
  10334. });
  10335. a.click();
  10336. window.URL.revokeObjectURL(url);
  10337. };
  10338. /**
  10339. * Captures a screenshot of the current rendering
  10340. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10341. * @param engine defines the rendering engine
  10342. * @param camera defines the source camera
  10343. * @param size This parameter can be set to a single number or to an object with the
  10344. * following (optional) properties: precision, width, height. If a single number is passed,
  10345. * it will be used for both width and height. If an object is passed, the screenshot size
  10346. * will be derived from the parameters. The precision property is a multiplier allowing
  10347. * rendering at a higher or lower resolution
  10348. * @param successCallback defines the callback receives a single parameter which contains the
  10349. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10350. * src parameter of an <img> to display it
  10351. * @param mimeType defines the MIME type of the screenshot image (default: image/png).
  10352. * Check your browser for supported MIME types
  10353. */
  10354. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  10355. if (mimeType === void 0) { mimeType = "image/png"; }
  10356. var width;
  10357. var height;
  10358. // If a precision value is specified
  10359. if (size.precision) {
  10360. width = Math.round(engine.getRenderWidth() * size.precision);
  10361. height = Math.round(width / engine.getAspectRatio(camera));
  10362. }
  10363. else if (size.width && size.height) {
  10364. width = size.width;
  10365. height = size.height;
  10366. }
  10367. //If passing only width, computing height to keep display canvas ratio.
  10368. else if (size.width && !size.height) {
  10369. width = size.width;
  10370. height = Math.round(width / engine.getAspectRatio(camera));
  10371. }
  10372. //If passing only height, computing width to keep display canvas ratio.
  10373. else if (size.height && !size.width) {
  10374. height = size.height;
  10375. width = Math.round(height * engine.getAspectRatio(camera));
  10376. }
  10377. //Assuming here that "size" parameter is a number
  10378. else if (!isNaN(size)) {
  10379. height = size;
  10380. width = size;
  10381. }
  10382. else {
  10383. Tools.Error("Invalid 'size' parameter !");
  10384. return;
  10385. }
  10386. if (!screenshotCanvas) {
  10387. screenshotCanvas = document.createElement('canvas');
  10388. }
  10389. screenshotCanvas.width = width;
  10390. screenshotCanvas.height = height;
  10391. var renderContext = screenshotCanvas.getContext("2d");
  10392. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  10393. var newWidth = width;
  10394. var newHeight = newWidth / ratio;
  10395. if (newHeight > height) {
  10396. newHeight = height;
  10397. newWidth = newHeight * ratio;
  10398. }
  10399. var offsetX = Math.max(0, width - newWidth) / 2;
  10400. var offsetY = Math.max(0, height - newHeight) / 2;
  10401. var renderingCanvas = engine.getRenderingCanvas();
  10402. if (renderContext && renderingCanvas) {
  10403. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  10404. }
  10405. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  10406. };
  10407. /**
  10408. * Generates an image screenshot from the specified camera.
  10409. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_png
  10410. * @param engine The engine to use for rendering
  10411. * @param camera The camera to use for rendering
  10412. * @param size This parameter can be set to a single number or to an object with the
  10413. * following (optional) properties: precision, width, height. If a single number is passed,
  10414. * it will be used for both width and height. If an object is passed, the screenshot size
  10415. * will be derived from the parameters. The precision property is a multiplier allowing
  10416. * rendering at a higher or lower resolution
  10417. * @param successCallback The callback receives a single parameter which contains the
  10418. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  10419. * src parameter of an <img> to display it
  10420. * @param mimeType The MIME type of the screenshot image (default: image/png).
  10421. * Check your browser for supported MIME types
  10422. * @param samples Texture samples (default: 1)
  10423. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  10424. * @param fileName A name for for the downloaded file.
  10425. */
  10426. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  10427. if (mimeType === void 0) { mimeType = "image/png"; }
  10428. if (samples === void 0) { samples = 1; }
  10429. if (antialiasing === void 0) { antialiasing = false; }
  10430. var width;
  10431. var height;
  10432. //If a precision value is specified
  10433. if (size.precision) {
  10434. width = Math.round(engine.getRenderWidth() * size.precision);
  10435. height = Math.round(width / engine.getAspectRatio(camera));
  10436. size = { width: width, height: height };
  10437. }
  10438. else if (size.width && size.height) {
  10439. width = size.width;
  10440. height = size.height;
  10441. }
  10442. //If passing only width, computing height to keep display canvas ratio.
  10443. else if (size.width && !size.height) {
  10444. width = size.width;
  10445. height = Math.round(width / engine.getAspectRatio(camera));
  10446. size = { width: width, height: height };
  10447. }
  10448. //If passing only height, computing width to keep display canvas ratio.
  10449. else if (size.height && !size.width) {
  10450. height = size.height;
  10451. width = Math.round(height * engine.getAspectRatio(camera));
  10452. size = { width: width, height: height };
  10453. }
  10454. //Assuming here that "size" parameter is a number
  10455. else if (!isNaN(size)) {
  10456. height = size;
  10457. width = size;
  10458. }
  10459. else {
  10460. Tools.Error("Invalid 'size' parameter !");
  10461. return;
  10462. }
  10463. var scene = camera.getScene();
  10464. var previousCamera = null;
  10465. if (scene.activeCamera !== camera) {
  10466. previousCamera = scene.activeCamera;
  10467. scene.activeCamera = camera;
  10468. }
  10469. // At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  10470. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  10471. texture.renderList = null;
  10472. texture.samples = samples;
  10473. if (antialiasing) {
  10474. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  10475. }
  10476. texture.onAfterRenderObservable.add(function () {
  10477. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  10478. });
  10479. scene.incrementRenderId();
  10480. scene.resetCachedMaterial();
  10481. texture.render(true);
  10482. texture.dispose();
  10483. if (previousCamera) {
  10484. scene.activeCamera = previousCamera;
  10485. }
  10486. camera.getProjectionMatrix(true); // Force cache refresh;
  10487. };
  10488. /**
  10489. * Validates if xhr data is correct
  10490. * @param xhr defines the request to validate
  10491. * @param dataType defines the expected data type
  10492. * @returns true if data is correct
  10493. */
  10494. Tools.ValidateXHRData = function (xhr, dataType) {
  10495. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  10496. if (dataType === void 0) { dataType = 7; }
  10497. try {
  10498. if (dataType & 1) {
  10499. if (xhr.responseText && xhr.responseText.length > 0) {
  10500. return true;
  10501. }
  10502. else if (dataType === 1) {
  10503. return false;
  10504. }
  10505. }
  10506. if (dataType & 2) {
  10507. // Check header width and height since there is no "TGA" magic number
  10508. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  10509. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  10510. return true;
  10511. }
  10512. else if (dataType === 2) {
  10513. return false;
  10514. }
  10515. }
  10516. if (dataType & 4) {
  10517. // Check for the "DDS" magic number
  10518. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  10519. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  10520. return true;
  10521. }
  10522. else {
  10523. return false;
  10524. }
  10525. }
  10526. }
  10527. catch (e) {
  10528. // Global protection
  10529. }
  10530. return false;
  10531. };
  10532. /**
  10533. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  10534. * Be aware Math.random() could cause collisions, but:
  10535. * "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"
  10536. * @returns a pseudo random id
  10537. */
  10538. Tools.RandomId = function () {
  10539. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  10540. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  10541. return v.toString(16);
  10542. });
  10543. };
  10544. /**
  10545. * Test if the given uri is a base64 string
  10546. * @param uri The uri to test
  10547. * @return True if the uri is a base64 string or false otherwise
  10548. */
  10549. Tools.IsBase64 = function (uri) {
  10550. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  10551. };
  10552. /**
  10553. * Decode the given base64 uri.
  10554. * @param uri The uri to decode
  10555. * @return The decoded base64 data.
  10556. */
  10557. Tools.DecodeBase64 = function (uri) {
  10558. var decodedString = atob(uri.split(",")[1]);
  10559. var bufferLength = decodedString.length;
  10560. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  10561. for (var i = 0; i < bufferLength; i++) {
  10562. bufferView[i] = decodedString.charCodeAt(i);
  10563. }
  10564. return bufferView.buffer;
  10565. };
  10566. Tools._AddLogEntry = function (entry) {
  10567. Tools._LogCache = entry + Tools._LogCache;
  10568. if (Tools.OnNewCacheEntry) {
  10569. Tools.OnNewCacheEntry(entry);
  10570. }
  10571. };
  10572. Tools._FormatMessage = function (message) {
  10573. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  10574. var date = new Date();
  10575. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  10576. };
  10577. Tools._LogDisabled = function (message) {
  10578. // nothing to do
  10579. };
  10580. Tools._LogEnabled = function (message) {
  10581. var formattedMessage = Tools._FormatMessage(message);
  10582. console.log("BJS - " + formattedMessage);
  10583. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  10584. Tools._AddLogEntry(entry);
  10585. };
  10586. Tools._WarnDisabled = function (message) {
  10587. // nothing to do
  10588. };
  10589. Tools._WarnEnabled = function (message) {
  10590. var formattedMessage = Tools._FormatMessage(message);
  10591. console.warn("BJS - " + formattedMessage);
  10592. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  10593. Tools._AddLogEntry(entry);
  10594. };
  10595. Tools._ErrorDisabled = function (message) {
  10596. // nothing to do
  10597. };
  10598. Tools._ErrorEnabled = function (message) {
  10599. Tools.errorsCount++;
  10600. var formattedMessage = Tools._FormatMessage(message);
  10601. console.error("BJS - " + formattedMessage);
  10602. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  10603. Tools._AddLogEntry(entry);
  10604. };
  10605. Object.defineProperty(Tools, "LogCache", {
  10606. /**
  10607. * Gets current log cache (list of logs)
  10608. */
  10609. get: function () {
  10610. return Tools._LogCache;
  10611. },
  10612. enumerable: true,
  10613. configurable: true
  10614. });
  10615. /**
  10616. * Clears the log cache
  10617. */
  10618. Tools.ClearLogCache = function () {
  10619. Tools._LogCache = "";
  10620. Tools.errorsCount = 0;
  10621. };
  10622. Object.defineProperty(Tools, "LogLevels", {
  10623. /**
  10624. * Sets the current log level (MessageLogLevel / WarningLogLevel / ErrorLogLevel)
  10625. */
  10626. set: function (level) {
  10627. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  10628. Tools.Log = Tools._LogEnabled;
  10629. }
  10630. else {
  10631. Tools.Log = Tools._LogDisabled;
  10632. }
  10633. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  10634. Tools.Warn = Tools._WarnEnabled;
  10635. }
  10636. else {
  10637. Tools.Warn = Tools._WarnDisabled;
  10638. }
  10639. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  10640. Tools.Error = Tools._ErrorEnabled;
  10641. }
  10642. else {
  10643. Tools.Error = Tools._ErrorDisabled;
  10644. }
  10645. },
  10646. enumerable: true,
  10647. configurable: true
  10648. });
  10649. /**
  10650. * Checks if the loaded document was accessed via `file:`-Protocol.
  10651. * @returns boolean
  10652. */
  10653. Tools.IsFileURL = function () {
  10654. return location.protocol === "file:";
  10655. };
  10656. /**
  10657. * Checks if the window object exists
  10658. * @returns true if the window object exists
  10659. */
  10660. Tools.IsWindowObjectExist = function () {
  10661. return (typeof window) !== "undefined";
  10662. };
  10663. Object.defineProperty(Tools, "PerformanceLogLevel", {
  10664. /**
  10665. * Sets the current performance log level
  10666. */
  10667. set: function (level) {
  10668. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  10669. Tools.StartPerformanceCounter = Tools._StartUserMark;
  10670. Tools.EndPerformanceCounter = Tools._EndUserMark;
  10671. return;
  10672. }
  10673. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  10674. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  10675. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  10676. return;
  10677. }
  10678. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10679. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10680. },
  10681. enumerable: true,
  10682. configurable: true
  10683. });
  10684. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  10685. };
  10686. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  10687. };
  10688. Tools._StartUserMark = function (counterName, condition) {
  10689. if (condition === void 0) { condition = true; }
  10690. if (!Tools._performance) {
  10691. if (!Tools.IsWindowObjectExist()) {
  10692. return;
  10693. }
  10694. Tools._performance = window.performance;
  10695. }
  10696. if (!condition || !Tools._performance.mark) {
  10697. return;
  10698. }
  10699. Tools._performance.mark(counterName + "-Begin");
  10700. };
  10701. Tools._EndUserMark = function (counterName, condition) {
  10702. if (condition === void 0) { condition = true; }
  10703. if (!condition || !Tools._performance.mark) {
  10704. return;
  10705. }
  10706. Tools._performance.mark(counterName + "-End");
  10707. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  10708. };
  10709. Tools._StartPerformanceConsole = function (counterName, condition) {
  10710. if (condition === void 0) { condition = true; }
  10711. if (!condition) {
  10712. return;
  10713. }
  10714. Tools._StartUserMark(counterName, condition);
  10715. if (console.time) {
  10716. console.time(counterName);
  10717. }
  10718. };
  10719. Tools._EndPerformanceConsole = function (counterName, condition) {
  10720. if (condition === void 0) { condition = true; }
  10721. if (!condition) {
  10722. return;
  10723. }
  10724. Tools._EndUserMark(counterName, condition);
  10725. if (console.time) {
  10726. console.timeEnd(counterName);
  10727. }
  10728. };
  10729. Object.defineProperty(Tools, "Now", {
  10730. /**
  10731. * Gets either window.performance.now() if supported or Date.now() else
  10732. */
  10733. get: function () {
  10734. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  10735. return window.performance.now();
  10736. }
  10737. return Date.now();
  10738. },
  10739. enumerable: true,
  10740. configurable: true
  10741. });
  10742. /**
  10743. * This method will return the name of the class used to create the instance of the given object.
  10744. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  10745. * @param object the object to get the class name from
  10746. * @param isType defines if the object is actually a type
  10747. * @returns the name of the class, will be "object" for a custom data type not using the @className decorator
  10748. */
  10749. Tools.GetClassName = function (object, isType) {
  10750. if (isType === void 0) { isType = false; }
  10751. var name = null;
  10752. if (!isType && object.getClassName) {
  10753. name = object.getClassName();
  10754. }
  10755. else {
  10756. if (object instanceof Object) {
  10757. var classObj = isType ? object : Object.getPrototypeOf(object);
  10758. name = classObj.constructor["__bjsclassName__"];
  10759. }
  10760. if (!name) {
  10761. name = typeof object;
  10762. }
  10763. }
  10764. return name;
  10765. };
  10766. /**
  10767. * Gets the first element of an array satisfying a given predicate
  10768. * @param array defines the array to browse
  10769. * @param predicate defines the predicate to use
  10770. * @returns null if not found or the element
  10771. */
  10772. Tools.First = function (array, predicate) {
  10773. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  10774. var el = array_1[_i];
  10775. if (predicate(el)) {
  10776. return el;
  10777. }
  10778. }
  10779. return null;
  10780. };
  10781. /**
  10782. * This method will return the name of the full name of the class, including its owning module (if any).
  10783. * 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).
  10784. * @param object the object to get the class name from
  10785. * @param isType defines if the object is actually a type
  10786. * @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.
  10787. * @ignorenaming
  10788. */
  10789. Tools.getFullClassName = function (object, isType) {
  10790. if (isType === void 0) { isType = false; }
  10791. var className = null;
  10792. var moduleName = null;
  10793. if (!isType && object.getClassName) {
  10794. className = object.getClassName();
  10795. }
  10796. else {
  10797. if (object instanceof Object) {
  10798. var classObj = isType ? object : Object.getPrototypeOf(object);
  10799. className = classObj.constructor["__bjsclassName__"];
  10800. moduleName = classObj.constructor["__bjsmoduleName__"];
  10801. }
  10802. if (!className) {
  10803. className = typeof object;
  10804. }
  10805. }
  10806. if (!className) {
  10807. return null;
  10808. }
  10809. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  10810. };
  10811. /**
  10812. * Returns a promise that resolves after the given amount of time.
  10813. * @param delay Number of milliseconds to delay
  10814. * @returns Promise that resolves after the given amount of time
  10815. */
  10816. Tools.DelayAsync = function (delay) {
  10817. return new Promise(function (resolve) {
  10818. setTimeout(function () {
  10819. resolve();
  10820. }, delay);
  10821. });
  10822. };
  10823. /**
  10824. * Gets the current gradient from an array of IValueGradient
  10825. * @param ratio defines the current ratio to get
  10826. * @param gradients defines the array of IValueGradient
  10827. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10828. */
  10829. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10830. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10831. var currentGradient = gradients[gradientIndex];
  10832. var nextGradient = gradients[gradientIndex + 1];
  10833. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10834. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10835. updateFunc(currentGradient, nextGradient, scale);
  10836. return;
  10837. }
  10838. }
  10839. // Use last index if over
  10840. var lastIndex = gradients.length - 1;
  10841. updateFunc(gradients[lastIndex], gradients[lastIndex], 1.0);
  10842. };
  10843. /**
  10844. * Gets or sets the base URL to use to load assets
  10845. */
  10846. Tools.BaseUrl = "";
  10847. /**
  10848. * Gets or sets the retry strategy to apply when an error happens while loading an asset
  10849. */
  10850. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10851. /**
  10852. * Default behaviour for cors in the application.
  10853. * It can be a string if the expected behavior is identical in the entire app.
  10854. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10855. */
  10856. Tools.CorsBehavior = "anonymous";
  10857. /**
  10858. * Gets or sets a global variable indicating if fallback texture must be used when a texture cannot be loaded
  10859. * @ignorenaming
  10860. */
  10861. Tools.UseFallbackTexture = true;
  10862. /**
  10863. * Use this object to register external classes like custom textures or material
  10864. * to allow the laoders to instantiate them
  10865. */
  10866. Tools.RegisteredExternalClasses = {};
  10867. /**
  10868. * Texture content used if a texture cannot loaded
  10869. * @ignorenaming
  10870. */
  10871. 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";
  10872. Tools._tmpFloatArray = new Float32Array(1);
  10873. /**
  10874. * Gets or sets a function used to pre-process url before using them to load assets
  10875. */
  10876. Tools.PreprocessUrl = function (url) {
  10877. return url;
  10878. };
  10879. // Logs
  10880. /**
  10881. * No log
  10882. */
  10883. Tools.NoneLogLevel = 0;
  10884. /**
  10885. * Only message logs
  10886. */
  10887. Tools.MessageLogLevel = 1;
  10888. /**
  10889. * Only warning logs
  10890. */
  10891. Tools.WarningLogLevel = 2;
  10892. /**
  10893. * Only error logs
  10894. */
  10895. Tools.ErrorLogLevel = 4;
  10896. /**
  10897. * All logs
  10898. */
  10899. Tools.AllLogLevel = 7;
  10900. Tools._LogCache = "";
  10901. /**
  10902. * Gets a value indicating the number of loading errors
  10903. * @ignorenaming
  10904. */
  10905. Tools.errorsCount = 0;
  10906. /**
  10907. * Log a message to the console
  10908. */
  10909. Tools.Log = Tools._LogEnabled;
  10910. /**
  10911. * Write a warning message to the console
  10912. */
  10913. Tools.Warn = Tools._WarnEnabled;
  10914. /**
  10915. * Write an error message to the console
  10916. */
  10917. Tools.Error = Tools._ErrorEnabled;
  10918. // Performances
  10919. /**
  10920. * No performance log
  10921. */
  10922. Tools.PerformanceNoneLogLevel = 0;
  10923. /**
  10924. * Use user marks to log performance
  10925. */
  10926. Tools.PerformanceUserMarkLogLevel = 1;
  10927. /**
  10928. * Log performance to the console
  10929. */
  10930. Tools.PerformanceConsoleLogLevel = 2;
  10931. /**
  10932. * Starts a performance counter
  10933. */
  10934. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10935. /**
  10936. * Ends a specific performance coutner
  10937. */
  10938. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10939. return Tools;
  10940. }());
  10941. BABYLON.Tools = Tools;
  10942. /**
  10943. * This class is used to track a performance counter which is number based.
  10944. * The user has access to many properties which give statistics of different nature.
  10945. *
  10946. * The implementer can track two kinds of Performance Counter: time and count.
  10947. * 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.
  10948. * 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.
  10949. */
  10950. var PerfCounter = /** @class */ (function () {
  10951. /**
  10952. * Creates a new counter
  10953. */
  10954. function PerfCounter() {
  10955. this._startMonitoringTime = 0;
  10956. this._min = 0;
  10957. this._max = 0;
  10958. this._average = 0;
  10959. this._lastSecAverage = 0;
  10960. this._current = 0;
  10961. this._totalValueCount = 0;
  10962. this._totalAccumulated = 0;
  10963. this._lastSecAccumulated = 0;
  10964. this._lastSecTime = 0;
  10965. this._lastSecValueCount = 0;
  10966. }
  10967. Object.defineProperty(PerfCounter.prototype, "min", {
  10968. /**
  10969. * Returns the smallest value ever
  10970. */
  10971. get: function () {
  10972. return this._min;
  10973. },
  10974. enumerable: true,
  10975. configurable: true
  10976. });
  10977. Object.defineProperty(PerfCounter.prototype, "max", {
  10978. /**
  10979. * Returns the biggest value ever
  10980. */
  10981. get: function () {
  10982. return this._max;
  10983. },
  10984. enumerable: true,
  10985. configurable: true
  10986. });
  10987. Object.defineProperty(PerfCounter.prototype, "average", {
  10988. /**
  10989. * Returns the average value since the performance counter is running
  10990. */
  10991. get: function () {
  10992. return this._average;
  10993. },
  10994. enumerable: true,
  10995. configurable: true
  10996. });
  10997. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10998. /**
  10999. * Returns the average value of the last second the counter was monitored
  11000. */
  11001. get: function () {
  11002. return this._lastSecAverage;
  11003. },
  11004. enumerable: true,
  11005. configurable: true
  11006. });
  11007. Object.defineProperty(PerfCounter.prototype, "current", {
  11008. /**
  11009. * Returns the current value
  11010. */
  11011. get: function () {
  11012. return this._current;
  11013. },
  11014. enumerable: true,
  11015. configurable: true
  11016. });
  11017. Object.defineProperty(PerfCounter.prototype, "total", {
  11018. /**
  11019. * Gets the accumulated total
  11020. */
  11021. get: function () {
  11022. return this._totalAccumulated;
  11023. },
  11024. enumerable: true,
  11025. configurable: true
  11026. });
  11027. Object.defineProperty(PerfCounter.prototype, "count", {
  11028. /**
  11029. * Gets the total value count
  11030. */
  11031. get: function () {
  11032. return this._totalValueCount;
  11033. },
  11034. enumerable: true,
  11035. configurable: true
  11036. });
  11037. /**
  11038. * Call this method to start monitoring a new frame.
  11039. * 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.
  11040. */
  11041. PerfCounter.prototype.fetchNewFrame = function () {
  11042. this._totalValueCount++;
  11043. this._current = 0;
  11044. this._lastSecValueCount++;
  11045. };
  11046. /**
  11047. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  11048. * @param newCount the count value to add to the monitored count
  11049. * @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.
  11050. */
  11051. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  11052. if (!PerfCounter.Enabled) {
  11053. return;
  11054. }
  11055. this._current += newCount;
  11056. if (fetchResult) {
  11057. this._fetchResult();
  11058. }
  11059. };
  11060. /**
  11061. * Start monitoring this performance counter
  11062. */
  11063. PerfCounter.prototype.beginMonitoring = function () {
  11064. if (!PerfCounter.Enabled) {
  11065. return;
  11066. }
  11067. this._startMonitoringTime = Tools.Now;
  11068. };
  11069. /**
  11070. * Compute the time lapsed since the previous beginMonitoring() call.
  11071. * @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
  11072. */
  11073. PerfCounter.prototype.endMonitoring = function (newFrame) {
  11074. if (newFrame === void 0) { newFrame = true; }
  11075. if (!PerfCounter.Enabled) {
  11076. return;
  11077. }
  11078. if (newFrame) {
  11079. this.fetchNewFrame();
  11080. }
  11081. var currentTime = Tools.Now;
  11082. this._current = currentTime - this._startMonitoringTime;
  11083. if (newFrame) {
  11084. this._fetchResult();
  11085. }
  11086. };
  11087. PerfCounter.prototype._fetchResult = function () {
  11088. this._totalAccumulated += this._current;
  11089. this._lastSecAccumulated += this._current;
  11090. // Min/Max update
  11091. this._min = Math.min(this._min, this._current);
  11092. this._max = Math.max(this._max, this._current);
  11093. this._average = this._totalAccumulated / this._totalValueCount;
  11094. // Reset last sec?
  11095. var now = Tools.Now;
  11096. if ((now - this._lastSecTime) > 1000) {
  11097. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  11098. this._lastSecTime = now;
  11099. this._lastSecAccumulated = 0;
  11100. this._lastSecValueCount = 0;
  11101. }
  11102. };
  11103. /**
  11104. * Gets or sets a global boolean to turn on and off all the counters
  11105. */
  11106. PerfCounter.Enabled = true;
  11107. return PerfCounter;
  11108. }());
  11109. BABYLON.PerfCounter = PerfCounter;
  11110. /**
  11111. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  11112. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  11113. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  11114. * @param name The name of the class, case should be preserved
  11115. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  11116. */
  11117. function className(name, module) {
  11118. return function (target) {
  11119. target["__bjsclassName__"] = name;
  11120. target["__bjsmoduleName__"] = (module != null) ? module : null;
  11121. };
  11122. }
  11123. BABYLON.className = className;
  11124. /**
  11125. * An implementation of a loop for asynchronous functions.
  11126. */
  11127. var AsyncLoop = /** @class */ (function () {
  11128. /**
  11129. * Constructor.
  11130. * @param iterations the number of iterations.
  11131. * @param func the function to run each iteration
  11132. * @param successCallback the callback that will be called upon succesful execution
  11133. * @param offset starting offset.
  11134. */
  11135. function AsyncLoop(
  11136. /**
  11137. * Defines the number of iterations for the loop
  11138. */
  11139. iterations, func, successCallback, offset) {
  11140. if (offset === void 0) { offset = 0; }
  11141. this.iterations = iterations;
  11142. this.index = offset - 1;
  11143. this._done = false;
  11144. this._fn = func;
  11145. this._successCallback = successCallback;
  11146. }
  11147. /**
  11148. * Execute the next iteration. Must be called after the last iteration was finished.
  11149. */
  11150. AsyncLoop.prototype.executeNext = function () {
  11151. if (!this._done) {
  11152. if (this.index + 1 < this.iterations) {
  11153. ++this.index;
  11154. this._fn(this);
  11155. }
  11156. else {
  11157. this.breakLoop();
  11158. }
  11159. }
  11160. };
  11161. /**
  11162. * Break the loop and run the success callback.
  11163. */
  11164. AsyncLoop.prototype.breakLoop = function () {
  11165. this._done = true;
  11166. this._successCallback();
  11167. };
  11168. /**
  11169. * Create and run an async loop.
  11170. * @param iterations the number of iterations.
  11171. * @param fn the function to run each iteration
  11172. * @param successCallback the callback that will be called upon succesful execution
  11173. * @param offset starting offset.
  11174. * @returns the created async loop object
  11175. */
  11176. AsyncLoop.Run = function (iterations, fn, successCallback, offset) {
  11177. if (offset === void 0) { offset = 0; }
  11178. var loop = new AsyncLoop(iterations, fn, successCallback, offset);
  11179. loop.executeNext();
  11180. return loop;
  11181. };
  11182. /**
  11183. * A for-loop that will run a given number of iterations synchronous and the rest async.
  11184. * @param iterations total number of iterations
  11185. * @param syncedIterations number of synchronous iterations in each async iteration.
  11186. * @param fn the function to call each iteration.
  11187. * @param callback a success call back that will be called when iterating stops.
  11188. * @param breakFunction a break condition (optional)
  11189. * @param timeout timeout settings for the setTimeout function. default - 0.
  11190. * @returns the created async loop object
  11191. */
  11192. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  11193. if (timeout === void 0) { timeout = 0; }
  11194. return AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  11195. if (breakFunction && breakFunction())
  11196. loop.breakLoop();
  11197. else {
  11198. setTimeout(function () {
  11199. for (var i = 0; i < syncedIterations; ++i) {
  11200. var iteration = (loop.index * syncedIterations) + i;
  11201. if (iteration >= iterations)
  11202. break;
  11203. fn(iteration);
  11204. if (breakFunction && breakFunction()) {
  11205. loop.breakLoop();
  11206. break;
  11207. }
  11208. }
  11209. loop.executeNext();
  11210. }, timeout);
  11211. }
  11212. }, callback);
  11213. };
  11214. return AsyncLoop;
  11215. }());
  11216. BABYLON.AsyncLoop = AsyncLoop;
  11217. })(BABYLON || (BABYLON = {}));
  11218. //# sourceMappingURL=babylon.tools.js.map
  11219. var BABYLON;
  11220. (function (BABYLON) {
  11221. var PromiseStates;
  11222. (function (PromiseStates) {
  11223. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  11224. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  11225. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  11226. })(PromiseStates || (PromiseStates = {}));
  11227. var FulFillmentAgregator = /** @class */ (function () {
  11228. function FulFillmentAgregator() {
  11229. this.count = 0;
  11230. this.target = 0;
  11231. this.results = [];
  11232. }
  11233. return FulFillmentAgregator;
  11234. }());
  11235. var InternalPromise = /** @class */ (function () {
  11236. function InternalPromise(resolver) {
  11237. var _this = this;
  11238. this._state = PromiseStates.Pending;
  11239. this._children = new Array();
  11240. this._rejectWasConsumed = false;
  11241. if (!resolver) {
  11242. return;
  11243. }
  11244. try {
  11245. resolver(function (value) {
  11246. _this._resolve(value);
  11247. }, function (reason) {
  11248. _this._reject(reason);
  11249. });
  11250. }
  11251. catch (e) {
  11252. this._reject(e);
  11253. }
  11254. }
  11255. Object.defineProperty(InternalPromise.prototype, "_result", {
  11256. get: function () {
  11257. return this._resultValue;
  11258. },
  11259. set: function (value) {
  11260. this._resultValue = value;
  11261. if (this._parent && this._parent._result === undefined) {
  11262. this._parent._result = value;
  11263. }
  11264. },
  11265. enumerable: true,
  11266. configurable: true
  11267. });
  11268. InternalPromise.prototype.catch = function (onRejected) {
  11269. return this.then(undefined, onRejected);
  11270. };
  11271. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  11272. var _this = this;
  11273. var newPromise = new InternalPromise();
  11274. newPromise._onFulfilled = onFulfilled;
  11275. newPromise._onRejected = onRejected;
  11276. // Composition
  11277. this._children.push(newPromise);
  11278. newPromise._parent = this;
  11279. if (this._state !== PromiseStates.Pending) {
  11280. BABYLON.Tools.SetImmediate(function () {
  11281. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  11282. var returnedValue = newPromise._resolve(_this._result);
  11283. if (returnedValue !== undefined && returnedValue !== null) {
  11284. if (returnedValue._state !== undefined) {
  11285. var returnedPromise = returnedValue;
  11286. newPromise._children.push(returnedPromise);
  11287. returnedPromise._parent = newPromise;
  11288. newPromise = returnedPromise;
  11289. }
  11290. else {
  11291. newPromise._result = returnedValue;
  11292. }
  11293. }
  11294. }
  11295. else {
  11296. newPromise._reject(_this._reason);
  11297. }
  11298. });
  11299. }
  11300. return newPromise;
  11301. };
  11302. InternalPromise.prototype._moveChildren = function (children) {
  11303. var _this = this;
  11304. var _a;
  11305. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  11306. this._children.forEach(function (child) {
  11307. child._parent = _this;
  11308. });
  11309. if (this._state === PromiseStates.Fulfilled) {
  11310. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  11311. var child = _b[_i];
  11312. child._resolve(this._result);
  11313. }
  11314. }
  11315. else if (this._state === PromiseStates.Rejected) {
  11316. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  11317. var child = _d[_c];
  11318. child._reject(this._reason);
  11319. }
  11320. }
  11321. };
  11322. InternalPromise.prototype._resolve = function (value) {
  11323. try {
  11324. this._state = PromiseStates.Fulfilled;
  11325. var returnedValue = null;
  11326. if (this._onFulfilled) {
  11327. returnedValue = this._onFulfilled(value);
  11328. }
  11329. if (returnedValue !== undefined && returnedValue !== null) {
  11330. if (returnedValue._state !== undefined) {
  11331. // Transmit children
  11332. var returnedPromise = returnedValue;
  11333. returnedPromise._parent = this;
  11334. returnedPromise._moveChildren(this._children);
  11335. value = returnedPromise._result;
  11336. }
  11337. else {
  11338. value = returnedValue;
  11339. }
  11340. }
  11341. this._result = value;
  11342. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11343. var child = _a[_i];
  11344. child._resolve(value);
  11345. }
  11346. this._children.length = 0;
  11347. delete this._onFulfilled;
  11348. delete this._onRejected;
  11349. }
  11350. catch (e) {
  11351. this._reject(e, true);
  11352. }
  11353. };
  11354. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  11355. if (onLocalThrow === void 0) { onLocalThrow = false; }
  11356. this._state = PromiseStates.Rejected;
  11357. this._reason = reason;
  11358. if (this._onRejected && !onLocalThrow) {
  11359. try {
  11360. this._onRejected(reason);
  11361. this._rejectWasConsumed = true;
  11362. }
  11363. catch (e) {
  11364. reason = e;
  11365. }
  11366. }
  11367. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  11368. var child = _a[_i];
  11369. if (this._rejectWasConsumed) {
  11370. child._resolve(null);
  11371. }
  11372. else {
  11373. child._reject(reason);
  11374. }
  11375. }
  11376. this._children.length = 0;
  11377. delete this._onFulfilled;
  11378. delete this._onRejected;
  11379. };
  11380. InternalPromise.resolve = function (value) {
  11381. var newPromise = new InternalPromise();
  11382. newPromise._resolve(value);
  11383. return newPromise;
  11384. };
  11385. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  11386. promise.then(function (value) {
  11387. agregator.results[index] = value;
  11388. agregator.count++;
  11389. if (agregator.count === agregator.target) {
  11390. agregator.rootPromise._resolve(agregator.results);
  11391. }
  11392. return null;
  11393. }, function (reason) {
  11394. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  11395. agregator.rootPromise._reject(reason);
  11396. }
  11397. });
  11398. };
  11399. InternalPromise.all = function (promises) {
  11400. var newPromise = new InternalPromise();
  11401. var agregator = new FulFillmentAgregator();
  11402. agregator.target = promises.length;
  11403. agregator.rootPromise = newPromise;
  11404. if (promises.length) {
  11405. for (var index = 0; index < promises.length; index++) {
  11406. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  11407. }
  11408. }
  11409. else {
  11410. newPromise._resolve([]);
  11411. }
  11412. return newPromise;
  11413. };
  11414. InternalPromise.race = function (promises) {
  11415. var newPromise = new InternalPromise();
  11416. if (promises.length) {
  11417. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  11418. var promise = promises_1[_i];
  11419. promise.then(function (value) {
  11420. if (newPromise) {
  11421. newPromise._resolve(value);
  11422. newPromise = null;
  11423. }
  11424. return null;
  11425. }, function (reason) {
  11426. if (newPromise) {
  11427. newPromise._reject(reason);
  11428. newPromise = null;
  11429. }
  11430. });
  11431. }
  11432. }
  11433. return newPromise;
  11434. };
  11435. return InternalPromise;
  11436. }());
  11437. /**
  11438. * Helper class that provides a small promise polyfill
  11439. */
  11440. var PromisePolyfill = /** @class */ (function () {
  11441. function PromisePolyfill() {
  11442. }
  11443. /**
  11444. * Static function used to check if the polyfill is required
  11445. * If this is the case then the function will inject the polyfill to window.Promise
  11446. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  11447. */
  11448. PromisePolyfill.Apply = function (force) {
  11449. if (force === void 0) { force = false; }
  11450. if (force || typeof Promise === 'undefined') {
  11451. var root = window;
  11452. root.Promise = InternalPromise;
  11453. }
  11454. };
  11455. return PromisePolyfill;
  11456. }());
  11457. BABYLON.PromisePolyfill = PromisePolyfill;
  11458. })(BABYLON || (BABYLON = {}));
  11459. //# sourceMappingURL=babylon.promise.js.map
  11460. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  11461. var BABYLON;
  11462. (function (BABYLON) {
  11463. /**
  11464. * Helper class to push actions to a pool of workers.
  11465. */
  11466. var WorkerPool = /** @class */ (function () {
  11467. /**
  11468. * Constructor
  11469. * @param workers Array of workers to use for actions
  11470. */
  11471. function WorkerPool(workers) {
  11472. this._pendingActions = new Array();
  11473. this._workerInfos = workers.map(function (worker) { return ({
  11474. worker: worker,
  11475. active: false
  11476. }); });
  11477. }
  11478. /**
  11479. * Terminates all workers and clears any pending actions.
  11480. */
  11481. WorkerPool.prototype.dispose = function () {
  11482. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11483. var workerInfo = _a[_i];
  11484. workerInfo.worker.terminate();
  11485. }
  11486. delete this._workerInfos;
  11487. delete this._pendingActions;
  11488. };
  11489. /**
  11490. * Pushes an action to the worker pool. If all the workers are active, the action will be
  11491. * pended until a worker has completed its action.
  11492. * @param action The action to perform. Call onComplete when the action is complete.
  11493. */
  11494. WorkerPool.prototype.push = function (action) {
  11495. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  11496. var workerInfo = _a[_i];
  11497. if (!workerInfo.active) {
  11498. this._execute(workerInfo, action);
  11499. return;
  11500. }
  11501. }
  11502. this._pendingActions.push(action);
  11503. };
  11504. WorkerPool.prototype._execute = function (workerInfo, action) {
  11505. var _this = this;
  11506. workerInfo.active = true;
  11507. action(workerInfo.worker, function () {
  11508. workerInfo.active = false;
  11509. var nextAction = _this._pendingActions.shift();
  11510. if (nextAction) {
  11511. _this._execute(workerInfo, nextAction);
  11512. }
  11513. });
  11514. };
  11515. return WorkerPool;
  11516. }());
  11517. BABYLON.WorkerPool = WorkerPool;
  11518. })(BABYLON || (BABYLON = {}));
  11519. //# sourceMappingURL=babylon.workerPool.js.map
  11520. var BABYLON;
  11521. (function (BABYLON) {
  11522. /**
  11523. * @hidden
  11524. **/
  11525. var _AlphaState = /** @class */ (function () {
  11526. /**
  11527. * Initializes the state.
  11528. */
  11529. function _AlphaState() {
  11530. this._isAlphaBlendDirty = false;
  11531. this._isBlendFunctionParametersDirty = false;
  11532. this._isBlendEquationParametersDirty = false;
  11533. this._isBlendConstantsDirty = false;
  11534. this._alphaBlend = false;
  11535. this._blendFunctionParameters = new Array(4);
  11536. this._blendEquationParameters = new Array(2);
  11537. this._blendConstants = new Array(4);
  11538. this.reset();
  11539. }
  11540. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  11541. get: function () {
  11542. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  11543. },
  11544. enumerable: true,
  11545. configurable: true
  11546. });
  11547. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  11548. get: function () {
  11549. return this._alphaBlend;
  11550. },
  11551. set: function (value) {
  11552. if (this._alphaBlend === value) {
  11553. return;
  11554. }
  11555. this._alphaBlend = value;
  11556. this._isAlphaBlendDirty = true;
  11557. },
  11558. enumerable: true,
  11559. configurable: true
  11560. });
  11561. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  11562. if (this._blendConstants[0] === r &&
  11563. this._blendConstants[1] === g &&
  11564. this._blendConstants[2] === b &&
  11565. this._blendConstants[3] === a) {
  11566. return;
  11567. }
  11568. this._blendConstants[0] = r;
  11569. this._blendConstants[1] = g;
  11570. this._blendConstants[2] = b;
  11571. this._blendConstants[3] = a;
  11572. this._isBlendConstantsDirty = true;
  11573. };
  11574. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  11575. if (this._blendFunctionParameters[0] === value0 &&
  11576. this._blendFunctionParameters[1] === value1 &&
  11577. this._blendFunctionParameters[2] === value2 &&
  11578. this._blendFunctionParameters[3] === value3) {
  11579. return;
  11580. }
  11581. this._blendFunctionParameters[0] = value0;
  11582. this._blendFunctionParameters[1] = value1;
  11583. this._blendFunctionParameters[2] = value2;
  11584. this._blendFunctionParameters[3] = value3;
  11585. this._isBlendFunctionParametersDirty = true;
  11586. };
  11587. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  11588. if (this._blendEquationParameters[0] === rgb &&
  11589. this._blendEquationParameters[1] === alpha) {
  11590. return;
  11591. }
  11592. this._blendEquationParameters[0] = rgb;
  11593. this._blendEquationParameters[1] = alpha;
  11594. this._isBlendEquationParametersDirty = true;
  11595. };
  11596. _AlphaState.prototype.reset = function () {
  11597. this._alphaBlend = false;
  11598. this._blendFunctionParameters[0] = null;
  11599. this._blendFunctionParameters[1] = null;
  11600. this._blendFunctionParameters[2] = null;
  11601. this._blendFunctionParameters[3] = null;
  11602. this._blendEquationParameters[0] = null;
  11603. this._blendEquationParameters[1] = null;
  11604. this._blendConstants[0] = null;
  11605. this._blendConstants[1] = null;
  11606. this._blendConstants[2] = null;
  11607. this._blendConstants[3] = null;
  11608. this._isAlphaBlendDirty = true;
  11609. this._isBlendFunctionParametersDirty = false;
  11610. this._isBlendEquationParametersDirty = false;
  11611. this._isBlendConstantsDirty = false;
  11612. };
  11613. _AlphaState.prototype.apply = function (gl) {
  11614. if (!this.isDirty) {
  11615. return;
  11616. }
  11617. // Alpha blend
  11618. if (this._isAlphaBlendDirty) {
  11619. if (this._alphaBlend) {
  11620. gl.enable(gl.BLEND);
  11621. }
  11622. else {
  11623. gl.disable(gl.BLEND);
  11624. }
  11625. this._isAlphaBlendDirty = false;
  11626. }
  11627. // Alpha function
  11628. if (this._isBlendFunctionParametersDirty) {
  11629. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  11630. this._isBlendFunctionParametersDirty = false;
  11631. }
  11632. // Alpha equation
  11633. if (this._isBlendEquationParametersDirty) {
  11634. gl.blendEquationSeparate(this._blendEquationParameters[0], this._blendEquationParameters[1]);
  11635. this._isBlendEquationParametersDirty = false;
  11636. }
  11637. // Constants
  11638. if (this._isBlendConstantsDirty) {
  11639. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  11640. this._isBlendConstantsDirty = false;
  11641. }
  11642. };
  11643. return _AlphaState;
  11644. }());
  11645. BABYLON._AlphaState = _AlphaState;
  11646. })(BABYLON || (BABYLON = {}));
  11647. //# sourceMappingURL=babylon.alphaCullingState.js.map
  11648. var BABYLON;
  11649. (function (BABYLON) {
  11650. /**
  11651. * @hidden
  11652. **/
  11653. var _DepthCullingState = /** @class */ (function () {
  11654. /**
  11655. * Initializes the state.
  11656. */
  11657. function _DepthCullingState() {
  11658. this._isDepthTestDirty = false;
  11659. this._isDepthMaskDirty = false;
  11660. this._isDepthFuncDirty = false;
  11661. this._isCullFaceDirty = false;
  11662. this._isCullDirty = false;
  11663. this._isZOffsetDirty = false;
  11664. this._isFrontFaceDirty = false;
  11665. this.reset();
  11666. }
  11667. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  11668. get: function () {
  11669. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  11670. },
  11671. enumerable: true,
  11672. configurable: true
  11673. });
  11674. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  11675. get: function () {
  11676. return this._zOffset;
  11677. },
  11678. set: function (value) {
  11679. if (this._zOffset === value) {
  11680. return;
  11681. }
  11682. this._zOffset = value;
  11683. this._isZOffsetDirty = true;
  11684. },
  11685. enumerable: true,
  11686. configurable: true
  11687. });
  11688. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  11689. get: function () {
  11690. return this._cullFace;
  11691. },
  11692. set: function (value) {
  11693. if (this._cullFace === value) {
  11694. return;
  11695. }
  11696. this._cullFace = value;
  11697. this._isCullFaceDirty = true;
  11698. },
  11699. enumerable: true,
  11700. configurable: true
  11701. });
  11702. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  11703. get: function () {
  11704. return this._cull;
  11705. },
  11706. set: function (value) {
  11707. if (this._cull === value) {
  11708. return;
  11709. }
  11710. this._cull = value;
  11711. this._isCullDirty = true;
  11712. },
  11713. enumerable: true,
  11714. configurable: true
  11715. });
  11716. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  11717. get: function () {
  11718. return this._depthFunc;
  11719. },
  11720. set: function (value) {
  11721. if (this._depthFunc === value) {
  11722. return;
  11723. }
  11724. this._depthFunc = value;
  11725. this._isDepthFuncDirty = true;
  11726. },
  11727. enumerable: true,
  11728. configurable: true
  11729. });
  11730. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  11731. get: function () {
  11732. return this._depthMask;
  11733. },
  11734. set: function (value) {
  11735. if (this._depthMask === value) {
  11736. return;
  11737. }
  11738. this._depthMask = value;
  11739. this._isDepthMaskDirty = true;
  11740. },
  11741. enumerable: true,
  11742. configurable: true
  11743. });
  11744. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  11745. get: function () {
  11746. return this._depthTest;
  11747. },
  11748. set: function (value) {
  11749. if (this._depthTest === value) {
  11750. return;
  11751. }
  11752. this._depthTest = value;
  11753. this._isDepthTestDirty = true;
  11754. },
  11755. enumerable: true,
  11756. configurable: true
  11757. });
  11758. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  11759. get: function () {
  11760. return this._frontFace;
  11761. },
  11762. set: function (value) {
  11763. if (this._frontFace === value) {
  11764. return;
  11765. }
  11766. this._frontFace = value;
  11767. this._isFrontFaceDirty = true;
  11768. },
  11769. enumerable: true,
  11770. configurable: true
  11771. });
  11772. _DepthCullingState.prototype.reset = function () {
  11773. this._depthMask = true;
  11774. this._depthTest = true;
  11775. this._depthFunc = null;
  11776. this._cullFace = null;
  11777. this._cull = null;
  11778. this._zOffset = 0;
  11779. this._frontFace = null;
  11780. this._isDepthTestDirty = true;
  11781. this._isDepthMaskDirty = true;
  11782. this._isDepthFuncDirty = false;
  11783. this._isCullFaceDirty = false;
  11784. this._isCullDirty = false;
  11785. this._isZOffsetDirty = false;
  11786. this._isFrontFaceDirty = false;
  11787. };
  11788. _DepthCullingState.prototype.apply = function (gl) {
  11789. if (!this.isDirty) {
  11790. return;
  11791. }
  11792. // Cull
  11793. if (this._isCullDirty) {
  11794. if (this.cull) {
  11795. gl.enable(gl.CULL_FACE);
  11796. }
  11797. else {
  11798. gl.disable(gl.CULL_FACE);
  11799. }
  11800. this._isCullDirty = false;
  11801. }
  11802. // Cull face
  11803. if (this._isCullFaceDirty) {
  11804. gl.cullFace(this.cullFace);
  11805. this._isCullFaceDirty = false;
  11806. }
  11807. // Depth mask
  11808. if (this._isDepthMaskDirty) {
  11809. gl.depthMask(this.depthMask);
  11810. this._isDepthMaskDirty = false;
  11811. }
  11812. // Depth test
  11813. if (this._isDepthTestDirty) {
  11814. if (this.depthTest) {
  11815. gl.enable(gl.DEPTH_TEST);
  11816. }
  11817. else {
  11818. gl.disable(gl.DEPTH_TEST);
  11819. }
  11820. this._isDepthTestDirty = false;
  11821. }
  11822. // Depth func
  11823. if (this._isDepthFuncDirty) {
  11824. gl.depthFunc(this.depthFunc);
  11825. this._isDepthFuncDirty = false;
  11826. }
  11827. // zOffset
  11828. if (this._isZOffsetDirty) {
  11829. if (this.zOffset) {
  11830. gl.enable(gl.POLYGON_OFFSET_FILL);
  11831. gl.polygonOffset(this.zOffset, 0);
  11832. }
  11833. else {
  11834. gl.disable(gl.POLYGON_OFFSET_FILL);
  11835. }
  11836. this._isZOffsetDirty = false;
  11837. }
  11838. // Front face
  11839. if (this._isFrontFaceDirty) {
  11840. gl.frontFace(this.frontFace);
  11841. this._isFrontFaceDirty = false;
  11842. }
  11843. };
  11844. return _DepthCullingState;
  11845. }());
  11846. BABYLON._DepthCullingState = _DepthCullingState;
  11847. })(BABYLON || (BABYLON = {}));
  11848. //# sourceMappingURL=babylon.depthCullingState.js.map
  11849. var BABYLON;
  11850. (function (BABYLON) {
  11851. /**
  11852. * @hidden
  11853. **/
  11854. var _StencilState = /** @class */ (function () {
  11855. function _StencilState() {
  11856. this._isStencilTestDirty = false;
  11857. this._isStencilMaskDirty = false;
  11858. this._isStencilFuncDirty = false;
  11859. this._isStencilOpDirty = false;
  11860. this.reset();
  11861. }
  11862. Object.defineProperty(_StencilState.prototype, "isDirty", {
  11863. get: function () {
  11864. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  11865. },
  11866. enumerable: true,
  11867. configurable: true
  11868. });
  11869. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  11870. get: function () {
  11871. return this._stencilFunc;
  11872. },
  11873. set: function (value) {
  11874. if (this._stencilFunc === value) {
  11875. return;
  11876. }
  11877. this._stencilFunc = value;
  11878. this._isStencilFuncDirty = true;
  11879. },
  11880. enumerable: true,
  11881. configurable: true
  11882. });
  11883. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11884. get: function () {
  11885. return this._stencilFuncRef;
  11886. },
  11887. set: function (value) {
  11888. if (this._stencilFuncRef === value) {
  11889. return;
  11890. }
  11891. this._stencilFuncRef = value;
  11892. this._isStencilFuncDirty = true;
  11893. },
  11894. enumerable: true,
  11895. configurable: true
  11896. });
  11897. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11898. get: function () {
  11899. return this._stencilFuncMask;
  11900. },
  11901. set: function (value) {
  11902. if (this._stencilFuncMask === value) {
  11903. return;
  11904. }
  11905. this._stencilFuncMask = value;
  11906. this._isStencilFuncDirty = true;
  11907. },
  11908. enumerable: true,
  11909. configurable: true
  11910. });
  11911. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11912. get: function () {
  11913. return this._stencilOpStencilFail;
  11914. },
  11915. set: function (value) {
  11916. if (this._stencilOpStencilFail === value) {
  11917. return;
  11918. }
  11919. this._stencilOpStencilFail = value;
  11920. this._isStencilOpDirty = true;
  11921. },
  11922. enumerable: true,
  11923. configurable: true
  11924. });
  11925. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11926. get: function () {
  11927. return this._stencilOpDepthFail;
  11928. },
  11929. set: function (value) {
  11930. if (this._stencilOpDepthFail === value) {
  11931. return;
  11932. }
  11933. this._stencilOpDepthFail = value;
  11934. this._isStencilOpDirty = true;
  11935. },
  11936. enumerable: true,
  11937. configurable: true
  11938. });
  11939. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11940. get: function () {
  11941. return this._stencilOpStencilDepthPass;
  11942. },
  11943. set: function (value) {
  11944. if (this._stencilOpStencilDepthPass === value) {
  11945. return;
  11946. }
  11947. this._stencilOpStencilDepthPass = value;
  11948. this._isStencilOpDirty = true;
  11949. },
  11950. enumerable: true,
  11951. configurable: true
  11952. });
  11953. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11954. get: function () {
  11955. return this._stencilMask;
  11956. },
  11957. set: function (value) {
  11958. if (this._stencilMask === value) {
  11959. return;
  11960. }
  11961. this._stencilMask = value;
  11962. this._isStencilMaskDirty = true;
  11963. },
  11964. enumerable: true,
  11965. configurable: true
  11966. });
  11967. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11968. get: function () {
  11969. return this._stencilTest;
  11970. },
  11971. set: function (value) {
  11972. if (this._stencilTest === value) {
  11973. return;
  11974. }
  11975. this._stencilTest = value;
  11976. this._isStencilTestDirty = true;
  11977. },
  11978. enumerable: true,
  11979. configurable: true
  11980. });
  11981. _StencilState.prototype.reset = function () {
  11982. this._stencilTest = false;
  11983. this._stencilMask = 0xFF;
  11984. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11985. this._stencilFuncRef = 1;
  11986. this._stencilFuncMask = 0xFF;
  11987. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11988. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11989. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11990. this._isStencilTestDirty = true;
  11991. this._isStencilMaskDirty = true;
  11992. this._isStencilFuncDirty = true;
  11993. this._isStencilOpDirty = true;
  11994. };
  11995. _StencilState.prototype.apply = function (gl) {
  11996. if (!this.isDirty) {
  11997. return;
  11998. }
  11999. // Stencil test
  12000. if (this._isStencilTestDirty) {
  12001. if (this.stencilTest) {
  12002. gl.enable(gl.STENCIL_TEST);
  12003. }
  12004. else {
  12005. gl.disable(gl.STENCIL_TEST);
  12006. }
  12007. this._isStencilTestDirty = false;
  12008. }
  12009. // Stencil mask
  12010. if (this._isStencilMaskDirty) {
  12011. gl.stencilMask(this.stencilMask);
  12012. this._isStencilMaskDirty = false;
  12013. }
  12014. // Stencil func
  12015. if (this._isStencilFuncDirty) {
  12016. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  12017. this._isStencilFuncDirty = false;
  12018. }
  12019. // Stencil op
  12020. if (this._isStencilOpDirty) {
  12021. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  12022. this._isStencilOpDirty = false;
  12023. }
  12024. };
  12025. return _StencilState;
  12026. }());
  12027. BABYLON._StencilState = _StencilState;
  12028. })(BABYLON || (BABYLON = {}));
  12029. //# sourceMappingURL=babylon.stencilState.js.map
  12030. var __assign = (this && this.__assign) || function () {
  12031. __assign = Object.assign || function(t) {
  12032. for (var s, i = 1, n = arguments.length; i < n; i++) {
  12033. s = arguments[i];
  12034. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  12035. t[p] = s[p];
  12036. }
  12037. return t;
  12038. };
  12039. return __assign.apply(this, arguments);
  12040. };
  12041. var BABYLON;
  12042. (function (BABYLON) {
  12043. /**
  12044. * Keeps track of all the buffer info used in engine.
  12045. */
  12046. var BufferPointer = /** @class */ (function () {
  12047. function BufferPointer() {
  12048. }
  12049. return BufferPointer;
  12050. }());
  12051. /**
  12052. * Interface for attribute information associated with buffer instanciation
  12053. */
  12054. var InstancingAttributeInfo = /** @class */ (function () {
  12055. function InstancingAttributeInfo() {
  12056. }
  12057. return InstancingAttributeInfo;
  12058. }());
  12059. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  12060. /**
  12061. * Define options used to create a render target texture
  12062. */
  12063. var RenderTargetCreationOptions = /** @class */ (function () {
  12064. function RenderTargetCreationOptions() {
  12065. }
  12066. return RenderTargetCreationOptions;
  12067. }());
  12068. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  12069. /**
  12070. * Define options used to create a depth texture
  12071. */
  12072. var DepthTextureCreationOptions = /** @class */ (function () {
  12073. function DepthTextureCreationOptions() {
  12074. }
  12075. return DepthTextureCreationOptions;
  12076. }());
  12077. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  12078. /**
  12079. * Class used to describe the capabilities of the engine relatively to the current browser
  12080. */
  12081. var EngineCapabilities = /** @class */ (function () {
  12082. function EngineCapabilities() {
  12083. }
  12084. return EngineCapabilities;
  12085. }());
  12086. BABYLON.EngineCapabilities = EngineCapabilities;
  12087. /**
  12088. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  12089. */
  12090. var Engine = /** @class */ (function () {
  12091. /**
  12092. * Creates a new engine
  12093. * @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
  12094. * @param antialias defines enable antialiasing (default: false)
  12095. * @param options defines further options to be sent to the getContext() function
  12096. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  12097. */
  12098. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  12099. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  12100. var _this = this;
  12101. // Public members
  12102. /**
  12103. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  12104. */
  12105. this.forcePOTTextures = false;
  12106. /**
  12107. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  12108. */
  12109. this.isFullscreen = false;
  12110. /**
  12111. * Gets a boolean indicating if the pointer is currently locked
  12112. */
  12113. this.isPointerLock = false;
  12114. /**
  12115. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  12116. */
  12117. this.cullBackFaces = true;
  12118. /**
  12119. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  12120. */
  12121. this.renderEvenInBackground = true;
  12122. /**
  12123. * Gets or sets a boolean indicating that cache can be kept between frames
  12124. */
  12125. this.preventCacheWipeBetweenFrames = false;
  12126. /**
  12127. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  12128. **/
  12129. this.enableOfflineSupport = false;
  12130. /**
  12131. * 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)
  12132. **/
  12133. this.disableManifestCheck = false;
  12134. /**
  12135. * Gets the list of created scenes
  12136. */
  12137. this.scenes = new Array();
  12138. /**
  12139. * Gets the list of created postprocesses
  12140. */
  12141. this.postProcesses = new Array();
  12142. /** Gets or sets a boolean indicating if the engine should validate programs after compilation */
  12143. this.validateShaderPrograms = false;
  12144. // Observables
  12145. /**
  12146. * Observable event triggered each time the rendering canvas is resized
  12147. */
  12148. this.onResizeObservable = new BABYLON.Observable();
  12149. /**
  12150. * Observable event triggered each time the canvas loses focus
  12151. */
  12152. this.onCanvasBlurObservable = new BABYLON.Observable();
  12153. /**
  12154. * Observable event triggered each time the canvas gains focus
  12155. */
  12156. this.onCanvasFocusObservable = new BABYLON.Observable();
  12157. /**
  12158. * Observable event triggered each time the canvas receives pointerout event
  12159. */
  12160. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  12161. /**
  12162. * Observable event triggered before each texture is initialized
  12163. */
  12164. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  12165. //WebVR
  12166. this._vrDisplay = undefined;
  12167. this._vrSupported = false;
  12168. this._vrExclusivePointerMode = false;
  12169. // Uniform buffers list
  12170. /**
  12171. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  12172. */
  12173. this.disableUniformBuffers = false;
  12174. /** @hidden */
  12175. this._uniformBuffers = new Array();
  12176. // Observables
  12177. /**
  12178. * Observable raised when the engine begins a new frame
  12179. */
  12180. this.onBeginFrameObservable = new BABYLON.Observable();
  12181. /**
  12182. * Observable raised when the engine ends the current frame
  12183. */
  12184. this.onEndFrameObservable = new BABYLON.Observable();
  12185. /**
  12186. * Observable raised when the engine is about to compile a shader
  12187. */
  12188. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  12189. /**
  12190. * Observable raised when the engine has jsut compiled a shader
  12191. */
  12192. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  12193. this._windowIsBackground = false;
  12194. this._webGLVersion = 1.0;
  12195. /** @hidden */
  12196. this._badOS = false;
  12197. /** @hidden */
  12198. this._badDesktopOS = false;
  12199. /**
  12200. * Gets or sets a value indicating if we want to disable texture binding optmization.
  12201. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  12202. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  12203. */
  12204. this.disableTextureBindingOptimization = false;
  12205. /**
  12206. * Observable signaled when VR display mode changes
  12207. */
  12208. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  12209. /**
  12210. * Observable signaled when VR request present is complete
  12211. */
  12212. this.onVRRequestPresentComplete = new BABYLON.Observable();
  12213. /**
  12214. * Observable signaled when VR request present starts
  12215. */
  12216. this.onVRRequestPresentStart = new BABYLON.Observable();
  12217. this._colorWrite = true;
  12218. /** @hidden */
  12219. this._drawCalls = new BABYLON.PerfCounter();
  12220. /** @hidden */
  12221. this._textureCollisions = new BABYLON.PerfCounter();
  12222. this._renderingQueueLaunched = false;
  12223. this._activeRenderLoops = new Array();
  12224. // Deterministic lockstepMaxSteps
  12225. this._deterministicLockstep = false;
  12226. this._lockstepMaxSteps = 4;
  12227. // Lost context
  12228. /**
  12229. * Observable signaled when a context lost event is raised
  12230. */
  12231. this.onContextLostObservable = new BABYLON.Observable();
  12232. /**
  12233. * Observable signaled when a context restored event is raised
  12234. */
  12235. this.onContextRestoredObservable = new BABYLON.Observable();
  12236. this._contextWasLost = false;
  12237. this._doNotHandleContextLost = false;
  12238. // FPS
  12239. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  12240. this._fps = 60;
  12241. this._deltaTime = 0;
  12242. /**
  12243. * Turn this value on if you want to pause FPS computation when in background
  12244. */
  12245. this.disablePerformanceMonitorInBackground = false;
  12246. // States
  12247. /** @hidden */
  12248. this._depthCullingState = new BABYLON._DepthCullingState();
  12249. /** @hidden */
  12250. this._stencilState = new BABYLON._StencilState();
  12251. /** @hidden */
  12252. this._alphaState = new BABYLON._AlphaState();
  12253. /** @hidden */
  12254. this._alphaMode = Engine.ALPHA_DISABLE;
  12255. // Cache
  12256. this._internalTexturesCache = new Array();
  12257. /** @hidden */
  12258. this._activeChannel = 0;
  12259. this._currentTextureChannel = -1;
  12260. /** @hidden */
  12261. this._boundTexturesCache = {};
  12262. this._compiledEffects = {};
  12263. this._vertexAttribArraysEnabled = [];
  12264. this._uintIndicesCurrentlySet = false;
  12265. this._currentBoundBuffer = new Array();
  12266. /** @hidden */
  12267. this._currentFramebuffer = null;
  12268. this._currentBufferPointers = new Array();
  12269. this._currentInstanceLocations = new Array();
  12270. this._currentInstanceBuffers = new Array();
  12271. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12272. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  12273. this._vaoRecordInProgress = false;
  12274. this._mustWipeVertexAttributes = false;
  12275. this._nextFreeTextureSlots = new Array();
  12276. this._maxSimultaneousTextures = 0;
  12277. this._activeRequests = new Array();
  12278. // Hardware supported Compressed Textures
  12279. this._texturesSupported = new Array();
  12280. /**
  12281. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  12282. */
  12283. this.premultipliedAlpha = true;
  12284. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  12285. this._onVRFullScreenTriggered = function () {
  12286. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  12287. //get the old size before we change
  12288. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  12289. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  12290. //get the width and height, change the render size
  12291. var leftEye = _this._vrDisplay.getEyeParameters('left');
  12292. _this.setHardwareScalingLevel(1);
  12293. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  12294. }
  12295. else {
  12296. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  12297. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  12298. }
  12299. };
  12300. this._unpackFlipYCached = null;
  12301. /**
  12302. * In case you are sharing the context with other applications, it might
  12303. * be interested to not cache the unpack flip y state to ensure a consistent
  12304. * value would be set.
  12305. */
  12306. this.enableUnpackFlipYCached = true;
  12307. this._boundUniforms = {};
  12308. // Register promises
  12309. BABYLON.PromisePolyfill.Apply();
  12310. var canvas = null;
  12311. Engine.Instances.push(this);
  12312. if (!canvasOrContext) {
  12313. return;
  12314. }
  12315. options = options || {};
  12316. if (canvasOrContext.getContext) {
  12317. canvas = canvasOrContext;
  12318. this._renderingCanvas = canvas;
  12319. if (antialias != null) {
  12320. options.antialias = antialias;
  12321. }
  12322. if (options.deterministicLockstep === undefined) {
  12323. options.deterministicLockstep = false;
  12324. }
  12325. if (options.lockstepMaxSteps === undefined) {
  12326. options.lockstepMaxSteps = 4;
  12327. }
  12328. if (options.preserveDrawingBuffer === undefined) {
  12329. options.preserveDrawingBuffer = false;
  12330. }
  12331. if (options.audioEngine === undefined) {
  12332. options.audioEngine = true;
  12333. }
  12334. if (options.stencil === undefined) {
  12335. options.stencil = true;
  12336. }
  12337. if (options.premultipliedAlpha === false) {
  12338. this.premultipliedAlpha = false;
  12339. }
  12340. this._deterministicLockstep = options.deterministicLockstep;
  12341. this._lockstepMaxSteps = options.lockstepMaxSteps;
  12342. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  12343. // Exceptions
  12344. if (navigator && navigator.userAgent) {
  12345. var ua = navigator.userAgent;
  12346. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  12347. var exception = _a[_i];
  12348. var key = exception.key;
  12349. var targets = exception.targets;
  12350. if (ua.indexOf(key) > -1) {
  12351. if (exception.capture && exception.captureConstraint) {
  12352. var capture = exception.capture;
  12353. var constraint = exception.captureConstraint;
  12354. var regex = new RegExp(capture);
  12355. var matches = regex.exec(ua);
  12356. if (matches && matches.length > 0) {
  12357. var capturedValue = parseInt(matches[matches.length - 1]);
  12358. if (capturedValue >= constraint) {
  12359. continue;
  12360. }
  12361. }
  12362. }
  12363. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  12364. var target = targets_1[_b];
  12365. switch (target) {
  12366. case "uniformBuffer":
  12367. this.disableUniformBuffers = true;
  12368. break;
  12369. case "textureBindingOptimization":
  12370. this.disableTextureBindingOptimization = true;
  12371. break;
  12372. }
  12373. }
  12374. }
  12375. }
  12376. }
  12377. // GL
  12378. if (!options.disableWebGL2Support) {
  12379. try {
  12380. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  12381. if (this._gl) {
  12382. this._webGLVersion = 2.0;
  12383. // Prevent weird browsers to lie :-)
  12384. if (!this._gl.deleteQuery) {
  12385. this._webGLVersion = 1.0;
  12386. }
  12387. }
  12388. }
  12389. catch (e) {
  12390. // Do nothing
  12391. }
  12392. }
  12393. if (!this._gl) {
  12394. if (!canvas) {
  12395. throw new Error("The provided canvas is null or undefined.");
  12396. }
  12397. try {
  12398. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  12399. }
  12400. catch (e) {
  12401. throw new Error("WebGL not supported");
  12402. }
  12403. }
  12404. if (!this._gl) {
  12405. throw new Error("WebGL not supported");
  12406. }
  12407. this._onCanvasFocus = function () {
  12408. _this.onCanvasFocusObservable.notifyObservers(_this);
  12409. };
  12410. this._onCanvasBlur = function () {
  12411. _this.onCanvasBlurObservable.notifyObservers(_this);
  12412. };
  12413. canvas.addEventListener("focus", this._onCanvasFocus);
  12414. canvas.addEventListener("blur", this._onCanvasBlur);
  12415. this._onBlur = function () {
  12416. if (_this.disablePerformanceMonitorInBackground) {
  12417. _this._performanceMonitor.disable();
  12418. }
  12419. _this._windowIsBackground = true;
  12420. };
  12421. this._onFocus = function () {
  12422. if (_this.disablePerformanceMonitorInBackground) {
  12423. _this._performanceMonitor.enable();
  12424. }
  12425. _this._windowIsBackground = false;
  12426. };
  12427. this._onCanvasPointerOut = function (ev) {
  12428. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  12429. };
  12430. window.addEventListener("blur", this._onBlur);
  12431. window.addEventListener("focus", this._onFocus);
  12432. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  12433. // Context lost
  12434. if (!this._doNotHandleContextLost) {
  12435. this._onContextLost = function (evt) {
  12436. evt.preventDefault();
  12437. _this._contextWasLost = true;
  12438. BABYLON.Tools.Warn("WebGL context lost.");
  12439. _this.onContextLostObservable.notifyObservers(_this);
  12440. };
  12441. this._onContextRestored = function (evt) {
  12442. // Adding a timeout to avoid race condition at browser level
  12443. setTimeout(function () {
  12444. // Rebuild gl context
  12445. _this._initGLContext();
  12446. // Rebuild effects
  12447. _this._rebuildEffects();
  12448. // Rebuild textures
  12449. _this._rebuildInternalTextures();
  12450. // Rebuild buffers
  12451. _this._rebuildBuffers();
  12452. // Cache
  12453. _this.wipeCaches(true);
  12454. BABYLON.Tools.Warn("WebGL context successfully restored.");
  12455. _this.onContextRestoredObservable.notifyObservers(_this);
  12456. _this._contextWasLost = false;
  12457. }, 0);
  12458. };
  12459. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  12460. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  12461. }
  12462. }
  12463. else {
  12464. this._gl = canvasOrContext;
  12465. this._renderingCanvas = this._gl.canvas;
  12466. if (this._gl.renderbufferStorageMultisample) {
  12467. this._webGLVersion = 2.0;
  12468. }
  12469. options.stencil = this._gl.getContextAttributes().stencil;
  12470. }
  12471. // Viewport
  12472. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  12473. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  12474. this.resize();
  12475. this._isStencilEnable = options.stencil ? true : false;
  12476. this._initGLContext();
  12477. if (canvas) {
  12478. // Fullscreen
  12479. this._onFullscreenChange = function () {
  12480. if (document.fullscreen !== undefined) {
  12481. _this.isFullscreen = document.fullscreen;
  12482. }
  12483. else if (document.mozFullScreen !== undefined) {
  12484. _this.isFullscreen = document.mozFullScreen;
  12485. }
  12486. else if (document.webkitIsFullScreen !== undefined) {
  12487. _this.isFullscreen = document.webkitIsFullScreen;
  12488. }
  12489. else if (document.msIsFullScreen !== undefined) {
  12490. _this.isFullscreen = document.msIsFullScreen;
  12491. }
  12492. // Pointer lock
  12493. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  12494. canvas.requestPointerLock = canvas.requestPointerLock ||
  12495. canvas.msRequestPointerLock ||
  12496. canvas.mozRequestPointerLock ||
  12497. canvas.webkitRequestPointerLock;
  12498. if (canvas.requestPointerLock) {
  12499. canvas.requestPointerLock();
  12500. }
  12501. }
  12502. };
  12503. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  12504. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  12505. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  12506. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  12507. // Pointer lock
  12508. this._onPointerLockChange = function () {
  12509. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  12510. document.webkitPointerLockElement === canvas ||
  12511. document.msPointerLockElement === canvas ||
  12512. document.pointerLockElement === canvas);
  12513. };
  12514. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  12515. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  12516. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  12517. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  12518. this._onVRDisplayPointerRestricted = function () {
  12519. if (canvas) {
  12520. canvas.requestPointerLock();
  12521. }
  12522. };
  12523. this._onVRDisplayPointerUnrestricted = function () {
  12524. document.exitPointerLock();
  12525. };
  12526. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  12527. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  12528. }
  12529. // Create Audio Engine if needed.
  12530. if (!Engine.audioEngine && options.audioEngine && Engine.AudioEngineFactory) {
  12531. Engine.audioEngine = Engine.AudioEngineFactory(this.getRenderingCanvas());
  12532. }
  12533. // Prepare buffer pointers
  12534. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  12535. this._currentBufferPointers[i] = new BufferPointer();
  12536. }
  12537. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  12538. // Load WebVR Devices
  12539. if (options.autoEnableWebVR) {
  12540. this.initWebVR();
  12541. }
  12542. // Detect if we are running on a faulty buggy OS.
  12543. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  12544. // Detect if we are running on a faulty buggy desktop OS.
  12545. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  12546. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  12547. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  12548. }
  12549. Object.defineProperty(Engine, "LastCreatedEngine", {
  12550. /**
  12551. * Gets the latest created engine
  12552. */
  12553. get: function () {
  12554. if (Engine.Instances.length === 0) {
  12555. return null;
  12556. }
  12557. return Engine.Instances[Engine.Instances.length - 1];
  12558. },
  12559. enumerable: true,
  12560. configurable: true
  12561. });
  12562. Object.defineProperty(Engine, "LastCreatedScene", {
  12563. /**
  12564. * Gets the latest created scene
  12565. */
  12566. get: function () {
  12567. var lastCreatedEngine = Engine.LastCreatedEngine;
  12568. if (!lastCreatedEngine) {
  12569. return null;
  12570. }
  12571. if (lastCreatedEngine.scenes.length === 0) {
  12572. return null;
  12573. }
  12574. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  12575. },
  12576. enumerable: true,
  12577. configurable: true
  12578. });
  12579. /**
  12580. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  12581. * @param flag defines which part of the materials must be marked as dirty
  12582. * @param predicate defines a predicate used to filter which materials should be affected
  12583. */
  12584. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  12585. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  12586. var engine = Engine.Instances[engineIndex];
  12587. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  12588. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  12589. }
  12590. }
  12591. };
  12592. Object.defineProperty(Engine, "Version", {
  12593. /**
  12594. * Returns the current version of the framework
  12595. */
  12596. get: function () {
  12597. return "3.3.0-rc.4";
  12598. },
  12599. enumerable: true,
  12600. configurable: true
  12601. });
  12602. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12603. /**
  12604. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12605. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12606. */
  12607. get: function () {
  12608. return this._vrExclusivePointerMode;
  12609. },
  12610. enumerable: true,
  12611. configurable: true
  12612. });
  12613. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12614. /**
  12615. * Gets a boolean indicating that the engine supports uniform buffers
  12616. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12617. */
  12618. get: function () {
  12619. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12620. },
  12621. enumerable: true,
  12622. configurable: true
  12623. });
  12624. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12625. /**
  12626. * Gets a boolean indicating that only power of 2 textures are supported
  12627. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12628. */
  12629. get: function () {
  12630. return this._webGLVersion < 2 || this.forcePOTTextures;
  12631. },
  12632. enumerable: true,
  12633. configurable: true
  12634. });
  12635. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12636. /**
  12637. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12638. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12639. */
  12640. get: function () {
  12641. return this._doNotHandleContextLost;
  12642. },
  12643. set: function (value) {
  12644. this._doNotHandleContextLost = value;
  12645. },
  12646. enumerable: true,
  12647. configurable: true
  12648. });
  12649. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12650. /**
  12651. * Gets the performance monitor attached to this engine
  12652. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12653. */
  12654. get: function () {
  12655. return this._performanceMonitor;
  12656. },
  12657. enumerable: true,
  12658. configurable: true
  12659. });
  12660. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12661. /**
  12662. * Gets the list of texture formats supported
  12663. */
  12664. get: function () {
  12665. return this._texturesSupported;
  12666. },
  12667. enumerable: true,
  12668. configurable: true
  12669. });
  12670. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12671. /**
  12672. * Gets the list of texture formats in use
  12673. */
  12674. get: function () {
  12675. return this._textureFormatInUse;
  12676. },
  12677. enumerable: true,
  12678. configurable: true
  12679. });
  12680. Object.defineProperty(Engine.prototype, "currentViewport", {
  12681. /**
  12682. * Gets the current viewport
  12683. */
  12684. get: function () {
  12685. return this._cachedViewport;
  12686. },
  12687. enumerable: true,
  12688. configurable: true
  12689. });
  12690. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12691. /**
  12692. * Gets the default empty texture
  12693. */
  12694. get: function () {
  12695. if (!this._emptyTexture) {
  12696. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12697. }
  12698. return this._emptyTexture;
  12699. },
  12700. enumerable: true,
  12701. configurable: true
  12702. });
  12703. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12704. /**
  12705. * Gets the default empty 3D texture
  12706. */
  12707. get: function () {
  12708. if (!this._emptyTexture3D) {
  12709. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12710. }
  12711. return this._emptyTexture3D;
  12712. },
  12713. enumerable: true,
  12714. configurable: true
  12715. });
  12716. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12717. /**
  12718. * Gets the default empty cube texture
  12719. */
  12720. get: function () {
  12721. if (!this._emptyCubeTexture) {
  12722. var faceData = new Uint8Array(4);
  12723. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12724. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, Engine.TEXTURE_NEAREST_SAMPLINGMODE);
  12725. }
  12726. return this._emptyCubeTexture;
  12727. },
  12728. enumerable: true,
  12729. configurable: true
  12730. });
  12731. Engine.prototype._rebuildInternalTextures = function () {
  12732. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12733. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12734. var internalTexture = currentState_1[_i];
  12735. internalTexture._rebuild();
  12736. }
  12737. };
  12738. Engine.prototype._rebuildEffects = function () {
  12739. for (var key in this._compiledEffects) {
  12740. var effect = this._compiledEffects[key];
  12741. effect._prepareEffect();
  12742. }
  12743. BABYLON.Effect.ResetCache();
  12744. };
  12745. Engine.prototype._rebuildBuffers = function () {
  12746. // Index / Vertex
  12747. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12748. var scene = _a[_i];
  12749. scene.resetCachedMaterial();
  12750. scene._rebuildGeometries();
  12751. scene._rebuildTextures();
  12752. }
  12753. // Uniforms
  12754. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12755. var uniformBuffer = _c[_b];
  12756. uniformBuffer._rebuild();
  12757. }
  12758. };
  12759. Engine.prototype._initGLContext = function () {
  12760. // Caps
  12761. this._caps = new EngineCapabilities();
  12762. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12763. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12764. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12765. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12766. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12767. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12768. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12769. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12770. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12771. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12772. // Infos
  12773. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12774. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12775. if (rendererInfo != null) {
  12776. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12777. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12778. }
  12779. if (!this._glVendor) {
  12780. this._glVendor = "Unknown vendor";
  12781. }
  12782. if (!this._glRenderer) {
  12783. this._glRenderer = "Unknown renderer";
  12784. }
  12785. // Constants
  12786. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12787. if (this._gl.RGBA16F !== 0x881A) {
  12788. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12789. }
  12790. if (this._gl.RGBA32F !== 0x8814) {
  12791. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12792. }
  12793. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12794. this._gl.DEPTH24_STENCIL8 = 35056;
  12795. }
  12796. // Extensions
  12797. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12798. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12799. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12800. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12801. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12802. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12803. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12804. 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');
  12805. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12806. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12807. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12808. this._caps.highPrecisionShaderSupported = true;
  12809. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12810. if (this._caps.timerQuery) {
  12811. if (this._webGLVersion === 1) {
  12812. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12813. }
  12814. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12815. }
  12816. // Checks if some of the format renders first to allow the use of webgl inspector.
  12817. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12818. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12819. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12820. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12821. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12822. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12823. if (this._webGLVersion > 1) {
  12824. this._gl.HALF_FLOAT_OES = 0x140B;
  12825. }
  12826. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12827. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12828. // Draw buffers
  12829. if (this._webGLVersion > 1) {
  12830. this._caps.drawBuffersExtension = true;
  12831. }
  12832. else {
  12833. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12834. if (drawBuffersExtension !== null) {
  12835. this._caps.drawBuffersExtension = true;
  12836. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12837. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12838. for (var i = 0; i < 16; i++) {
  12839. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12840. }
  12841. }
  12842. else {
  12843. this._caps.drawBuffersExtension = false;
  12844. }
  12845. }
  12846. // Depth Texture
  12847. if (this._webGLVersion > 1) {
  12848. this._caps.depthTextureExtension = true;
  12849. }
  12850. else {
  12851. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12852. if (depthTextureExtension != null) {
  12853. this._caps.depthTextureExtension = true;
  12854. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12855. }
  12856. }
  12857. // Vertex array object
  12858. if (this._webGLVersion > 1) {
  12859. this._caps.vertexArrayObject = true;
  12860. }
  12861. else {
  12862. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12863. if (vertexArrayObjectExtension != null) {
  12864. this._caps.vertexArrayObject = true;
  12865. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12866. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12867. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12868. }
  12869. else {
  12870. this._caps.vertexArrayObject = false;
  12871. }
  12872. }
  12873. // Instances count
  12874. if (this._webGLVersion > 1) {
  12875. this._caps.instancedArrays = true;
  12876. }
  12877. else {
  12878. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12879. if (instanceExtension != null) {
  12880. this._caps.instancedArrays = true;
  12881. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12882. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12883. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12884. }
  12885. else {
  12886. this._caps.instancedArrays = false;
  12887. }
  12888. }
  12889. // Intelligently add supported compressed formats in order to check for.
  12890. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12891. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12892. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12893. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12894. if (this._caps.astc)
  12895. this.texturesSupported.push('-astc.ktx');
  12896. if (this._caps.s3tc)
  12897. this.texturesSupported.push('-dxt.ktx');
  12898. if (this._caps.pvrtc)
  12899. this.texturesSupported.push('-pvrtc.ktx');
  12900. if (this._caps.etc2)
  12901. this.texturesSupported.push('-etc2.ktx');
  12902. if (this._caps.etc1)
  12903. this.texturesSupported.push('-etc1.ktx');
  12904. if (this._gl.getShaderPrecisionFormat) {
  12905. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12906. if (highp) {
  12907. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12908. }
  12909. }
  12910. // Depth buffer
  12911. this.setDepthBuffer(true);
  12912. this.setDepthFunctionToLessOrEqual();
  12913. this.setDepthWrite(true);
  12914. // Texture maps
  12915. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12916. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12917. this._nextFreeTextureSlots.push(slot);
  12918. }
  12919. };
  12920. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12921. /**
  12922. * Gets version of the current webGL context
  12923. */
  12924. get: function () {
  12925. return this._webGLVersion;
  12926. },
  12927. enumerable: true,
  12928. configurable: true
  12929. });
  12930. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12931. /**
  12932. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12933. */
  12934. get: function () {
  12935. return this._isStencilEnable;
  12936. },
  12937. enumerable: true,
  12938. configurable: true
  12939. });
  12940. Engine.prototype._prepareWorkingCanvas = function () {
  12941. if (this._workingCanvas) {
  12942. return;
  12943. }
  12944. this._workingCanvas = document.createElement("canvas");
  12945. var context = this._workingCanvas.getContext("2d");
  12946. if (context) {
  12947. this._workingContext = context;
  12948. }
  12949. };
  12950. /**
  12951. * Reset the texture cache to empty state
  12952. */
  12953. Engine.prototype.resetTextureCache = function () {
  12954. for (var key in this._boundTexturesCache) {
  12955. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12956. continue;
  12957. }
  12958. var boundTexture = this._boundTexturesCache[key];
  12959. if (boundTexture) {
  12960. this._removeDesignatedSlot(boundTexture);
  12961. }
  12962. this._boundTexturesCache[key] = null;
  12963. }
  12964. if (!this.disableTextureBindingOptimization) {
  12965. this._nextFreeTextureSlots = [];
  12966. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12967. this._nextFreeTextureSlots.push(slot);
  12968. }
  12969. }
  12970. this._currentTextureChannel = -1;
  12971. };
  12972. /**
  12973. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12974. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12975. * @returns true if engine is in deterministic lock step mode
  12976. */
  12977. Engine.prototype.isDeterministicLockStep = function () {
  12978. return this._deterministicLockstep;
  12979. };
  12980. /**
  12981. * Gets the max steps when engine is running in deterministic lock step
  12982. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12983. * @returns the max steps
  12984. */
  12985. Engine.prototype.getLockstepMaxSteps = function () {
  12986. return this._lockstepMaxSteps;
  12987. };
  12988. /**
  12989. * Gets an object containing information about the current webGL context
  12990. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12991. */
  12992. Engine.prototype.getGlInfo = function () {
  12993. return {
  12994. vendor: this._glVendor,
  12995. renderer: this._glRenderer,
  12996. version: this._glVersion
  12997. };
  12998. };
  12999. /**
  13000. * Gets current aspect ratio
  13001. * @param camera defines the camera to use to get the aspect ratio
  13002. * @param useScreen defines if screen size must be used (or the current render target if any)
  13003. * @returns a number defining the aspect ratio
  13004. */
  13005. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  13006. if (useScreen === void 0) { useScreen = false; }
  13007. var viewport = camera.viewport;
  13008. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  13009. };
  13010. /**
  13011. * Gets current screen aspect ratio
  13012. * @returns a number defining the aspect ratio
  13013. */
  13014. Engine.prototype.getScreenAspectRatio = function () {
  13015. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  13016. };
  13017. /**
  13018. * Gets the current render width
  13019. * @param useScreen defines if screen size must be used (or the current render target if any)
  13020. * @returns a number defining the current render width
  13021. */
  13022. Engine.prototype.getRenderWidth = function (useScreen) {
  13023. if (useScreen === void 0) { useScreen = false; }
  13024. if (!useScreen && this._currentRenderTarget) {
  13025. return this._currentRenderTarget.width;
  13026. }
  13027. return this._gl.drawingBufferWidth;
  13028. };
  13029. /**
  13030. * Gets the current render height
  13031. * @param useScreen defines if screen size must be used (or the current render target if any)
  13032. * @returns a number defining the current render height
  13033. */
  13034. Engine.prototype.getRenderHeight = function (useScreen) {
  13035. if (useScreen === void 0) { useScreen = false; }
  13036. if (!useScreen && this._currentRenderTarget) {
  13037. return this._currentRenderTarget.height;
  13038. }
  13039. return this._gl.drawingBufferHeight;
  13040. };
  13041. /**
  13042. * Gets the HTML canvas attached with the current webGL context
  13043. * @returns a HTML canvas
  13044. */
  13045. Engine.prototype.getRenderingCanvas = function () {
  13046. return this._renderingCanvas;
  13047. };
  13048. /**
  13049. * Gets the client rect of the HTML canvas attached with the current webGL context
  13050. * @returns a client rectanglee
  13051. */
  13052. Engine.prototype.getRenderingCanvasClientRect = function () {
  13053. if (!this._renderingCanvas) {
  13054. return null;
  13055. }
  13056. return this._renderingCanvas.getBoundingClientRect();
  13057. };
  13058. /**
  13059. * Defines the hardware scaling level.
  13060. * By default the hardware scaling level is computed from the window device ratio.
  13061. * 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.
  13062. * @param level defines the level to use
  13063. */
  13064. Engine.prototype.setHardwareScalingLevel = function (level) {
  13065. this._hardwareScalingLevel = level;
  13066. this.resize();
  13067. };
  13068. /**
  13069. * Gets the current hardware scaling level.
  13070. * By default the hardware scaling level is computed from the window device ratio.
  13071. * 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.
  13072. * @returns a number indicating the current hardware scaling level
  13073. */
  13074. Engine.prototype.getHardwareScalingLevel = function () {
  13075. return this._hardwareScalingLevel;
  13076. };
  13077. /**
  13078. * Gets the list of loaded textures
  13079. * @returns an array containing all loaded textures
  13080. */
  13081. Engine.prototype.getLoadedTexturesCache = function () {
  13082. return this._internalTexturesCache;
  13083. };
  13084. /**
  13085. * Gets the object containing all engine capabilities
  13086. * @returns the EngineCapabilities object
  13087. */
  13088. Engine.prototype.getCaps = function () {
  13089. return this._caps;
  13090. };
  13091. Object.defineProperty(Engine.prototype, "drawCalls", {
  13092. /** @hidden */
  13093. get: function () {
  13094. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  13095. return 0;
  13096. },
  13097. enumerable: true,
  13098. configurable: true
  13099. });
  13100. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  13101. /** @hidden */
  13102. get: function () {
  13103. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  13104. return null;
  13105. },
  13106. enumerable: true,
  13107. configurable: true
  13108. });
  13109. /**
  13110. * Gets the current depth function
  13111. * @returns a number defining the depth function
  13112. */
  13113. Engine.prototype.getDepthFunction = function () {
  13114. return this._depthCullingState.depthFunc;
  13115. };
  13116. /**
  13117. * Sets the current depth function
  13118. * @param depthFunc defines the function to use
  13119. */
  13120. Engine.prototype.setDepthFunction = function (depthFunc) {
  13121. this._depthCullingState.depthFunc = depthFunc;
  13122. };
  13123. /**
  13124. * Sets the current depth function to GREATER
  13125. */
  13126. Engine.prototype.setDepthFunctionToGreater = function () {
  13127. this._depthCullingState.depthFunc = this._gl.GREATER;
  13128. };
  13129. /**
  13130. * Sets the current depth function to GEQUAL
  13131. */
  13132. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  13133. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  13134. };
  13135. /**
  13136. * Sets the current depth function to LESS
  13137. */
  13138. Engine.prototype.setDepthFunctionToLess = function () {
  13139. this._depthCullingState.depthFunc = this._gl.LESS;
  13140. };
  13141. /**
  13142. * Sets the current depth function to LEQUAL
  13143. */
  13144. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  13145. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  13146. };
  13147. /**
  13148. * Gets a boolean indicating if stencil buffer is enabled
  13149. * @returns the current stencil buffer state
  13150. */
  13151. Engine.prototype.getStencilBuffer = function () {
  13152. return this._stencilState.stencilTest;
  13153. };
  13154. /**
  13155. * Enable or disable the stencil buffer
  13156. * @param enable defines if the stencil buffer must be enabled or disabled
  13157. */
  13158. Engine.prototype.setStencilBuffer = function (enable) {
  13159. this._stencilState.stencilTest = enable;
  13160. };
  13161. /**
  13162. * Gets the current stencil mask
  13163. * @returns a number defining the new stencil mask to use
  13164. */
  13165. Engine.prototype.getStencilMask = function () {
  13166. return this._stencilState.stencilMask;
  13167. };
  13168. /**
  13169. * Sets the current stencil mask
  13170. * @param mask defines the new stencil mask to use
  13171. */
  13172. Engine.prototype.setStencilMask = function (mask) {
  13173. this._stencilState.stencilMask = mask;
  13174. };
  13175. /**
  13176. * Gets the current stencil function
  13177. * @returns a number defining the stencil function to use
  13178. */
  13179. Engine.prototype.getStencilFunction = function () {
  13180. return this._stencilState.stencilFunc;
  13181. };
  13182. /**
  13183. * Gets the current stencil reference value
  13184. * @returns a number defining the stencil reference value to use
  13185. */
  13186. Engine.prototype.getStencilFunctionReference = function () {
  13187. return this._stencilState.stencilFuncRef;
  13188. };
  13189. /**
  13190. * Gets the current stencil mask
  13191. * @returns a number defining the stencil mask to use
  13192. */
  13193. Engine.prototype.getStencilFunctionMask = function () {
  13194. return this._stencilState.stencilFuncMask;
  13195. };
  13196. /**
  13197. * Sets the current stencil function
  13198. * @param stencilFunc defines the new stencil function to use
  13199. */
  13200. Engine.prototype.setStencilFunction = function (stencilFunc) {
  13201. this._stencilState.stencilFunc = stencilFunc;
  13202. };
  13203. /**
  13204. * Sets the current stencil reference
  13205. * @param reference defines the new stencil reference to use
  13206. */
  13207. Engine.prototype.setStencilFunctionReference = function (reference) {
  13208. this._stencilState.stencilFuncRef = reference;
  13209. };
  13210. /**
  13211. * Sets the current stencil mask
  13212. * @param mask defines the new stencil mask to use
  13213. */
  13214. Engine.prototype.setStencilFunctionMask = function (mask) {
  13215. this._stencilState.stencilFuncMask = mask;
  13216. };
  13217. /**
  13218. * Gets the current stencil operation when stencil fails
  13219. * @returns a number defining stencil operation to use when stencil fails
  13220. */
  13221. Engine.prototype.getStencilOperationFail = function () {
  13222. return this._stencilState.stencilOpStencilFail;
  13223. };
  13224. /**
  13225. * Gets the current stencil operation when depth fails
  13226. * @returns a number defining stencil operation to use when depth fails
  13227. */
  13228. Engine.prototype.getStencilOperationDepthFail = function () {
  13229. return this._stencilState.stencilOpDepthFail;
  13230. };
  13231. /**
  13232. * Gets the current stencil operation when stencil passes
  13233. * @returns a number defining stencil operation to use when stencil passes
  13234. */
  13235. Engine.prototype.getStencilOperationPass = function () {
  13236. return this._stencilState.stencilOpStencilDepthPass;
  13237. };
  13238. /**
  13239. * Sets the stencil operation to use when stencil fails
  13240. * @param operation defines the stencil operation to use when stencil fails
  13241. */
  13242. Engine.prototype.setStencilOperationFail = function (operation) {
  13243. this._stencilState.stencilOpStencilFail = operation;
  13244. };
  13245. /**
  13246. * Sets the stencil operation to use when depth fails
  13247. * @param operation defines the stencil operation to use when depth fails
  13248. */
  13249. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  13250. this._stencilState.stencilOpDepthFail = operation;
  13251. };
  13252. /**
  13253. * Sets the stencil operation to use when stencil passes
  13254. * @param operation defines the stencil operation to use when stencil passes
  13255. */
  13256. Engine.prototype.setStencilOperationPass = function (operation) {
  13257. this._stencilState.stencilOpStencilDepthPass = operation;
  13258. };
  13259. /**
  13260. * Sets a boolean indicating if the dithering state is enabled or disabled
  13261. * @param value defines the dithering state
  13262. */
  13263. Engine.prototype.setDitheringState = function (value) {
  13264. if (value) {
  13265. this._gl.enable(this._gl.DITHER);
  13266. }
  13267. else {
  13268. this._gl.disable(this._gl.DITHER);
  13269. }
  13270. };
  13271. /**
  13272. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  13273. * @param value defines the rasterizer state
  13274. */
  13275. Engine.prototype.setRasterizerState = function (value) {
  13276. if (value) {
  13277. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  13278. }
  13279. else {
  13280. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  13281. }
  13282. };
  13283. /**
  13284. * stop executing a render loop function and remove it from the execution array
  13285. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  13286. */
  13287. Engine.prototype.stopRenderLoop = function (renderFunction) {
  13288. if (!renderFunction) {
  13289. this._activeRenderLoops = [];
  13290. return;
  13291. }
  13292. var index = this._activeRenderLoops.indexOf(renderFunction);
  13293. if (index >= 0) {
  13294. this._activeRenderLoops.splice(index, 1);
  13295. }
  13296. };
  13297. /** @hidden */
  13298. Engine.prototype._renderLoop = function () {
  13299. if (!this._contextWasLost) {
  13300. var shouldRender = true;
  13301. if (!this.renderEvenInBackground && this._windowIsBackground) {
  13302. shouldRender = false;
  13303. }
  13304. if (shouldRender) {
  13305. // Start new frame
  13306. this.beginFrame();
  13307. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  13308. var renderFunction = this._activeRenderLoops[index];
  13309. renderFunction();
  13310. }
  13311. // Present
  13312. this.endFrame();
  13313. }
  13314. }
  13315. if (this._activeRenderLoops.length > 0) {
  13316. // Register new frame
  13317. var requester = null;
  13318. if (this._vrDisplay && this._vrDisplay.isPresenting)
  13319. requester = this._vrDisplay;
  13320. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  13321. }
  13322. else {
  13323. this._renderingQueueLaunched = false;
  13324. }
  13325. };
  13326. /**
  13327. * Register and execute a render loop. The engine can have more than one render function
  13328. * @param renderFunction defines the function to continuously execute
  13329. */
  13330. Engine.prototype.runRenderLoop = function (renderFunction) {
  13331. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  13332. return;
  13333. }
  13334. this._activeRenderLoops.push(renderFunction);
  13335. if (!this._renderingQueueLaunched) {
  13336. this._renderingQueueLaunched = true;
  13337. this._bindedRenderFunction = this._renderLoop.bind(this);
  13338. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  13339. }
  13340. };
  13341. /**
  13342. * Toggle full screen mode
  13343. * @param requestPointerLock defines if a pointer lock should be requested from the user
  13344. */
  13345. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  13346. if (this.isFullscreen) {
  13347. BABYLON.Tools.ExitFullscreen();
  13348. }
  13349. else {
  13350. this._pointerLockRequested = requestPointerLock;
  13351. if (this._renderingCanvas) {
  13352. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  13353. }
  13354. }
  13355. };
  13356. /**
  13357. * Clear the current render buffer or the current render target (if any is set up)
  13358. * @param color defines the color to use
  13359. * @param backBuffer defines if the back buffer must be cleared
  13360. * @param depth defines if the depth buffer must be cleared
  13361. * @param stencil defines if the stencil buffer must be cleared
  13362. */
  13363. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  13364. if (stencil === void 0) { stencil = false; }
  13365. this.applyStates();
  13366. var mode = 0;
  13367. if (backBuffer && color) {
  13368. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  13369. mode |= this._gl.COLOR_BUFFER_BIT;
  13370. }
  13371. if (depth) {
  13372. this._gl.clearDepth(1.0);
  13373. mode |= this._gl.DEPTH_BUFFER_BIT;
  13374. }
  13375. if (stencil) {
  13376. this._gl.clearStencil(0);
  13377. mode |= this._gl.STENCIL_BUFFER_BIT;
  13378. }
  13379. this._gl.clear(mode);
  13380. };
  13381. /**
  13382. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  13383. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  13384. * @param y defines the y-coordinate of the corner of the clear rectangle
  13385. * @param width defines the width of the clear rectangle
  13386. * @param height defines the height of the clear rectangle
  13387. * @param clearColor defines the clear color
  13388. */
  13389. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13390. var gl = this._gl;
  13391. // Save state
  13392. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13393. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13394. // Change state
  13395. gl.enable(gl.SCISSOR_TEST);
  13396. gl.scissor(x, y, width, height);
  13397. // Clear
  13398. this.clear(clearColor, true, true, true);
  13399. // Restore state
  13400. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13401. if (curScissor === true) {
  13402. gl.enable(gl.SCISSOR_TEST);
  13403. }
  13404. else {
  13405. gl.disable(gl.SCISSOR_TEST);
  13406. }
  13407. };
  13408. /** @hidden */
  13409. Engine.prototype._viewport = function (x, y, width, height) {
  13410. if (x !== this._viewportCached.x ||
  13411. y !== this._viewportCached.y ||
  13412. width !== this._viewportCached.z ||
  13413. height !== this._viewportCached.w) {
  13414. this._viewportCached.x = x;
  13415. this._viewportCached.y = y;
  13416. this._viewportCached.z = width;
  13417. this._viewportCached.w = height;
  13418. this._gl.viewport(x, y, width, height);
  13419. }
  13420. };
  13421. /**
  13422. * Set the WebGL's viewport
  13423. * @param viewport defines the viewport element to be used
  13424. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13425. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13426. */
  13427. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13428. var width = requiredWidth || this.getRenderWidth();
  13429. var height = requiredHeight || this.getRenderHeight();
  13430. var x = viewport.x || 0;
  13431. var y = viewport.y || 0;
  13432. this._cachedViewport = viewport;
  13433. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13434. };
  13435. /**
  13436. * Directly set the WebGL Viewport
  13437. * @param x defines the x coordinate of the viewport (in screen space)
  13438. * @param y defines the y coordinate of the viewport (in screen space)
  13439. * @param width defines the width of the viewport (in screen space)
  13440. * @param height defines the height of the viewport (in screen space)
  13441. * @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
  13442. */
  13443. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13444. var currentViewport = this._cachedViewport;
  13445. this._cachedViewport = null;
  13446. this._viewport(x, y, width, height);
  13447. return currentViewport;
  13448. };
  13449. /**
  13450. * Begin a new frame
  13451. */
  13452. Engine.prototype.beginFrame = function () {
  13453. this.onBeginFrameObservable.notifyObservers(this);
  13454. this._measureFps();
  13455. };
  13456. /**
  13457. * Enf the current frame
  13458. */
  13459. Engine.prototype.endFrame = function () {
  13460. // Force a flush in case we are using a bad OS.
  13461. if (this._badOS) {
  13462. this.flushFramebuffer();
  13463. }
  13464. // Submit frame to the vr device, if enabled
  13465. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13466. // TODO: We should only submit the frame if we read frameData successfully.
  13467. this._vrDisplay.submitFrame();
  13468. }
  13469. this.onEndFrameObservable.notifyObservers(this);
  13470. };
  13471. /**
  13472. * Resize the view according to the canvas' size
  13473. */
  13474. Engine.prototype.resize = function () {
  13475. // We're not resizing the size of the canvas while in VR mode & presenting
  13476. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13477. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13478. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13479. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13480. }
  13481. };
  13482. /**
  13483. * Force a specific size of the canvas
  13484. * @param width defines the new canvas' width
  13485. * @param height defines the new canvas' height
  13486. */
  13487. Engine.prototype.setSize = function (width, height) {
  13488. if (!this._renderingCanvas) {
  13489. return;
  13490. }
  13491. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13492. return;
  13493. }
  13494. this._renderingCanvas.width = width;
  13495. this._renderingCanvas.height = height;
  13496. for (var index = 0; index < this.scenes.length; index++) {
  13497. var scene = this.scenes[index];
  13498. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13499. var cam = scene.cameras[camIndex];
  13500. cam._currentRenderId = 0;
  13501. }
  13502. }
  13503. if (this.onResizeObservable.hasObservers) {
  13504. this.onResizeObservable.notifyObservers(this);
  13505. }
  13506. };
  13507. // WebVR functions
  13508. /**
  13509. * Gets a boolean indicating if a webVR device was detected
  13510. * @returns true if a webVR device was detected
  13511. */
  13512. Engine.prototype.isVRDevicePresent = function () {
  13513. return !!this._vrDisplay;
  13514. };
  13515. /**
  13516. * Gets the current webVR device
  13517. * @returns the current webVR device (or null)
  13518. */
  13519. Engine.prototype.getVRDevice = function () {
  13520. return this._vrDisplay;
  13521. };
  13522. /**
  13523. * Initializes a webVR display and starts listening to display change events
  13524. * The onVRDisplayChangedObservable will be notified upon these changes
  13525. * @returns The onVRDisplayChangedObservable
  13526. */
  13527. Engine.prototype.initWebVR = function () {
  13528. this.initWebVRAsync();
  13529. return this.onVRDisplayChangedObservable;
  13530. };
  13531. /**
  13532. * Initializes a webVR display and starts listening to display change events
  13533. * The onVRDisplayChangedObservable will be notified upon these changes
  13534. * @returns A promise containing a VRDisplay and if vr is supported
  13535. */
  13536. Engine.prototype.initWebVRAsync = function () {
  13537. var _this = this;
  13538. var notifyObservers = function () {
  13539. var eventArgs = {
  13540. vrDisplay: _this._vrDisplay,
  13541. vrSupported: _this._vrSupported
  13542. };
  13543. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13544. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13545. };
  13546. if (!this._onVrDisplayConnect) {
  13547. this._onVrDisplayConnect = function (event) {
  13548. _this._vrDisplay = event.display;
  13549. notifyObservers();
  13550. };
  13551. this._onVrDisplayDisconnect = function () {
  13552. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13553. _this._vrDisplay = undefined;
  13554. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13555. notifyObservers();
  13556. };
  13557. this._onVrDisplayPresentChange = function () {
  13558. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13559. };
  13560. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13561. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13562. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13563. }
  13564. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13565. this._webVRInitPromise.then(notifyObservers);
  13566. return this._webVRInitPromise;
  13567. };
  13568. /**
  13569. * Call this function to switch to webVR mode
  13570. * Will do nothing if webVR is not supported or if there is no webVR device
  13571. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13572. */
  13573. Engine.prototype.enableVR = function () {
  13574. var _this = this;
  13575. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13576. var onResolved = function () {
  13577. _this.onVRRequestPresentComplete.notifyObservers(true);
  13578. _this._onVRFullScreenTriggered();
  13579. };
  13580. var onRejected = function () {
  13581. _this.onVRRequestPresentComplete.notifyObservers(false);
  13582. };
  13583. this.onVRRequestPresentStart.notifyObservers(this);
  13584. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13585. }
  13586. };
  13587. /**
  13588. * Call this function to leave webVR mode
  13589. * Will do nothing if webVR is not supported or if there is no webVR device
  13590. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13591. */
  13592. Engine.prototype.disableVR = function () {
  13593. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13594. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13595. }
  13596. };
  13597. Engine.prototype._getVRDisplaysAsync = function () {
  13598. var _this = this;
  13599. return new Promise(function (res, rej) {
  13600. if (navigator.getVRDisplays) {
  13601. navigator.getVRDisplays().then(function (devices) {
  13602. _this._vrSupported = true;
  13603. // note that devices may actually be an empty array. This is fine;
  13604. // we expect this._vrDisplay to be undefined in this case.
  13605. _this._vrDisplay = devices[0];
  13606. res({
  13607. vrDisplay: _this._vrDisplay,
  13608. vrSupported: _this._vrSupported
  13609. });
  13610. });
  13611. }
  13612. else {
  13613. _this._vrDisplay = undefined;
  13614. _this._vrSupported = false;
  13615. res({
  13616. vrDisplay: _this._vrDisplay,
  13617. vrSupported: _this._vrSupported
  13618. });
  13619. }
  13620. });
  13621. };
  13622. /**
  13623. * Binds the frame buffer to the specified texture.
  13624. * @param texture The texture to render to or null for the default canvas
  13625. * @param faceIndex The face of the texture to render to in case of cube texture
  13626. * @param requiredWidth The width of the target to render to
  13627. * @param requiredHeight The height of the target to render to
  13628. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13629. * @param depthStencilTexture The depth stencil texture to use to render
  13630. * @param lodLevel defines le lod level to bind to the frame buffer
  13631. */
  13632. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13633. if (lodLevel === void 0) { lodLevel = 0; }
  13634. if (this._currentRenderTarget) {
  13635. this.unBindFramebuffer(this._currentRenderTarget);
  13636. }
  13637. this._currentRenderTarget = texture;
  13638. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13639. var gl = this._gl;
  13640. if (texture.isCube) {
  13641. if (faceIndex === undefined) {
  13642. faceIndex = 0;
  13643. }
  13644. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13645. if (depthStencilTexture) {
  13646. if (depthStencilTexture._generateStencilBuffer) {
  13647. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13648. }
  13649. else {
  13650. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13651. }
  13652. }
  13653. }
  13654. if (this._cachedViewport && !forceFullscreenViewport) {
  13655. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13656. }
  13657. else {
  13658. if (!requiredWidth) {
  13659. requiredWidth = texture.width;
  13660. if (lodLevel) {
  13661. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13662. }
  13663. }
  13664. if (!requiredHeight) {
  13665. requiredHeight = texture.height;
  13666. if (lodLevel) {
  13667. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13668. }
  13669. }
  13670. this._viewport(0, 0, requiredWidth, requiredHeight);
  13671. }
  13672. this.wipeCaches();
  13673. };
  13674. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13675. if (this._currentFramebuffer !== framebuffer) {
  13676. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13677. this._currentFramebuffer = framebuffer;
  13678. }
  13679. };
  13680. /**
  13681. * Unbind the current render target texture from the webGL context
  13682. * @param texture defines the render target texture to unbind
  13683. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13684. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13685. */
  13686. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13687. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13688. this._currentRenderTarget = null;
  13689. // If MSAA, we need to bitblt back to main texture
  13690. var gl = this._gl;
  13691. if (texture._MSAAFramebuffer) {
  13692. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13693. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13694. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13695. }
  13696. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13697. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13698. gl.generateMipmap(gl.TEXTURE_2D);
  13699. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13700. }
  13701. if (onBeforeUnbind) {
  13702. if (texture._MSAAFramebuffer) {
  13703. // Bind the correct framebuffer
  13704. this.bindUnboundFramebuffer(texture._framebuffer);
  13705. }
  13706. onBeforeUnbind();
  13707. }
  13708. this.bindUnboundFramebuffer(null);
  13709. };
  13710. /**
  13711. * Unbind a list of render target textures from the webGL context
  13712. * This is used only when drawBuffer extension or webGL2 are active
  13713. * @param textures defines the render target textures to unbind
  13714. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13715. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13716. */
  13717. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13718. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13719. this._currentRenderTarget = null;
  13720. // If MSAA, we need to bitblt back to main texture
  13721. var gl = this._gl;
  13722. if (textures[0]._MSAAFramebuffer) {
  13723. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13724. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13725. var attachments = textures[0]._attachments;
  13726. if (!attachments) {
  13727. attachments = new Array(textures.length);
  13728. textures[0]._attachments = attachments;
  13729. }
  13730. for (var i = 0; i < textures.length; i++) {
  13731. var texture = textures[i];
  13732. for (var j = 0; j < attachments.length; j++) {
  13733. attachments[j] = gl.NONE;
  13734. }
  13735. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13736. gl.readBuffer(attachments[i]);
  13737. gl.drawBuffers(attachments);
  13738. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13739. }
  13740. for (var i = 0; i < attachments.length; i++) {
  13741. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13742. }
  13743. gl.drawBuffers(attachments);
  13744. }
  13745. for (var i = 0; i < textures.length; i++) {
  13746. var texture = textures[i];
  13747. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13748. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13749. gl.generateMipmap(gl.TEXTURE_2D);
  13750. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13751. }
  13752. }
  13753. if (onBeforeUnbind) {
  13754. if (textures[0]._MSAAFramebuffer) {
  13755. // Bind the correct framebuffer
  13756. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13757. }
  13758. onBeforeUnbind();
  13759. }
  13760. this.bindUnboundFramebuffer(null);
  13761. };
  13762. /**
  13763. * Force the mipmap generation for the given render target texture
  13764. * @param texture defines the render target texture to use
  13765. */
  13766. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13767. if (texture.generateMipMaps) {
  13768. var gl = this._gl;
  13769. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13770. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13771. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13772. }
  13773. };
  13774. /**
  13775. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13776. */
  13777. Engine.prototype.flushFramebuffer = function () {
  13778. this._gl.flush();
  13779. };
  13780. /**
  13781. * Unbind the current render target and bind the default framebuffer
  13782. */
  13783. Engine.prototype.restoreDefaultFramebuffer = function () {
  13784. if (this._currentRenderTarget) {
  13785. this.unBindFramebuffer(this._currentRenderTarget);
  13786. }
  13787. else {
  13788. this.bindUnboundFramebuffer(null);
  13789. }
  13790. if (this._cachedViewport) {
  13791. this.setViewport(this._cachedViewport);
  13792. }
  13793. this.wipeCaches();
  13794. };
  13795. // UBOs
  13796. /**
  13797. * Create an uniform buffer
  13798. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13799. * @param elements defines the content of the uniform buffer
  13800. * @returns the webGL uniform buffer
  13801. */
  13802. Engine.prototype.createUniformBuffer = function (elements) {
  13803. var ubo = this._gl.createBuffer();
  13804. if (!ubo) {
  13805. throw new Error("Unable to create uniform buffer");
  13806. }
  13807. this.bindUniformBuffer(ubo);
  13808. if (elements instanceof Float32Array) {
  13809. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13810. }
  13811. else {
  13812. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13813. }
  13814. this.bindUniformBuffer(null);
  13815. ubo.references = 1;
  13816. return ubo;
  13817. };
  13818. /**
  13819. * Create a dynamic uniform buffer
  13820. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13821. * @param elements defines the content of the uniform buffer
  13822. * @returns the webGL uniform buffer
  13823. */
  13824. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13825. var ubo = this._gl.createBuffer();
  13826. if (!ubo) {
  13827. throw new Error("Unable to create dynamic uniform buffer");
  13828. }
  13829. this.bindUniformBuffer(ubo);
  13830. if (elements instanceof Float32Array) {
  13831. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13832. }
  13833. else {
  13834. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13835. }
  13836. this.bindUniformBuffer(null);
  13837. ubo.references = 1;
  13838. return ubo;
  13839. };
  13840. /**
  13841. * Update an existing uniform buffer
  13842. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13843. * @param uniformBuffer defines the target uniform buffer
  13844. * @param elements defines the content to update
  13845. * @param offset defines the offset in the uniform buffer where update should start
  13846. * @param count defines the size of the data to update
  13847. */
  13848. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13849. this.bindUniformBuffer(uniformBuffer);
  13850. if (offset === undefined) {
  13851. offset = 0;
  13852. }
  13853. if (count === undefined) {
  13854. if (elements instanceof Float32Array) {
  13855. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13856. }
  13857. else {
  13858. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13859. }
  13860. }
  13861. else {
  13862. if (elements instanceof Float32Array) {
  13863. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13864. }
  13865. else {
  13866. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13867. }
  13868. }
  13869. this.bindUniformBuffer(null);
  13870. };
  13871. // VBOs
  13872. Engine.prototype._resetVertexBufferBinding = function () {
  13873. this.bindArrayBuffer(null);
  13874. this._cachedVertexBuffers = null;
  13875. };
  13876. /**
  13877. * Creates a vertex buffer
  13878. * @param data the data for the vertex buffer
  13879. * @returns the new WebGL static buffer
  13880. */
  13881. Engine.prototype.createVertexBuffer = function (data) {
  13882. var vbo = this._gl.createBuffer();
  13883. if (!vbo) {
  13884. throw new Error("Unable to create vertex buffer");
  13885. }
  13886. this.bindArrayBuffer(vbo);
  13887. if (data instanceof Array) {
  13888. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13889. }
  13890. else {
  13891. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13892. }
  13893. this._resetVertexBufferBinding();
  13894. vbo.references = 1;
  13895. return vbo;
  13896. };
  13897. /**
  13898. * Creates a dynamic vertex buffer
  13899. * @param data the data for the dynamic vertex buffer
  13900. * @returns the new WebGL dynamic buffer
  13901. */
  13902. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13903. var vbo = this._gl.createBuffer();
  13904. if (!vbo) {
  13905. throw new Error("Unable to create dynamic vertex buffer");
  13906. }
  13907. this.bindArrayBuffer(vbo);
  13908. if (data instanceof Array) {
  13909. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13910. }
  13911. else {
  13912. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13913. }
  13914. this._resetVertexBufferBinding();
  13915. vbo.references = 1;
  13916. return vbo;
  13917. };
  13918. /**
  13919. * Update a dynamic index buffer
  13920. * @param indexBuffer defines the target index buffer
  13921. * @param indices defines the data to update
  13922. * @param offset defines the offset in the target index buffer where update should start
  13923. */
  13924. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13925. if (offset === void 0) { offset = 0; }
  13926. // Force cache update
  13927. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13928. this.bindIndexBuffer(indexBuffer);
  13929. var arrayBuffer;
  13930. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13931. arrayBuffer = indices;
  13932. }
  13933. else {
  13934. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13935. }
  13936. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13937. this._resetIndexBufferBinding();
  13938. };
  13939. /**
  13940. * Updates a dynamic vertex buffer.
  13941. * @param vertexBuffer the vertex buffer to update
  13942. * @param data the data used to update the vertex buffer
  13943. * @param byteOffset the byte offset of the data
  13944. * @param byteLength the byte length of the data
  13945. */
  13946. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13947. this.bindArrayBuffer(vertexBuffer);
  13948. if (byteOffset === undefined) {
  13949. byteOffset = 0;
  13950. }
  13951. if (byteLength === undefined) {
  13952. if (data instanceof Array) {
  13953. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13954. }
  13955. else {
  13956. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13957. }
  13958. }
  13959. else {
  13960. if (data instanceof Array) {
  13961. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13962. }
  13963. else {
  13964. if (data instanceof ArrayBuffer) {
  13965. data = new Uint8Array(data, byteOffset, byteLength);
  13966. }
  13967. else {
  13968. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13969. }
  13970. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13971. }
  13972. }
  13973. this._resetVertexBufferBinding();
  13974. };
  13975. Engine.prototype._resetIndexBufferBinding = function () {
  13976. this.bindIndexBuffer(null);
  13977. this._cachedIndexBuffer = null;
  13978. };
  13979. /**
  13980. * Creates a new index buffer
  13981. * @param indices defines the content of the index buffer
  13982. * @param updatable defines if the index buffer must be updatable
  13983. * @returns a new webGL buffer
  13984. */
  13985. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13986. var vbo = this._gl.createBuffer();
  13987. if (!vbo) {
  13988. throw new Error("Unable to create index buffer");
  13989. }
  13990. this.bindIndexBuffer(vbo);
  13991. // Check for 32 bits indices
  13992. var arrayBuffer;
  13993. var need32Bits = false;
  13994. if (indices instanceof Uint16Array) {
  13995. arrayBuffer = indices;
  13996. }
  13997. else {
  13998. //check 32 bit support
  13999. if (this._caps.uintIndices) {
  14000. if (indices instanceof Uint32Array) {
  14001. arrayBuffer = indices;
  14002. need32Bits = true;
  14003. }
  14004. else {
  14005. //number[] or Int32Array, check if 32 bit is necessary
  14006. for (var index = 0; index < indices.length; index++) {
  14007. if (indices[index] > 65535) {
  14008. need32Bits = true;
  14009. break;
  14010. }
  14011. }
  14012. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  14013. }
  14014. }
  14015. else {
  14016. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  14017. arrayBuffer = new Uint16Array(indices);
  14018. }
  14019. }
  14020. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  14021. this._resetIndexBufferBinding();
  14022. vbo.references = 1;
  14023. vbo.is32Bits = need32Bits;
  14024. return vbo;
  14025. };
  14026. /**
  14027. * Bind a webGL buffer to the webGL context
  14028. * @param buffer defines the buffer to bind
  14029. */
  14030. Engine.prototype.bindArrayBuffer = function (buffer) {
  14031. if (!this._vaoRecordInProgress) {
  14032. this._unbindVertexArrayObject();
  14033. }
  14034. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  14035. };
  14036. /**
  14037. * Bind an uniform buffer to the current webGL context
  14038. * @param buffer defines the buffer to bind
  14039. */
  14040. Engine.prototype.bindUniformBuffer = function (buffer) {
  14041. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  14042. };
  14043. /**
  14044. * Bind a buffer to the current webGL context at a given location
  14045. * @param buffer defines the buffer to bind
  14046. * @param location defines the index where to bind the buffer
  14047. */
  14048. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  14049. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  14050. };
  14051. /**
  14052. * Bind a specific block at a given index in a specific shader program
  14053. * @param shaderProgram defines the shader program
  14054. * @param blockName defines the block name
  14055. * @param index defines the index where to bind the block
  14056. */
  14057. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  14058. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  14059. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  14060. };
  14061. ;
  14062. Engine.prototype.bindIndexBuffer = function (buffer) {
  14063. if (!this._vaoRecordInProgress) {
  14064. this._unbindVertexArrayObject();
  14065. }
  14066. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  14067. };
  14068. Engine.prototype.bindBuffer = function (buffer, target) {
  14069. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  14070. this._gl.bindBuffer(target, buffer);
  14071. this._currentBoundBuffer[target] = buffer;
  14072. }
  14073. };
  14074. /**
  14075. * update the bound buffer with the given data
  14076. * @param data defines the data to update
  14077. */
  14078. Engine.prototype.updateArrayBuffer = function (data) {
  14079. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14080. };
  14081. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  14082. var pointer = this._currentBufferPointers[indx];
  14083. var changed = false;
  14084. if (!pointer.active) {
  14085. changed = true;
  14086. pointer.active = true;
  14087. pointer.index = indx;
  14088. pointer.size = size;
  14089. pointer.type = type;
  14090. pointer.normalized = normalized;
  14091. pointer.stride = stride;
  14092. pointer.offset = offset;
  14093. pointer.buffer = buffer;
  14094. }
  14095. else {
  14096. if (pointer.buffer !== buffer) {
  14097. pointer.buffer = buffer;
  14098. changed = true;
  14099. }
  14100. if (pointer.size !== size) {
  14101. pointer.size = size;
  14102. changed = true;
  14103. }
  14104. if (pointer.type !== type) {
  14105. pointer.type = type;
  14106. changed = true;
  14107. }
  14108. if (pointer.normalized !== normalized) {
  14109. pointer.normalized = normalized;
  14110. changed = true;
  14111. }
  14112. if (pointer.stride !== stride) {
  14113. pointer.stride = stride;
  14114. changed = true;
  14115. }
  14116. if (pointer.offset !== offset) {
  14117. pointer.offset = offset;
  14118. changed = true;
  14119. }
  14120. }
  14121. if (changed || this._vaoRecordInProgress) {
  14122. this.bindArrayBuffer(buffer);
  14123. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  14124. }
  14125. };
  14126. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  14127. if (indexBuffer == null) {
  14128. return;
  14129. }
  14130. if (this._cachedIndexBuffer !== indexBuffer) {
  14131. this._cachedIndexBuffer = indexBuffer;
  14132. this.bindIndexBuffer(indexBuffer);
  14133. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  14134. }
  14135. };
  14136. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  14137. var attributes = effect.getAttributesNames();
  14138. if (!this._vaoRecordInProgress) {
  14139. this._unbindVertexArrayObject();
  14140. }
  14141. this.unbindAllAttributes();
  14142. for (var index = 0; index < attributes.length; index++) {
  14143. var order = effect.getAttributeLocation(index);
  14144. if (order >= 0) {
  14145. var vertexBuffer = vertexBuffers[attributes[index]];
  14146. if (!vertexBuffer) {
  14147. continue;
  14148. }
  14149. this._gl.enableVertexAttribArray(order);
  14150. if (!this._vaoRecordInProgress) {
  14151. this._vertexAttribArraysEnabled[order] = true;
  14152. }
  14153. var buffer = vertexBuffer.getBuffer();
  14154. if (buffer) {
  14155. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  14156. if (vertexBuffer.getIsInstanced()) {
  14157. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  14158. if (!this._vaoRecordInProgress) {
  14159. this._currentInstanceLocations.push(order);
  14160. this._currentInstanceBuffers.push(buffer);
  14161. }
  14162. }
  14163. }
  14164. }
  14165. }
  14166. };
  14167. /**
  14168. * Records a vertex array object
  14169. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14170. * @param vertexBuffers defines the list of vertex buffers to store
  14171. * @param indexBuffer defines the index buffer to store
  14172. * @param effect defines the effect to store
  14173. * @returns the new vertex array object
  14174. */
  14175. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  14176. var vao = this._gl.createVertexArray();
  14177. this._vaoRecordInProgress = true;
  14178. this._gl.bindVertexArray(vao);
  14179. this._mustWipeVertexAttributes = true;
  14180. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14181. this.bindIndexBuffer(indexBuffer);
  14182. this._vaoRecordInProgress = false;
  14183. this._gl.bindVertexArray(null);
  14184. return vao;
  14185. };
  14186. /**
  14187. * Bind a specific vertex array object
  14188. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  14189. * @param vertexArrayObject defines the vertex array object to bind
  14190. * @param indexBuffer defines the index buffer to bind
  14191. */
  14192. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  14193. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  14194. this._cachedVertexArrayObject = vertexArrayObject;
  14195. this._gl.bindVertexArray(vertexArrayObject);
  14196. this._cachedVertexBuffers = null;
  14197. this._cachedIndexBuffer = null;
  14198. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  14199. this._mustWipeVertexAttributes = true;
  14200. }
  14201. };
  14202. /**
  14203. * Bind webGl buffers directly to the webGL context
  14204. * @param vertexBuffer defines the vertex buffer to bind
  14205. * @param indexBuffer defines the index buffer to bind
  14206. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  14207. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  14208. * @param effect defines the effect associated with the vertex buffer
  14209. */
  14210. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  14211. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  14212. this._cachedVertexBuffers = vertexBuffer;
  14213. this._cachedEffectForVertexBuffers = effect;
  14214. var attributesCount = effect.getAttributesCount();
  14215. this._unbindVertexArrayObject();
  14216. this.unbindAllAttributes();
  14217. var offset = 0;
  14218. for (var index = 0; index < attributesCount; index++) {
  14219. if (index < vertexDeclaration.length) {
  14220. var order = effect.getAttributeLocation(index);
  14221. if (order >= 0) {
  14222. this._gl.enableVertexAttribArray(order);
  14223. this._vertexAttribArraysEnabled[order] = true;
  14224. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  14225. }
  14226. offset += vertexDeclaration[index] * 4;
  14227. }
  14228. }
  14229. }
  14230. this._bindIndexBufferWithCache(indexBuffer);
  14231. };
  14232. Engine.prototype._unbindVertexArrayObject = function () {
  14233. if (!this._cachedVertexArrayObject) {
  14234. return;
  14235. }
  14236. this._cachedVertexArrayObject = null;
  14237. this._gl.bindVertexArray(null);
  14238. };
  14239. /**
  14240. * Bind a list of vertex buffers to the webGL context
  14241. * @param vertexBuffers defines the list of vertex buffers to bind
  14242. * @param indexBuffer defines the index buffer to bind
  14243. * @param effect defines the effect associated with the vertex buffers
  14244. */
  14245. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  14246. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  14247. this._cachedVertexBuffers = vertexBuffers;
  14248. this._cachedEffectForVertexBuffers = effect;
  14249. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  14250. }
  14251. this._bindIndexBufferWithCache(indexBuffer);
  14252. };
  14253. /**
  14254. * Unbind all instance attributes
  14255. */
  14256. Engine.prototype.unbindInstanceAttributes = function () {
  14257. var boundBuffer;
  14258. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  14259. var instancesBuffer = this._currentInstanceBuffers[i];
  14260. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  14261. boundBuffer = instancesBuffer;
  14262. this.bindArrayBuffer(instancesBuffer);
  14263. }
  14264. var offsetLocation = this._currentInstanceLocations[i];
  14265. this._gl.vertexAttribDivisor(offsetLocation, 0);
  14266. }
  14267. this._currentInstanceBuffers.length = 0;
  14268. this._currentInstanceLocations.length = 0;
  14269. };
  14270. /**
  14271. * Release and free the memory of a vertex array object
  14272. * @param vao defines the vertex array object to delete
  14273. */
  14274. Engine.prototype.releaseVertexArrayObject = function (vao) {
  14275. this._gl.deleteVertexArray(vao);
  14276. };
  14277. /** @hidden */
  14278. Engine.prototype._releaseBuffer = function (buffer) {
  14279. buffer.references--;
  14280. if (buffer.references === 0) {
  14281. this._gl.deleteBuffer(buffer);
  14282. return true;
  14283. }
  14284. return false;
  14285. };
  14286. /**
  14287. * Creates a webGL buffer to use with instanciation
  14288. * @param capacity defines the size of the buffer
  14289. * @returns the webGL buffer
  14290. */
  14291. Engine.prototype.createInstancesBuffer = function (capacity) {
  14292. var buffer = this._gl.createBuffer();
  14293. if (!buffer) {
  14294. throw new Error("Unable to create instance buffer");
  14295. }
  14296. buffer.capacity = capacity;
  14297. this.bindArrayBuffer(buffer);
  14298. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  14299. return buffer;
  14300. };
  14301. /**
  14302. * Delete a webGL buffer used with instanciation
  14303. * @param buffer defines the webGL buffer to delete
  14304. */
  14305. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  14306. this._gl.deleteBuffer(buffer);
  14307. };
  14308. /**
  14309. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  14310. * @param instancesBuffer defines the webGL buffer to update and bind
  14311. * @param data defines the data to store in the buffer
  14312. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  14313. */
  14314. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  14315. this.bindArrayBuffer(instancesBuffer);
  14316. if (data) {
  14317. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  14318. }
  14319. if (offsetLocations[0].index !== undefined) {
  14320. var stride = 0;
  14321. for (var i = 0; i < offsetLocations.length; i++) {
  14322. var ai = offsetLocations[i];
  14323. stride += ai.attributeSize * 4;
  14324. }
  14325. for (var i = 0; i < offsetLocations.length; i++) {
  14326. var ai = offsetLocations[i];
  14327. if (!this._vertexAttribArraysEnabled[ai.index]) {
  14328. this._gl.enableVertexAttribArray(ai.index);
  14329. this._vertexAttribArraysEnabled[ai.index] = true;
  14330. }
  14331. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  14332. this._gl.vertexAttribDivisor(ai.index, 1);
  14333. this._currentInstanceLocations.push(ai.index);
  14334. this._currentInstanceBuffers.push(instancesBuffer);
  14335. }
  14336. }
  14337. else {
  14338. for (var index = 0; index < 4; index++) {
  14339. var offsetLocation = offsetLocations[index];
  14340. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  14341. this._gl.enableVertexAttribArray(offsetLocation);
  14342. this._vertexAttribArraysEnabled[offsetLocation] = true;
  14343. }
  14344. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  14345. this._gl.vertexAttribDivisor(offsetLocation, 1);
  14346. this._currentInstanceLocations.push(offsetLocation);
  14347. this._currentInstanceBuffers.push(instancesBuffer);
  14348. }
  14349. }
  14350. };
  14351. /**
  14352. * Apply all cached states (depth, culling, stencil and alpha)
  14353. */
  14354. Engine.prototype.applyStates = function () {
  14355. this._depthCullingState.apply(this._gl);
  14356. this._stencilState.apply(this._gl);
  14357. this._alphaState.apply(this._gl);
  14358. };
  14359. /**
  14360. * Send a draw order
  14361. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14362. * @param indexStart defines the starting index
  14363. * @param indexCount defines the number of index to draw
  14364. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14365. */
  14366. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  14367. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  14368. };
  14369. /**
  14370. * Draw a list of points
  14371. * @param verticesStart defines the index of first vertex to draw
  14372. * @param verticesCount defines the count of vertices to draw
  14373. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14374. */
  14375. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  14376. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  14377. };
  14378. /**
  14379. * Draw a list of unindexed primitives
  14380. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  14381. * @param verticesStart defines the index of first vertex to draw
  14382. * @param verticesCount defines the count of vertices to draw
  14383. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14384. */
  14385. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  14386. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14387. };
  14388. /**
  14389. * Draw a list of indexed primitives
  14390. * @param fillMode defines the primitive to use
  14391. * @param indexStart defines the starting index
  14392. * @param indexCount defines the number of index to draw
  14393. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14394. */
  14395. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14396. // Apply states
  14397. this.applyStates();
  14398. this._drawCalls.addCount(1, false);
  14399. // Render
  14400. var drawMode = this._drawMode(fillMode);
  14401. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14402. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14403. if (instancesCount) {
  14404. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14405. }
  14406. else {
  14407. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14408. }
  14409. };
  14410. /**
  14411. * Draw a list of unindexed primitives
  14412. * @param fillMode defines the primitive to use
  14413. * @param verticesStart defines the index of first vertex to draw
  14414. * @param verticesCount defines the count of vertices to draw
  14415. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14416. */
  14417. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14418. // Apply states
  14419. this.applyStates();
  14420. this._drawCalls.addCount(1, false);
  14421. var drawMode = this._drawMode(fillMode);
  14422. if (instancesCount) {
  14423. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14424. }
  14425. else {
  14426. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14427. }
  14428. };
  14429. Engine.prototype._drawMode = function (fillMode) {
  14430. switch (fillMode) {
  14431. // Triangle views
  14432. case BABYLON.Material.TriangleFillMode:
  14433. return this._gl.TRIANGLES;
  14434. case BABYLON.Material.PointFillMode:
  14435. return this._gl.POINTS;
  14436. case BABYLON.Material.WireFrameFillMode:
  14437. return this._gl.LINES;
  14438. // Draw modes
  14439. case BABYLON.Material.PointListDrawMode:
  14440. return this._gl.POINTS;
  14441. case BABYLON.Material.LineListDrawMode:
  14442. return this._gl.LINES;
  14443. case BABYLON.Material.LineLoopDrawMode:
  14444. return this._gl.LINE_LOOP;
  14445. case BABYLON.Material.LineStripDrawMode:
  14446. return this._gl.LINE_STRIP;
  14447. case BABYLON.Material.TriangleStripDrawMode:
  14448. return this._gl.TRIANGLE_STRIP;
  14449. case BABYLON.Material.TriangleFanDrawMode:
  14450. return this._gl.TRIANGLE_FAN;
  14451. default:
  14452. return this._gl.TRIANGLES;
  14453. }
  14454. };
  14455. // Shaders
  14456. /** @hidden */
  14457. Engine.prototype._releaseEffect = function (effect) {
  14458. if (this._compiledEffects[effect._key]) {
  14459. delete this._compiledEffects[effect._key];
  14460. this._deleteProgram(effect.getProgram());
  14461. }
  14462. };
  14463. /** @hidden */
  14464. Engine.prototype._deleteProgram = function (program) {
  14465. if (program) {
  14466. program.__SPECTOR_rebuildProgram = null;
  14467. if (program.transformFeedback) {
  14468. this.deleteTransformFeedback(program.transformFeedback);
  14469. program.transformFeedback = null;
  14470. }
  14471. this._gl.deleteProgram(program);
  14472. }
  14473. };
  14474. /**
  14475. * Create a new effect (used to store vertex/fragment shaders)
  14476. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14477. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14478. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14479. * @param samplers defines an array of string used to represent textures
  14480. * @param defines defines the string containing the defines to use to compile the shaders
  14481. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14482. * @param onCompiled defines a function to call when the effect creation is successful
  14483. * @param onError defines a function to call when the effect creation has failed
  14484. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14485. * @returns the new Effect
  14486. */
  14487. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14488. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14489. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14490. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14491. if (this._compiledEffects[name]) {
  14492. var compiledEffect = this._compiledEffects[name];
  14493. if (onCompiled && compiledEffect.isReady()) {
  14494. onCompiled(compiledEffect);
  14495. }
  14496. return compiledEffect;
  14497. }
  14498. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14499. effect._key = name;
  14500. this._compiledEffects[name] = effect;
  14501. return effect;
  14502. };
  14503. Engine.prototype._compileShader = function (source, type, defines, shaderVersion) {
  14504. return this._compileRawShader(shaderVersion + (defines ? defines + "\n" : "") + source, type);
  14505. };
  14506. ;
  14507. Engine.prototype._compileRawShader = function (source, type) {
  14508. var gl = this._gl;
  14509. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  14510. gl.shaderSource(shader, source);
  14511. gl.compileShader(shader);
  14512. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  14513. var log = gl.getShaderInfoLog(shader);
  14514. if (log) {
  14515. throw new Error(log);
  14516. }
  14517. }
  14518. if (!shader) {
  14519. throw new Error("Something went wrong while compile the shader.");
  14520. }
  14521. return shader;
  14522. };
  14523. ;
  14524. /**
  14525. * Directly creates a webGL program
  14526. * @param vertexCode defines the vertex shader code to use
  14527. * @param fragmentCode defines the fragment shader code to use
  14528. * @param context defines the webGL context to use (if not set, the current one will be used)
  14529. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14530. * @returns the new webGL program
  14531. */
  14532. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14533. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14534. context = context || this._gl;
  14535. var vertexShader = this._compileRawShader(vertexCode, "vertex");
  14536. var fragmentShader = this._compileRawShader(fragmentCode, "fragment");
  14537. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14538. };
  14539. /**
  14540. * Creates a webGL program
  14541. * @param vertexCode defines the vertex shader code to use
  14542. * @param fragmentCode defines the fragment shader code to use
  14543. * @param defines defines the string containing the defines to use to compile the shaders
  14544. * @param context defines the webGL context to use (if not set, the current one will be used)
  14545. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14546. * @returns the new webGL program
  14547. */
  14548. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14549. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14550. context = context || this._gl;
  14551. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14552. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14553. var vertexShader = this._compileShader(vertexCode, "vertex", defines, shaderVersion);
  14554. var fragmentShader = this._compileShader(fragmentCode, "fragment", defines, shaderVersion);
  14555. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14556. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14557. return program;
  14558. };
  14559. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14560. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14561. var shaderProgram = context.createProgram();
  14562. if (!shaderProgram) {
  14563. throw new Error("Unable to create program");
  14564. }
  14565. context.attachShader(shaderProgram, vertexShader);
  14566. context.attachShader(shaderProgram, fragmentShader);
  14567. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14568. var transformFeedback = this.createTransformFeedback();
  14569. this.bindTransformFeedback(transformFeedback);
  14570. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14571. shaderProgram.transformFeedback = transformFeedback;
  14572. }
  14573. context.linkProgram(shaderProgram);
  14574. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14575. this.bindTransformFeedback(null);
  14576. }
  14577. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14578. if (!linked) {
  14579. var error = context.getProgramInfoLog(shaderProgram);
  14580. if (error) {
  14581. throw new Error(error);
  14582. }
  14583. }
  14584. if (this.validateShaderPrograms) {
  14585. context.validateProgram(shaderProgram);
  14586. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14587. if (!validated) {
  14588. var error = context.getProgramInfoLog(shaderProgram);
  14589. if (error) {
  14590. throw new Error(error);
  14591. }
  14592. }
  14593. }
  14594. context.deleteShader(vertexShader);
  14595. context.deleteShader(fragmentShader);
  14596. return shaderProgram;
  14597. };
  14598. /**
  14599. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14600. * @param shaderProgram defines the webGL program to use
  14601. * @param uniformsNames defines the list of uniform names
  14602. * @returns an array of webGL uniform locations
  14603. */
  14604. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14605. var results = new Array();
  14606. for (var index = 0; index < uniformsNames.length; index++) {
  14607. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14608. }
  14609. return results;
  14610. };
  14611. /**
  14612. * Gets the lsit of active attributes for a given webGL program
  14613. * @param shaderProgram defines the webGL program to use
  14614. * @param attributesNames defines the list of attribute names to get
  14615. * @returns an array of indices indicating the offset of each attribute
  14616. */
  14617. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14618. var results = [];
  14619. for (var index = 0; index < attributesNames.length; index++) {
  14620. try {
  14621. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14622. }
  14623. catch (e) {
  14624. results.push(-1);
  14625. }
  14626. }
  14627. return results;
  14628. };
  14629. /**
  14630. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14631. * @param effect defines the effect to activate
  14632. */
  14633. Engine.prototype.enableEffect = function (effect) {
  14634. if (!effect || effect === this._currentEffect) {
  14635. return;
  14636. }
  14637. // Use program
  14638. this.bindSamplers(effect);
  14639. this._currentEffect = effect;
  14640. if (effect.onBind) {
  14641. effect.onBind(effect);
  14642. }
  14643. if (effect._onBindObservable) {
  14644. effect._onBindObservable.notifyObservers(effect);
  14645. }
  14646. };
  14647. /**
  14648. * Set the value of an uniform to an array of int32
  14649. * @param uniform defines the webGL uniform location where to store the value
  14650. * @param array defines the array of int32 to store
  14651. */
  14652. Engine.prototype.setIntArray = function (uniform, array) {
  14653. if (!uniform)
  14654. return;
  14655. this._gl.uniform1iv(uniform, array);
  14656. };
  14657. /**
  14658. * Set the value of an uniform to an array of int32 (stored as vec2)
  14659. * @param uniform defines the webGL uniform location where to store the value
  14660. * @param array defines the array of int32 to store
  14661. */
  14662. Engine.prototype.setIntArray2 = function (uniform, array) {
  14663. if (!uniform || array.length % 2 !== 0)
  14664. return;
  14665. this._gl.uniform2iv(uniform, array);
  14666. };
  14667. /**
  14668. * Set the value of an uniform to an array of int32 (stored as vec3)
  14669. * @param uniform defines the webGL uniform location where to store the value
  14670. * @param array defines the array of int32 to store
  14671. */
  14672. Engine.prototype.setIntArray3 = function (uniform, array) {
  14673. if (!uniform || array.length % 3 !== 0)
  14674. return;
  14675. this._gl.uniform3iv(uniform, array);
  14676. };
  14677. /**
  14678. * Set the value of an uniform to an array of int32 (stored as vec4)
  14679. * @param uniform defines the webGL uniform location where to store the value
  14680. * @param array defines the array of int32 to store
  14681. */
  14682. Engine.prototype.setIntArray4 = function (uniform, array) {
  14683. if (!uniform || array.length % 4 !== 0)
  14684. return;
  14685. this._gl.uniform4iv(uniform, array);
  14686. };
  14687. /**
  14688. * Set the value of an uniform to an array of float32
  14689. * @param uniform defines the webGL uniform location where to store the value
  14690. * @param array defines the array of float32 to store
  14691. */
  14692. Engine.prototype.setFloatArray = function (uniform, array) {
  14693. if (!uniform)
  14694. return;
  14695. this._gl.uniform1fv(uniform, array);
  14696. };
  14697. /**
  14698. * Set the value of an uniform to an array of float32 (stored as vec2)
  14699. * @param uniform defines the webGL uniform location where to store the value
  14700. * @param array defines the array of float32 to store
  14701. */
  14702. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14703. if (!uniform || array.length % 2 !== 0)
  14704. return;
  14705. this._gl.uniform2fv(uniform, array);
  14706. };
  14707. /**
  14708. * Set the value of an uniform to an array of float32 (stored as vec3)
  14709. * @param uniform defines the webGL uniform location where to store the value
  14710. * @param array defines the array of float32 to store
  14711. */
  14712. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14713. if (!uniform || array.length % 3 !== 0)
  14714. return;
  14715. this._gl.uniform3fv(uniform, array);
  14716. };
  14717. /**
  14718. * Set the value of an uniform to an array of float32 (stored as vec4)
  14719. * @param uniform defines the webGL uniform location where to store the value
  14720. * @param array defines the array of float32 to store
  14721. */
  14722. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14723. if (!uniform || array.length % 4 !== 0)
  14724. return;
  14725. this._gl.uniform4fv(uniform, array);
  14726. };
  14727. /**
  14728. * Set the value of an uniform to an array of number
  14729. * @param uniform defines the webGL uniform location where to store the value
  14730. * @param array defines the array of number to store
  14731. */
  14732. Engine.prototype.setArray = function (uniform, array) {
  14733. if (!uniform)
  14734. return;
  14735. this._gl.uniform1fv(uniform, array);
  14736. };
  14737. /**
  14738. * Set the value of an uniform to an array of number (stored as vec2)
  14739. * @param uniform defines the webGL uniform location where to store the value
  14740. * @param array defines the array of number to store
  14741. */
  14742. Engine.prototype.setArray2 = function (uniform, array) {
  14743. if (!uniform || array.length % 2 !== 0)
  14744. return;
  14745. this._gl.uniform2fv(uniform, array);
  14746. };
  14747. /**
  14748. * Set the value of an uniform to an array of number (stored as vec3)
  14749. * @param uniform defines the webGL uniform location where to store the value
  14750. * @param array defines the array of number to store
  14751. */
  14752. Engine.prototype.setArray3 = function (uniform, array) {
  14753. if (!uniform || array.length % 3 !== 0)
  14754. return;
  14755. this._gl.uniform3fv(uniform, array);
  14756. };
  14757. /**
  14758. * Set the value of an uniform to an array of number (stored as vec4)
  14759. * @param uniform defines the webGL uniform location where to store the value
  14760. * @param array defines the array of number to store
  14761. */
  14762. Engine.prototype.setArray4 = function (uniform, array) {
  14763. if (!uniform || array.length % 4 !== 0)
  14764. return;
  14765. this._gl.uniform4fv(uniform, array);
  14766. };
  14767. /**
  14768. * Set the value of an uniform to an array of float32 (stored as matrices)
  14769. * @param uniform defines the webGL uniform location where to store the value
  14770. * @param matrices defines the array of float32 to store
  14771. */
  14772. Engine.prototype.setMatrices = function (uniform, matrices) {
  14773. if (!uniform)
  14774. return;
  14775. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14776. };
  14777. /**
  14778. * Set the value of an uniform to a matrix
  14779. * @param uniform defines the webGL uniform location where to store the value
  14780. * @param matrix defines the matrix to store
  14781. */
  14782. Engine.prototype.setMatrix = function (uniform, matrix) {
  14783. if (!uniform)
  14784. return;
  14785. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14786. };
  14787. /**
  14788. * Set the value of an uniform to a matrix (3x3)
  14789. * @param uniform defines the webGL uniform location where to store the value
  14790. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14791. */
  14792. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14793. if (!uniform)
  14794. return;
  14795. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14796. };
  14797. /**
  14798. * Set the value of an uniform to a matrix (2x2)
  14799. * @param uniform defines the webGL uniform location where to store the value
  14800. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14801. */
  14802. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14803. if (!uniform)
  14804. return;
  14805. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14806. };
  14807. /**
  14808. * Set the value of an uniform to a number (int)
  14809. * @param uniform defines the webGL uniform location where to store the value
  14810. * @param value defines the int number to store
  14811. */
  14812. Engine.prototype.setInt = function (uniform, value) {
  14813. if (!uniform)
  14814. return;
  14815. this._gl.uniform1i(uniform, value);
  14816. };
  14817. /**
  14818. * Set the value of an uniform to a number (float)
  14819. * @param uniform defines the webGL uniform location where to store the value
  14820. * @param value defines the float number to store
  14821. */
  14822. Engine.prototype.setFloat = function (uniform, value) {
  14823. if (!uniform)
  14824. return;
  14825. this._gl.uniform1f(uniform, value);
  14826. };
  14827. /**
  14828. * Set the value of an uniform to a vec2
  14829. * @param uniform defines the webGL uniform location where to store the value
  14830. * @param x defines the 1st component of the value
  14831. * @param y defines the 2nd component of the value
  14832. */
  14833. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14834. if (!uniform)
  14835. return;
  14836. this._gl.uniform2f(uniform, x, y);
  14837. };
  14838. /**
  14839. * Set the value of an uniform to a vec3
  14840. * @param uniform defines the webGL uniform location where to store the value
  14841. * @param x defines the 1st component of the value
  14842. * @param y defines the 2nd component of the value
  14843. * @param z defines the 3rd component of the value
  14844. */
  14845. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14846. if (!uniform)
  14847. return;
  14848. this._gl.uniform3f(uniform, x, y, z);
  14849. };
  14850. /**
  14851. * Set the value of an uniform to a boolean
  14852. * @param uniform defines the webGL uniform location where to store the value
  14853. * @param bool defines the boolean to store
  14854. */
  14855. Engine.prototype.setBool = function (uniform, bool) {
  14856. if (!uniform)
  14857. return;
  14858. this._gl.uniform1i(uniform, bool);
  14859. };
  14860. /**
  14861. * Set the value of an uniform to a vec4
  14862. * @param uniform defines the webGL uniform location where to store the value
  14863. * @param x defines the 1st component of the value
  14864. * @param y defines the 2nd component of the value
  14865. * @param z defines the 3rd component of the value
  14866. * @param w defines the 4th component of the value
  14867. */
  14868. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14869. if (!uniform)
  14870. return;
  14871. this._gl.uniform4f(uniform, x, y, z, w);
  14872. };
  14873. /**
  14874. * Set the value of an uniform to a Color3
  14875. * @param uniform defines the webGL uniform location where to store the value
  14876. * @param color3 defines the color to store
  14877. */
  14878. Engine.prototype.setColor3 = function (uniform, color3) {
  14879. if (!uniform)
  14880. return;
  14881. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14882. };
  14883. /**
  14884. * Set the value of an uniform to a Color3 and an alpha value
  14885. * @param uniform defines the webGL uniform location where to store the value
  14886. * @param color3 defines the color to store
  14887. * @param alpha defines the alpha component to store
  14888. */
  14889. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14890. if (!uniform)
  14891. return;
  14892. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14893. };
  14894. /**
  14895. * Sets a Color4 on a uniform variable
  14896. * @param uniform defines the uniform location
  14897. * @param color4 defines the value to be set
  14898. */
  14899. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14900. if (!uniform)
  14901. return;
  14902. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14903. };
  14904. // States
  14905. /**
  14906. * Set various states to the webGL context
  14907. * @param culling defines backface culling state
  14908. * @param zOffset defines the value to apply to zOffset (0 by default)
  14909. * @param force defines if states must be applied even if cache is up to date
  14910. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14911. */
  14912. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14913. if (zOffset === void 0) { zOffset = 0; }
  14914. if (reverseSide === void 0) { reverseSide = false; }
  14915. // Culling
  14916. if (this._depthCullingState.cull !== culling || force) {
  14917. this._depthCullingState.cull = culling;
  14918. }
  14919. // Cull face
  14920. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14921. if (this._depthCullingState.cullFace !== cullFace || force) {
  14922. this._depthCullingState.cullFace = cullFace;
  14923. }
  14924. // Z offset
  14925. this.setZOffset(zOffset);
  14926. // Front face
  14927. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14928. if (this._depthCullingState.frontFace !== frontFace || force) {
  14929. this._depthCullingState.frontFace = frontFace;
  14930. }
  14931. };
  14932. /**
  14933. * Set the z offset to apply to current rendering
  14934. * @param value defines the offset to apply
  14935. */
  14936. Engine.prototype.setZOffset = function (value) {
  14937. this._depthCullingState.zOffset = value;
  14938. };
  14939. /**
  14940. * Gets the current value of the zOffset
  14941. * @returns the current zOffset state
  14942. */
  14943. Engine.prototype.getZOffset = function () {
  14944. return this._depthCullingState.zOffset;
  14945. };
  14946. /**
  14947. * Enable or disable depth buffering
  14948. * @param enable defines the state to set
  14949. */
  14950. Engine.prototype.setDepthBuffer = function (enable) {
  14951. this._depthCullingState.depthTest = enable;
  14952. };
  14953. /**
  14954. * Gets a boolean indicating if depth writing is enabled
  14955. * @returns the current depth writing state
  14956. */
  14957. Engine.prototype.getDepthWrite = function () {
  14958. return this._depthCullingState.depthMask;
  14959. };
  14960. /**
  14961. * Enable or disable depth writing
  14962. * @param enable defines the state to set
  14963. */
  14964. Engine.prototype.setDepthWrite = function (enable) {
  14965. this._depthCullingState.depthMask = enable;
  14966. };
  14967. /**
  14968. * Enable or disable color writing
  14969. * @param enable defines the state to set
  14970. */
  14971. Engine.prototype.setColorWrite = function (enable) {
  14972. this._gl.colorMask(enable, enable, enable, enable);
  14973. this._colorWrite = enable;
  14974. };
  14975. /**
  14976. * Gets a boolean indicating if color writing is enabled
  14977. * @returns the current color writing state
  14978. */
  14979. Engine.prototype.getColorWrite = function () {
  14980. return this._colorWrite;
  14981. };
  14982. /**
  14983. * Sets alpha constants used by some alpha blending modes
  14984. * @param r defines the red component
  14985. * @param g defines the green component
  14986. * @param b defines the blue component
  14987. * @param a defines the alpha component
  14988. */
  14989. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14990. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14991. };
  14992. /**
  14993. * Sets the current alpha mode
  14994. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14995. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14996. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14997. */
  14998. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14999. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  15000. if (this._alphaMode === mode) {
  15001. return;
  15002. }
  15003. switch (mode) {
  15004. case Engine.ALPHA_DISABLE:
  15005. this._alphaState.alphaBlend = false;
  15006. break;
  15007. case Engine.ALPHA_PREMULTIPLIED:
  15008. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15009. this._alphaState.alphaBlend = true;
  15010. break;
  15011. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  15012. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15013. this._alphaState.alphaBlend = true;
  15014. break;
  15015. case Engine.ALPHA_COMBINE:
  15016. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  15017. this._alphaState.alphaBlend = true;
  15018. break;
  15019. case Engine.ALPHA_ONEONE:
  15020. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15021. this._alphaState.alphaBlend = true;
  15022. break;
  15023. case Engine.ALPHA_ADD:
  15024. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  15025. this._alphaState.alphaBlend = true;
  15026. break;
  15027. case Engine.ALPHA_SUBTRACT:
  15028. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15029. this._alphaState.alphaBlend = true;
  15030. break;
  15031. case Engine.ALPHA_MULTIPLY:
  15032. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  15033. this._alphaState.alphaBlend = true;
  15034. break;
  15035. case Engine.ALPHA_MAXIMIZED:
  15036. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  15037. this._alphaState.alphaBlend = true;
  15038. break;
  15039. case Engine.ALPHA_INTERPOLATE:
  15040. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  15041. this._alphaState.alphaBlend = true;
  15042. break;
  15043. case Engine.ALPHA_SCREENMODE:
  15044. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  15045. this._alphaState.alphaBlend = true;
  15046. break;
  15047. }
  15048. if (!noDepthWriteChange) {
  15049. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  15050. }
  15051. this._alphaMode = mode;
  15052. };
  15053. /**
  15054. * Gets the current alpha mode
  15055. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  15056. * @returns the current alpha mode
  15057. */
  15058. Engine.prototype.getAlphaMode = function () {
  15059. return this._alphaMode;
  15060. };
  15061. // Textures
  15062. /**
  15063. * Clears the list of texture accessible through engine.
  15064. * This can help preventing texture load conflict due to name collision.
  15065. */
  15066. Engine.prototype.clearInternalTexturesCache = function () {
  15067. this._internalTexturesCache = [];
  15068. };
  15069. /**
  15070. * Force the entire cache to be cleared
  15071. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  15072. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  15073. */
  15074. Engine.prototype.wipeCaches = function (bruteForce) {
  15075. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  15076. return;
  15077. }
  15078. this._currentEffect = null;
  15079. this._viewportCached.x = 0;
  15080. this._viewportCached.y = 0;
  15081. this._viewportCached.z = 0;
  15082. this._viewportCached.w = 0;
  15083. if (bruteForce) {
  15084. this.resetTextureCache();
  15085. this._currentProgram = null;
  15086. this._stencilState.reset();
  15087. this._depthCullingState.reset();
  15088. this.setDepthFunctionToLessOrEqual();
  15089. this._alphaState.reset();
  15090. this._unpackFlipYCached = null;
  15091. }
  15092. this._resetVertexBufferBinding();
  15093. this._cachedIndexBuffer = null;
  15094. this._cachedEffectForVertexBuffers = null;
  15095. this._unbindVertexArrayObject();
  15096. this.bindIndexBuffer(null);
  15097. };
  15098. /**
  15099. * Set the compressed texture format to use, based on the formats you have, and the formats
  15100. * supported by the hardware / browser.
  15101. *
  15102. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  15103. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  15104. * to API arguments needed to compressed textures. This puts the burden on the container
  15105. * generator to house the arcane code for determining these for current & future formats.
  15106. *
  15107. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  15108. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  15109. *
  15110. * Note: The result of this call is not taken into account when a texture is base64.
  15111. *
  15112. * @param formatsAvailable defines the list of those format families you have created
  15113. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  15114. *
  15115. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  15116. * @returns The extension selected.
  15117. */
  15118. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  15119. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  15120. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  15121. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  15122. return this._textureFormatInUse = this._texturesSupported[i];
  15123. }
  15124. }
  15125. }
  15126. // actively set format to nothing, to allow this to be called more than once
  15127. // and possibly fail the 2nd time
  15128. this._textureFormatInUse = null;
  15129. return null;
  15130. };
  15131. Engine.prototype._getSamplingParameters = function (samplingMode, generateMipMaps) {
  15132. var gl = this._gl;
  15133. var magFilter = gl.NEAREST;
  15134. var minFilter = gl.NEAREST;
  15135. switch (samplingMode) {
  15136. case Engine.TEXTURE_BILINEAR_SAMPLINGMODE:
  15137. magFilter = gl.LINEAR;
  15138. if (generateMipMaps) {
  15139. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15140. }
  15141. else {
  15142. minFilter = gl.LINEAR;
  15143. }
  15144. break;
  15145. case Engine.TEXTURE_TRILINEAR_SAMPLINGMODE:
  15146. magFilter = gl.LINEAR;
  15147. if (generateMipMaps) {
  15148. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15149. }
  15150. else {
  15151. minFilter = gl.LINEAR;
  15152. }
  15153. break;
  15154. case Engine.TEXTURE_NEAREST_SAMPLINGMODE:
  15155. magFilter = gl.NEAREST;
  15156. if (generateMipMaps) {
  15157. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15158. }
  15159. else {
  15160. minFilter = gl.NEAREST;
  15161. }
  15162. break;
  15163. case Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST:
  15164. magFilter = gl.NEAREST;
  15165. if (generateMipMaps) {
  15166. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15167. }
  15168. else {
  15169. minFilter = gl.NEAREST;
  15170. }
  15171. break;
  15172. case Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST:
  15173. magFilter = gl.NEAREST;
  15174. if (generateMipMaps) {
  15175. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  15176. }
  15177. else {
  15178. minFilter = gl.LINEAR;
  15179. }
  15180. break;
  15181. case Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR:
  15182. magFilter = gl.NEAREST;
  15183. if (generateMipMaps) {
  15184. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  15185. }
  15186. else {
  15187. minFilter = gl.LINEAR;
  15188. }
  15189. break;
  15190. case Engine.TEXTURE_NEAREST_LINEAR:
  15191. magFilter = gl.NEAREST;
  15192. minFilter = gl.LINEAR;
  15193. break;
  15194. case Engine.TEXTURE_NEAREST_NEAREST:
  15195. magFilter = gl.NEAREST;
  15196. minFilter = gl.NEAREST;
  15197. break;
  15198. case Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST:
  15199. magFilter = gl.LINEAR;
  15200. if (generateMipMaps) {
  15201. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  15202. }
  15203. else {
  15204. minFilter = gl.NEAREST;
  15205. }
  15206. break;
  15207. case Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR:
  15208. magFilter = gl.LINEAR;
  15209. if (generateMipMaps) {
  15210. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  15211. }
  15212. else {
  15213. minFilter = gl.NEAREST;
  15214. }
  15215. break;
  15216. case Engine.TEXTURE_LINEAR_LINEAR:
  15217. magFilter = gl.LINEAR;
  15218. minFilter = gl.LINEAR;
  15219. break;
  15220. case Engine.TEXTURE_LINEAR_NEAREST:
  15221. magFilter = gl.LINEAR;
  15222. minFilter = gl.NEAREST;
  15223. break;
  15224. }
  15225. return {
  15226. min: minFilter,
  15227. mag: magFilter
  15228. };
  15229. };
  15230. Engine.prototype._partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  15231. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  15232. var img;
  15233. var onload = function () {
  15234. loadedImages[index] = img;
  15235. loadedImages._internalCount++;
  15236. if (scene) {
  15237. scene._removePendingData(img);
  15238. }
  15239. if (loadedImages._internalCount === 6) {
  15240. onfinish(loadedImages);
  15241. }
  15242. };
  15243. var onerror = function (message, exception) {
  15244. if (scene) {
  15245. scene._removePendingData(img);
  15246. }
  15247. if (onErrorCallBack) {
  15248. onErrorCallBack(message, exception);
  15249. }
  15250. };
  15251. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  15252. if (scene) {
  15253. scene._addPendingData(img);
  15254. }
  15255. };
  15256. Engine.prototype._cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  15257. if (onError === void 0) { onError = null; }
  15258. var loadedImages = [];
  15259. loadedImages._internalCount = 0;
  15260. for (var index = 0; index < 6; index++) {
  15261. this._partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  15262. }
  15263. };
  15264. ;
  15265. /** @hidden */
  15266. Engine.prototype._createTexture = function () {
  15267. var texture = this._gl.createTexture();
  15268. if (!texture) {
  15269. throw new Error("Unable to create texture");
  15270. }
  15271. return texture;
  15272. };
  15273. /**
  15274. * Usually called from BABYLON.Texture.ts.
  15275. * Passed information to create a WebGLTexture
  15276. * @param urlArg defines a value which contains one of the following:
  15277. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  15278. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  15279. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  15280. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  15281. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  15282. * @param scene needed for loading to the correct scene
  15283. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  15284. * @param onLoad optional callback to be called upon successful completion
  15285. * @param onError optional callback to be called upon failure
  15286. * @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
  15287. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  15288. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  15289. * @param forcedExtension defines the extension to use to pick the right loader
  15290. * @returns a InternalTexture for assignment back into BABYLON.Texture
  15291. */
  15292. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format, forcedExtension) {
  15293. var _this = this;
  15294. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  15295. if (onLoad === void 0) { onLoad = null; }
  15296. if (onError === void 0) { onError = null; }
  15297. if (buffer === void 0) { buffer = null; }
  15298. if (fallback === void 0) { fallback = null; }
  15299. if (format === void 0) { format = null; }
  15300. if (forcedExtension === void 0) { forcedExtension = null; }
  15301. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  15302. var fromData = url.substr(0, 5) === "data:";
  15303. var fromBlob = url.substr(0, 5) === "blob:";
  15304. var isBase64 = fromData && url.indexOf(";base64,") !== -1;
  15305. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  15306. // establish the file extension, if possible
  15307. var lastDot = url.lastIndexOf('.');
  15308. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? url.substring(lastDot).toLowerCase() : "");
  15309. var loader = null;
  15310. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  15311. var availableLoader = _a[_i];
  15312. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, isBase64, buffer ? true : false)) {
  15313. loader = availableLoader;
  15314. break;
  15315. }
  15316. }
  15317. if (loader) {
  15318. url = loader.transformUrl(url, this._textureFormatInUse);
  15319. }
  15320. if (scene) {
  15321. scene._addPendingData(texture);
  15322. }
  15323. texture.url = url;
  15324. texture.generateMipMaps = !noMipmap;
  15325. texture.samplingMode = samplingMode;
  15326. texture.invertY = invertY;
  15327. if (!this._doNotHandleContextLost) {
  15328. // Keep a link to the buffer only if we plan to handle context lost
  15329. texture._buffer = buffer;
  15330. }
  15331. var onLoadObserver = null;
  15332. if (onLoad && !fallback) {
  15333. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  15334. }
  15335. if (!fallback)
  15336. this._internalTexturesCache.push(texture);
  15337. var onInternalError = function (message, exception) {
  15338. if (scene) {
  15339. scene._removePendingData(texture);
  15340. }
  15341. var customFallback = false;
  15342. if (loader) {
  15343. var fallbackUrl = loader.getFallbackTextureUrl(url, _this._textureFormatInUse);
  15344. if (fallbackUrl) {
  15345. // Add Back
  15346. customFallback = true;
  15347. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15348. }
  15349. }
  15350. if (!customFallback) {
  15351. if (onLoadObserver) {
  15352. texture.onLoadedObservable.remove(onLoadObserver);
  15353. }
  15354. if (BABYLON.Tools.UseFallbackTexture) {
  15355. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  15356. }
  15357. }
  15358. if (onError) {
  15359. onError(message || "Unknown error", exception);
  15360. }
  15361. };
  15362. // processing for non-image formats
  15363. if (loader) {
  15364. var callback = function (data) {
  15365. loader.loadData(data, texture, function (width, height, loadMipmap, isCompressed, done) {
  15366. _this._prepareWebGLTexture(texture, scene, width, height, invertY, !loadMipmap, isCompressed, function () {
  15367. done();
  15368. return false;
  15369. }, samplingMode);
  15370. });
  15371. };
  15372. if (!buffer) {
  15373. this._loadFile(url, callback, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  15374. onInternalError("Unable to load " + (request ? request.responseURL : url, exception));
  15375. });
  15376. }
  15377. else {
  15378. callback(buffer);
  15379. }
  15380. }
  15381. else {
  15382. var onload = function (img) {
  15383. if (fromBlob && !_this._doNotHandleContextLost) {
  15384. // We need to store the image if we need to rebuild the texture
  15385. // in case of a webgl context lost
  15386. texture._buffer = img;
  15387. }
  15388. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  15389. var gl = _this._gl;
  15390. var isPot = (img.width === potWidth && img.height === potHeight);
  15391. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  15392. if (isPot) {
  15393. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15394. return false;
  15395. }
  15396. var maxTextureSize = _this._caps.maxTextureSize;
  15397. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  15398. _this._prepareWorkingCanvas();
  15399. if (!_this._workingCanvas || !_this._workingContext) {
  15400. return false;
  15401. }
  15402. _this._workingCanvas.width = potWidth;
  15403. _this._workingCanvas.height = potHeight;
  15404. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  15405. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15406. texture.width = potWidth;
  15407. texture.height = potHeight;
  15408. return false;
  15409. }
  15410. else {
  15411. // Using shaders when possible to rescale because canvas.drawImage is lossy
  15412. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15413. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  15414. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  15415. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15416. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15417. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15418. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15419. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  15420. _this._releaseTexture(source_1);
  15421. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15422. continuationCallback();
  15423. });
  15424. }
  15425. return true;
  15426. }, samplingMode);
  15427. };
  15428. if (!fromData || isBase64) {
  15429. if (buffer instanceof HTMLImageElement) {
  15430. onload(buffer);
  15431. }
  15432. else {
  15433. BABYLON.Tools.LoadImage(url, onload, onInternalError, scene ? scene.database : null);
  15434. }
  15435. }
  15436. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  15437. BABYLON.Tools.LoadImage(buffer, onload, onInternalError, scene ? scene.database : null);
  15438. }
  15439. else {
  15440. onload(buffer);
  15441. }
  15442. }
  15443. return texture;
  15444. };
  15445. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  15446. var _this = this;
  15447. var rtt = this.createRenderTargetTexture({
  15448. width: destination.width,
  15449. height: destination.height,
  15450. }, {
  15451. generateMipMaps: false,
  15452. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  15453. samplingMode: Engine.TEXTURE_BILINEAR_SAMPLINGMODE,
  15454. generateDepthBuffer: false,
  15455. generateStencilBuffer: false
  15456. });
  15457. if (!this._rescalePostProcess) {
  15458. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, Engine.TEXTURE_BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  15459. }
  15460. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  15461. _this._rescalePostProcess.onApply = function (effect) {
  15462. effect._bindTexture("textureSampler", source);
  15463. };
  15464. var hostingScene = scene;
  15465. if (!hostingScene) {
  15466. hostingScene = _this.scenes[_this.scenes.length - 1];
  15467. }
  15468. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  15469. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  15470. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  15471. _this.unBindFramebuffer(rtt);
  15472. _this._releaseTexture(rtt);
  15473. if (onComplete) {
  15474. onComplete();
  15475. }
  15476. });
  15477. };
  15478. /**
  15479. * Update a raw texture
  15480. * @param texture defines the texture to update
  15481. * @param data defines the data to store in the texture
  15482. * @param format defines the format of the data
  15483. * @param invertY defines if data must be stored with Y axis inverted
  15484. * @param compression defines the compression used (null by default)
  15485. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15486. */
  15487. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  15488. if (compression === void 0) { compression = null; }
  15489. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15490. if (!texture) {
  15491. return;
  15492. }
  15493. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  15494. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  15495. // babylon's internalFormat but gl's texImage2D format
  15496. var internalFormat = this._getInternalFormat(format);
  15497. var textureType = this._getWebGLTextureType(type);
  15498. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15499. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15500. if (!this._doNotHandleContextLost) {
  15501. texture._bufferView = data;
  15502. texture.format = format;
  15503. texture.type = type;
  15504. texture.invertY = invertY;
  15505. texture._compression = compression;
  15506. }
  15507. if (texture.width % 4 !== 0) {
  15508. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15509. }
  15510. if (compression && data) {
  15511. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15512. }
  15513. else {
  15514. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15515. }
  15516. if (texture.generateMipMaps) {
  15517. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15518. }
  15519. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15520. // this.resetTextureCache();
  15521. texture.isReady = true;
  15522. };
  15523. /**
  15524. * Creates a raw texture
  15525. * @param data defines the data to store in the texture
  15526. * @param width defines the width of the texture
  15527. * @param height defines the height of the texture
  15528. * @param format defines the format of the data
  15529. * @param generateMipMaps defines if the engine should generate the mip levels
  15530. * @param invertY defines if data must be stored with Y axis inverted
  15531. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15532. * @param compression defines the compression used (null by default)
  15533. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15534. * @returns the raw texture inside an InternalTexture
  15535. */
  15536. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15537. if (compression === void 0) { compression = null; }
  15538. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15539. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15540. texture.baseWidth = width;
  15541. texture.baseHeight = height;
  15542. texture.width = width;
  15543. texture.height = height;
  15544. texture.format = format;
  15545. texture.generateMipMaps = generateMipMaps;
  15546. texture.samplingMode = samplingMode;
  15547. texture.invertY = invertY;
  15548. texture._compression = compression;
  15549. texture.type = type;
  15550. if (!this._doNotHandleContextLost) {
  15551. texture._bufferView = data;
  15552. }
  15553. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15554. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15555. // Filters
  15556. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  15557. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15558. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15559. if (generateMipMaps) {
  15560. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15561. }
  15562. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15563. this._internalTexturesCache.push(texture);
  15564. return texture;
  15565. };
  15566. /** @hidden */
  15567. Engine.prototype._unpackFlipY = function (value) {
  15568. if (this._unpackFlipYCached !== value) {
  15569. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15570. if (this.enableUnpackFlipYCached) {
  15571. this._unpackFlipYCached = value;
  15572. }
  15573. }
  15574. };
  15575. /** @hidden */
  15576. Engine.prototype._getUnpackAlignement = function () {
  15577. return this._gl.getParameter(this._gl.UNPACK_ALIGNMENT);
  15578. };
  15579. /**
  15580. * Creates a dynamic texture
  15581. * @param width defines the width of the texture
  15582. * @param height defines the height of the texture
  15583. * @param generateMipMaps defines if the engine should generate the mip levels
  15584. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15585. * @returns the dynamic texture inside an InternalTexture
  15586. */
  15587. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15588. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15589. texture.baseWidth = width;
  15590. texture.baseHeight = height;
  15591. if (generateMipMaps) {
  15592. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15593. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15594. }
  15595. // this.resetTextureCache();
  15596. texture.width = width;
  15597. texture.height = height;
  15598. texture.isReady = false;
  15599. texture.generateMipMaps = generateMipMaps;
  15600. texture.samplingMode = samplingMode;
  15601. this.updateTextureSamplingMode(samplingMode, texture);
  15602. this._internalTexturesCache.push(texture);
  15603. return texture;
  15604. };
  15605. /**
  15606. * Update the sampling mode of a given texture
  15607. * @param samplingMode defines the required sampling mode
  15608. * @param texture defines the texture to update
  15609. */
  15610. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15611. var filters = this._getSamplingParameters(samplingMode, texture.generateMipMaps);
  15612. if (texture.isCube) {
  15613. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15614. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15615. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15616. }
  15617. else if (texture.is3D) {
  15618. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15619. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15620. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15621. }
  15622. else {
  15623. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15624. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15625. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15626. }
  15627. texture.samplingMode = samplingMode;
  15628. };
  15629. /**
  15630. * Update the content of a dynamic texture
  15631. * @param texture defines the texture to update
  15632. * @param canvas defines the canvas containing the source
  15633. * @param invertY defines if data must be stored with Y axis inverted
  15634. * @param premulAlpha defines if alpha is stored as premultiplied
  15635. * @param format defines the format of the data
  15636. */
  15637. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15638. if (premulAlpha === void 0) { premulAlpha = false; }
  15639. if (!texture) {
  15640. return;
  15641. }
  15642. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15643. this._unpackFlipY(invertY);
  15644. if (premulAlpha) {
  15645. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15646. }
  15647. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15648. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15649. if (texture.generateMipMaps) {
  15650. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15651. }
  15652. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15653. if (premulAlpha) {
  15654. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15655. }
  15656. texture.isReady = true;
  15657. };
  15658. /**
  15659. * Update a video texture
  15660. * @param texture defines the texture to update
  15661. * @param video defines the video element to use
  15662. * @param invertY defines if data must be stored with Y axis inverted
  15663. */
  15664. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15665. if (!texture || texture._isDisabled) {
  15666. return;
  15667. }
  15668. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15669. this._unpackFlipY(!invertY); // Video are upside down by default
  15670. try {
  15671. // Testing video texture support
  15672. if (this._videoTextureSupported === undefined) {
  15673. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15674. if (this._gl.getError() !== 0) {
  15675. this._videoTextureSupported = false;
  15676. }
  15677. else {
  15678. this._videoTextureSupported = true;
  15679. }
  15680. }
  15681. // Copy video through the current working canvas if video texture is not supported
  15682. if (!this._videoTextureSupported) {
  15683. if (!texture._workingCanvas) {
  15684. texture._workingCanvas = document.createElement("canvas");
  15685. var context = texture._workingCanvas.getContext("2d");
  15686. if (!context) {
  15687. throw new Error("Unable to get 2d context");
  15688. }
  15689. texture._workingContext = context;
  15690. texture._workingCanvas.width = texture.width;
  15691. texture._workingCanvas.height = texture.height;
  15692. }
  15693. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15694. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15695. }
  15696. else {
  15697. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15698. }
  15699. if (texture.generateMipMaps) {
  15700. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15701. }
  15702. if (!wasPreviouslyBound) {
  15703. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15704. }
  15705. // this.resetTextureCache();
  15706. texture.isReady = true;
  15707. }
  15708. catch (ex) {
  15709. // Something unexpected
  15710. // Let's disable the texture
  15711. texture._isDisabled = true;
  15712. }
  15713. };
  15714. /**
  15715. * Updates a depth texture Comparison Mode and Function.
  15716. * If the comparison Function is equal to 0, the mode will be set to none.
  15717. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15718. * @param texture The texture to set the comparison function for
  15719. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15720. */
  15721. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15722. if (this.webGLVersion === 1) {
  15723. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15724. return;
  15725. }
  15726. var gl = this._gl;
  15727. if (texture.isCube) {
  15728. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15729. if (comparisonFunction === 0) {
  15730. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15731. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15732. }
  15733. else {
  15734. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15735. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15736. }
  15737. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15738. }
  15739. else {
  15740. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15741. if (comparisonFunction === 0) {
  15742. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15743. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15744. }
  15745. else {
  15746. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15747. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15748. }
  15749. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15750. }
  15751. texture._comparisonFunction = comparisonFunction;
  15752. };
  15753. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15754. var width = size.width || size;
  15755. var height = size.height || size;
  15756. internalTexture.baseWidth = width;
  15757. internalTexture.baseHeight = height;
  15758. internalTexture.width = width;
  15759. internalTexture.height = height;
  15760. internalTexture.isReady = true;
  15761. internalTexture.samples = 1;
  15762. internalTexture.generateMipMaps = false;
  15763. internalTexture._generateDepthBuffer = true;
  15764. internalTexture._generateStencilBuffer = generateStencil;
  15765. internalTexture.samplingMode = bilinearFiltering ? Engine.TEXTURE_BILINEAR_SAMPLINGMODE : Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15766. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15767. internalTexture._comparisonFunction = comparisonFunction;
  15768. var gl = this._gl;
  15769. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15770. var samplingParameters = this._getSamplingParameters(internalTexture.samplingMode, false);
  15771. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15772. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15773. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15774. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15775. if (comparisonFunction === 0) {
  15776. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15777. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15778. }
  15779. else {
  15780. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15781. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15782. }
  15783. };
  15784. /**
  15785. * Creates a depth stencil texture.
  15786. * This is only available in WebGL 2 or with the depth texture extension available.
  15787. * @param size The size of face edge in the texture.
  15788. * @param options The options defining the texture.
  15789. * @returns The texture
  15790. */
  15791. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15792. if (options.isCube) {
  15793. var width = size.width || size;
  15794. return this._createDepthStencilCubeTexture(width, options);
  15795. }
  15796. else {
  15797. return this._createDepthStencilTexture(size, options);
  15798. }
  15799. };
  15800. /**
  15801. * Creates a depth stencil texture.
  15802. * This is only available in WebGL 2 or with the depth texture extension available.
  15803. * @param size The size of face edge in the texture.
  15804. * @param options The options defining the texture.
  15805. * @returns The texture
  15806. */
  15807. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15808. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15809. if (!this._caps.depthTextureExtension) {
  15810. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15811. return internalTexture;
  15812. }
  15813. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15814. var gl = this._gl;
  15815. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15816. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15817. if (this.webGLVersion > 1) {
  15818. if (internalOptions.generateStencil) {
  15819. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15820. }
  15821. else {
  15822. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15823. }
  15824. }
  15825. else {
  15826. if (internalOptions.generateStencil) {
  15827. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15828. }
  15829. else {
  15830. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15831. }
  15832. }
  15833. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15834. return internalTexture;
  15835. };
  15836. /**
  15837. * Creates a depth stencil cube texture.
  15838. * This is only available in WebGL 2.
  15839. * @param size The size of face edge in the cube texture.
  15840. * @param options The options defining the cube texture.
  15841. * @returns The cube texture
  15842. */
  15843. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15844. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15845. internalTexture.isCube = true;
  15846. if (this.webGLVersion === 1) {
  15847. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15848. return internalTexture;
  15849. }
  15850. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15851. var gl = this._gl;
  15852. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15853. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15854. // Create the depth/stencil buffer
  15855. for (var face = 0; face < 6; face++) {
  15856. if (internalOptions.generateStencil) {
  15857. 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);
  15858. }
  15859. else {
  15860. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15861. }
  15862. }
  15863. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15864. return internalTexture;
  15865. };
  15866. /**
  15867. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15868. * @param renderTarget The render target to set the frame buffer for
  15869. */
  15870. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15871. // Create the framebuffer
  15872. var internalTexture = renderTarget.getInternalTexture();
  15873. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15874. return;
  15875. }
  15876. var gl = this._gl;
  15877. var depthStencilTexture = renderTarget.depthStencilTexture;
  15878. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15879. if (depthStencilTexture.isCube) {
  15880. if (depthStencilTexture._generateStencilBuffer) {
  15881. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15882. }
  15883. else {
  15884. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15885. }
  15886. }
  15887. else {
  15888. if (depthStencilTexture._generateStencilBuffer) {
  15889. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15890. }
  15891. else {
  15892. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15893. }
  15894. }
  15895. this.bindUnboundFramebuffer(null);
  15896. };
  15897. /**
  15898. * Creates a new render target texture
  15899. * @param size defines the size of the texture
  15900. * @param options defines the options used to create the texture
  15901. * @returns a new render target texture stored in an InternalTexture
  15902. */
  15903. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15904. var fullOptions = new RenderTargetCreationOptions();
  15905. if (options !== undefined && typeof options === "object") {
  15906. fullOptions.generateMipMaps = options.generateMipMaps;
  15907. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15908. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15909. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15910. fullOptions.samplingMode = options.samplingMode === undefined ? Engine.TEXTURE_TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15911. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15912. }
  15913. else {
  15914. fullOptions.generateMipMaps = options;
  15915. fullOptions.generateDepthBuffer = true;
  15916. fullOptions.generateStencilBuffer = false;
  15917. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15918. fullOptions.samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15919. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15920. }
  15921. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15922. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15923. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15924. }
  15925. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15926. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15927. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  15928. }
  15929. var gl = this._gl;
  15930. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15931. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15932. var width = size.width || size;
  15933. var height = size.height || size;
  15934. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false);
  15935. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15936. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15937. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15938. }
  15939. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15940. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15941. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15942. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15943. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15944. // Create the framebuffer
  15945. var currentFrameBuffer = this._currentFramebuffer;
  15946. var framebuffer = gl.createFramebuffer();
  15947. this.bindUnboundFramebuffer(framebuffer);
  15948. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15949. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15950. if (fullOptions.generateMipMaps) {
  15951. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15952. }
  15953. // Unbind
  15954. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15955. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15956. this.bindUnboundFramebuffer(currentFrameBuffer);
  15957. texture._framebuffer = framebuffer;
  15958. texture.baseWidth = width;
  15959. texture.baseHeight = height;
  15960. texture.width = width;
  15961. texture.height = height;
  15962. texture.isReady = true;
  15963. texture.samples = 1;
  15964. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15965. texture.samplingMode = fullOptions.samplingMode;
  15966. texture.type = fullOptions.type;
  15967. texture.format = fullOptions.format;
  15968. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15969. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15970. // this.resetTextureCache();
  15971. this._internalTexturesCache.push(texture);
  15972. return texture;
  15973. };
  15974. /**
  15975. * Create a multi render target texture
  15976. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15977. * @param size defines the size of the texture
  15978. * @param options defines the creation options
  15979. * @returns the cube texture as an InternalTexture
  15980. */
  15981. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15982. var generateMipMaps = false;
  15983. var generateDepthBuffer = true;
  15984. var generateStencilBuffer = false;
  15985. var generateDepthTexture = false;
  15986. var textureCount = 1;
  15987. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15988. var defaultSamplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  15989. var types = new Array();
  15990. var samplingModes = new Array();
  15991. if (options !== undefined) {
  15992. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15993. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15994. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15995. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15996. textureCount = options.textureCount || 1;
  15997. if (options.types) {
  15998. types = options.types;
  15999. }
  16000. if (options.samplingModes) {
  16001. samplingModes = options.samplingModes;
  16002. }
  16003. }
  16004. var gl = this._gl;
  16005. // Create the framebuffer
  16006. var framebuffer = gl.createFramebuffer();
  16007. this.bindUnboundFramebuffer(framebuffer);
  16008. var width = size.width || size;
  16009. var height = size.height || size;
  16010. var textures = [];
  16011. var attachments = [];
  16012. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  16013. for (var i = 0; i < textureCount; i++) {
  16014. var samplingMode = samplingModes[i] || defaultSamplingMode;
  16015. var type = types[i] || defaultType;
  16016. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16017. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16018. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16019. }
  16020. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16021. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16022. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16023. }
  16024. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16025. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16026. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16027. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  16028. }
  16029. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16030. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16031. textures.push(texture);
  16032. attachments.push(attachment);
  16033. gl.activeTexture(gl["TEXTURE" + i]);
  16034. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  16035. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16036. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16037. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16038. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16039. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16040. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16041. if (generateMipMaps) {
  16042. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  16043. }
  16044. // Unbind
  16045. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16046. texture._framebuffer = framebuffer;
  16047. texture._depthStencilBuffer = depthStencilBuffer;
  16048. texture.baseWidth = width;
  16049. texture.baseHeight = height;
  16050. texture.width = width;
  16051. texture.height = height;
  16052. texture.isReady = true;
  16053. texture.samples = 1;
  16054. texture.generateMipMaps = generateMipMaps;
  16055. texture.samplingMode = samplingMode;
  16056. texture.type = type;
  16057. texture._generateDepthBuffer = generateDepthBuffer;
  16058. texture._generateStencilBuffer = generateStencilBuffer;
  16059. texture._attachments = attachments;
  16060. this._internalTexturesCache.push(texture);
  16061. }
  16062. if (generateDepthTexture && this._caps.depthTextureExtension) {
  16063. // Depth texture
  16064. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  16065. gl.activeTexture(gl.TEXTURE0);
  16066. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  16067. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16068. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16069. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16070. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16071. 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);
  16072. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  16073. depthTexture._framebuffer = framebuffer;
  16074. depthTexture.baseWidth = width;
  16075. depthTexture.baseHeight = height;
  16076. depthTexture.width = width;
  16077. depthTexture.height = height;
  16078. depthTexture.isReady = true;
  16079. depthTexture.samples = 1;
  16080. depthTexture.generateMipMaps = generateMipMaps;
  16081. depthTexture.samplingMode = gl.NEAREST;
  16082. depthTexture._generateDepthBuffer = generateDepthBuffer;
  16083. depthTexture._generateStencilBuffer = generateStencilBuffer;
  16084. textures.push(depthTexture);
  16085. this._internalTexturesCache.push(depthTexture);
  16086. }
  16087. gl.drawBuffers(attachments);
  16088. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16089. this.bindUnboundFramebuffer(null);
  16090. this.resetTextureCache();
  16091. return textures;
  16092. };
  16093. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  16094. if (samples === void 0) { samples = 1; }
  16095. var depthStencilBuffer = null;
  16096. var gl = this._gl;
  16097. // Create the depth/stencil buffer
  16098. if (generateStencilBuffer) {
  16099. depthStencilBuffer = gl.createRenderbuffer();
  16100. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16101. if (samples > 1) {
  16102. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  16103. }
  16104. else {
  16105. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  16106. }
  16107. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16108. }
  16109. else if (generateDepthBuffer) {
  16110. depthStencilBuffer = gl.createRenderbuffer();
  16111. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  16112. if (samples > 1) {
  16113. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  16114. }
  16115. else {
  16116. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  16117. }
  16118. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  16119. }
  16120. return depthStencilBuffer;
  16121. };
  16122. /**
  16123. * Updates the sample count of a render target texture
  16124. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16125. * @param texture defines the texture to update
  16126. * @param samples defines the sample count to set
  16127. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16128. */
  16129. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  16130. if (this.webGLVersion < 2 || !texture) {
  16131. return 1;
  16132. }
  16133. if (texture.samples === samples) {
  16134. return samples;
  16135. }
  16136. var gl = this._gl;
  16137. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16138. // Dispose previous render buffers
  16139. if (texture._depthStencilBuffer) {
  16140. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16141. texture._depthStencilBuffer = null;
  16142. }
  16143. if (texture._MSAAFramebuffer) {
  16144. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16145. texture._MSAAFramebuffer = null;
  16146. }
  16147. if (texture._MSAARenderBuffer) {
  16148. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16149. texture._MSAARenderBuffer = null;
  16150. }
  16151. if (samples > 1) {
  16152. var framebuffer = gl.createFramebuffer();
  16153. if (!framebuffer) {
  16154. throw new Error("Unable to create multi sampled framebuffer");
  16155. }
  16156. texture._MSAAFramebuffer = framebuffer;
  16157. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  16158. var colorRenderbuffer = gl.createRenderbuffer();
  16159. if (!colorRenderbuffer) {
  16160. throw new Error("Unable to create multi sampled framebuffer");
  16161. }
  16162. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16163. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16164. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  16165. texture._MSAARenderBuffer = colorRenderbuffer;
  16166. }
  16167. else {
  16168. this.bindUnboundFramebuffer(texture._framebuffer);
  16169. }
  16170. texture.samples = samples;
  16171. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  16172. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16173. this.bindUnboundFramebuffer(null);
  16174. return samples;
  16175. };
  16176. /**
  16177. * Update the sample count for a given multiple render target texture
  16178. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  16179. * @param textures defines the textures to update
  16180. * @param samples defines the sample count to set
  16181. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  16182. */
  16183. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  16184. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  16185. return 1;
  16186. }
  16187. if (textures[0].samples === samples) {
  16188. return samples;
  16189. }
  16190. var gl = this._gl;
  16191. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  16192. // Dispose previous render buffers
  16193. if (textures[0]._depthStencilBuffer) {
  16194. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  16195. textures[0]._depthStencilBuffer = null;
  16196. }
  16197. if (textures[0]._MSAAFramebuffer) {
  16198. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  16199. textures[0]._MSAAFramebuffer = null;
  16200. }
  16201. for (var i = 0; i < textures.length; i++) {
  16202. if (textures[i]._MSAARenderBuffer) {
  16203. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  16204. textures[i]._MSAARenderBuffer = null;
  16205. }
  16206. }
  16207. if (samples > 1) {
  16208. var framebuffer = gl.createFramebuffer();
  16209. if (!framebuffer) {
  16210. throw new Error("Unable to create multi sampled framebuffer");
  16211. }
  16212. this.bindUnboundFramebuffer(framebuffer);
  16213. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  16214. var attachments = [];
  16215. for (var i = 0; i < textures.length; i++) {
  16216. var texture = textures[i];
  16217. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  16218. var colorRenderbuffer = gl.createRenderbuffer();
  16219. if (!colorRenderbuffer) {
  16220. throw new Error("Unable to create multi sampled framebuffer");
  16221. }
  16222. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  16223. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  16224. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  16225. texture._MSAAFramebuffer = framebuffer;
  16226. texture._MSAARenderBuffer = colorRenderbuffer;
  16227. texture.samples = samples;
  16228. texture._depthStencilBuffer = depthStencilBuffer;
  16229. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16230. attachments.push(attachment);
  16231. }
  16232. gl.drawBuffers(attachments);
  16233. }
  16234. else {
  16235. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  16236. }
  16237. this.bindUnboundFramebuffer(null);
  16238. return samples;
  16239. };
  16240. /** @hidden */
  16241. Engine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  16242. if (faceIndex === void 0) { faceIndex = 0; }
  16243. if (lod === void 0) { lod = 0; }
  16244. var gl = this._gl;
  16245. var target = gl.TEXTURE_2D;
  16246. if (texture.isCube) {
  16247. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16248. }
  16249. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  16250. };
  16251. /** @hidden */
  16252. Engine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  16253. if (faceIndex === void 0) { faceIndex = 0; }
  16254. if (lod === void 0) { lod = 0; }
  16255. var gl = this._gl;
  16256. var textureType = this._getWebGLTextureType(texture.type);
  16257. var format = this._getInternalFormat(texture.format);
  16258. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16259. this._unpackFlipY(texture.invertY);
  16260. var target = gl.TEXTURE_2D;
  16261. if (texture.isCube) {
  16262. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16263. }
  16264. var lodMaxWidth = Math.round(BABYLON.Scalar.Log2(texture.width));
  16265. var lodMaxHeight = Math.round(BABYLON.Scalar.Log2(texture.height));
  16266. var width = Math.pow(2, Math.max(lodMaxWidth - lod, 0));
  16267. var height = Math.pow(2, Math.max(lodMaxHeight - lod, 0));
  16268. gl.texImage2D(target, lod, internalFormat, width, height, 0, format, textureType, imageData);
  16269. };
  16270. /** @hidden */
  16271. Engine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  16272. if (faceIndex === void 0) { faceIndex = 0; }
  16273. if (lod === void 0) { lod = 0; }
  16274. var gl = this._gl;
  16275. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16276. this._bindTextureDirectly(bindTarget, texture, true);
  16277. this._uploadDataToTextureDirectly(texture, imageData, faceIndex, lod);
  16278. this._bindTextureDirectly(bindTarget, null, true);
  16279. };
  16280. /** @hidden */
  16281. Engine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  16282. if (faceIndex === void 0) { faceIndex = 0; }
  16283. if (lod === void 0) { lod = 0; }
  16284. var gl = this._gl;
  16285. var textureType = this._getWebGLTextureType(texture.type);
  16286. var format = this._getInternalFormat(texture.format);
  16287. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  16288. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  16289. this._bindTextureDirectly(bindTarget, texture, true);
  16290. this._unpackFlipY(texture.invertY);
  16291. var target = gl.TEXTURE_2D;
  16292. if (texture.isCube) {
  16293. target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  16294. }
  16295. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  16296. this._bindTextureDirectly(bindTarget, null, true);
  16297. };
  16298. /**
  16299. * Creates a new render target cube texture
  16300. * @param size defines the size of the texture
  16301. * @param options defines the options used to create the texture
  16302. * @returns a new render target cube texture stored in an InternalTexture
  16303. */
  16304. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  16305. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: Engine.TEXTURE_TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  16306. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  16307. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  16308. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  16309. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16310. }
  16311. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  16312. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  16313. fullOptions.samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16314. }
  16315. var gl = this._gl;
  16316. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  16317. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16318. var filters = this._getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps);
  16319. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  16320. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  16321. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  16322. }
  16323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16324. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16326. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16327. for (var face = 0; face < 6; face++) {
  16328. 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);
  16329. }
  16330. // Create the framebuffer
  16331. var framebuffer = gl.createFramebuffer();
  16332. this.bindUnboundFramebuffer(framebuffer);
  16333. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  16334. // MipMaps
  16335. if (fullOptions.generateMipMaps) {
  16336. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16337. }
  16338. // Unbind
  16339. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16340. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  16341. this.bindUnboundFramebuffer(null);
  16342. texture._framebuffer = framebuffer;
  16343. texture.width = size;
  16344. texture.height = size;
  16345. texture.isReady = true;
  16346. texture.isCube = true;
  16347. texture.samples = 1;
  16348. texture.generateMipMaps = fullOptions.generateMipMaps;
  16349. texture.samplingMode = fullOptions.samplingMode;
  16350. texture.type = fullOptions.type;
  16351. texture.format = fullOptions.format;
  16352. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  16353. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  16354. this._internalTexturesCache.push(texture);
  16355. return texture;
  16356. };
  16357. /**
  16358. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  16359. * @param rootUrl defines the url where the file to load is located
  16360. * @param scene defines the current scene
  16361. * @param lodScale defines scale to apply to the mip map selection
  16362. * @param lodOffset defines offset to apply to the mip map selection
  16363. * @param onLoad defines an optional callback raised when the texture is loaded
  16364. * @param onError defines an optional callback raised if there is an issue to load the texture
  16365. * @param format defines the format of the data
  16366. * @param forcedExtension defines the extension to use to pick the right loader
  16367. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  16368. * @returns the cube texture as an InternalTexture
  16369. */
  16370. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  16371. var _this = this;
  16372. if (onLoad === void 0) { onLoad = null; }
  16373. if (onError === void 0) { onError = null; }
  16374. if (forcedExtension === void 0) { forcedExtension = null; }
  16375. if (createPolynomials === void 0) { createPolynomials = true; }
  16376. var callback = function (loadData) {
  16377. if (!loadData) {
  16378. if (onLoad) {
  16379. onLoad(null);
  16380. }
  16381. return;
  16382. }
  16383. var texture = loadData.texture;
  16384. if (!createPolynomials) {
  16385. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16386. }
  16387. else if (loadData.info.sphericalPolynomial) {
  16388. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  16389. }
  16390. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  16391. if (_this._caps.textureLOD) {
  16392. // Do not add extra process if texture lod is supported.
  16393. if (onLoad) {
  16394. onLoad(texture);
  16395. }
  16396. return;
  16397. }
  16398. var mipSlices = 3;
  16399. var gl = _this._gl;
  16400. var width = loadData.width;
  16401. if (!width) {
  16402. return;
  16403. }
  16404. var textures = [];
  16405. for (var i = 0; i < mipSlices; i++) {
  16406. //compute LOD from even spacing in smoothness (matching shader calculation)
  16407. var smoothness = i / (mipSlices - 1);
  16408. var roughness = 1 - smoothness;
  16409. var minLODIndex = lodOffset; // roughness = 0
  16410. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  16411. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  16412. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  16413. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  16414. glTextureFromLod.type = texture.type;
  16415. glTextureFromLod.format = texture.format;
  16416. glTextureFromLod.width = Math.pow(2, Math.max(BABYLON.Scalar.Log2(width) - mipmapIndex, 0));
  16417. glTextureFromLod.height = glTextureFromLod.width;
  16418. glTextureFromLod.isCube = true;
  16419. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  16420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16421. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  16422. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16423. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16424. if (loadData.isDDS) {
  16425. var info = loadData.info;
  16426. var data = loadData.data;
  16427. _this._unpackFlipY(info.isCompressed);
  16428. BABYLON.DDSTools.UploadDDSLevels(_this, glTextureFromLod, data, info, true, 6, mipmapIndex);
  16429. }
  16430. else {
  16431. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  16432. }
  16433. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16434. // Wrap in a base texture for easy binding.
  16435. var lodTexture = new BABYLON.BaseTexture(scene);
  16436. lodTexture.isCube = true;
  16437. lodTexture._texture = glTextureFromLod;
  16438. glTextureFromLod.isReady = true;
  16439. textures.push(lodTexture);
  16440. }
  16441. texture._lodTextureHigh = textures[2];
  16442. texture._lodTextureMid = textures[1];
  16443. texture._lodTextureLow = textures[0];
  16444. if (onLoad) {
  16445. onLoad(texture);
  16446. }
  16447. };
  16448. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  16449. };
  16450. /**
  16451. * Creates a cube texture
  16452. * @param rootUrl defines the url where the files to load is located
  16453. * @param scene defines the current scene
  16454. * @param files defines the list of files to load (1 per face)
  16455. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  16456. * @param onLoad defines an optional callback raised when the texture is loaded
  16457. * @param onError defines an optional callback raised if there is an issue to load the texture
  16458. * @param format defines the format of the data
  16459. * @param forcedExtension defines the extension to use to pick the right loader
  16460. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  16461. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  16462. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  16463. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  16464. * @returns the cube texture as an InternalTexture
  16465. */
  16466. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  16467. var _this = this;
  16468. if (onLoad === void 0) { onLoad = null; }
  16469. if (onError === void 0) { onError = null; }
  16470. if (forcedExtension === void 0) { forcedExtension = null; }
  16471. if (createPolynomials === void 0) { createPolynomials = false; }
  16472. if (lodScale === void 0) { lodScale = 0; }
  16473. if (lodOffset === void 0) { lodOffset = 0; }
  16474. if (fallback === void 0) { fallback = null; }
  16475. var gl = this._gl;
  16476. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  16477. texture.isCube = true;
  16478. texture.url = rootUrl;
  16479. texture.generateMipMaps = !noMipmap;
  16480. texture._lodGenerationScale = lodScale;
  16481. texture._lodGenerationOffset = lodOffset;
  16482. if (!this._doNotHandleContextLost) {
  16483. texture._extension = forcedExtension;
  16484. texture._files = files;
  16485. }
  16486. var lastDot = rootUrl.lastIndexOf('.');
  16487. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  16488. var loader = null;
  16489. for (var _i = 0, _a = Engine._TextureLoaders; _i < _a.length; _i++) {
  16490. var availableLoader = _a[_i];
  16491. if (availableLoader.canLoad(extension, this._textureFormatInUse, fallback, false, false)) {
  16492. loader = availableLoader;
  16493. break;
  16494. }
  16495. }
  16496. var onInternalError = function (request, exception) {
  16497. if (loader) {
  16498. var fallbackUrl = loader.getFallbackTextureUrl(rootUrl, _this._textureFormatInUse);
  16499. if (fallbackUrl) {
  16500. _this.createCubeTexture(fallbackUrl, scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  16501. }
  16502. }
  16503. if (onError && request) {
  16504. onError(request.status + " " + request.statusText, exception);
  16505. }
  16506. };
  16507. if (loader) {
  16508. rootUrl = loader.transformUrl(rootUrl, this._textureFormatInUse);
  16509. var onloaddata = function (data) {
  16510. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16511. loader.loadCubeData(data, texture, createPolynomials, onLoad, onError);
  16512. };
  16513. if (files && files.length === 6) {
  16514. if (loader.supportCascades) {
  16515. this._cascadeLoadFiles(scene, onloaddata, files, onError);
  16516. }
  16517. else if (onError) {
  16518. onError("Textures type does not support cascades.");
  16519. }
  16520. }
  16521. else {
  16522. this._loadFile(rootUrl, onloaddata, undefined, undefined, true, onInternalError);
  16523. }
  16524. }
  16525. else {
  16526. if (!files) {
  16527. throw new Error("Cannot load cubemap because files were not defined");
  16528. }
  16529. this._cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16530. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16531. var height = width;
  16532. _this._prepareWorkingCanvas();
  16533. if (!_this._workingCanvas || !_this._workingContext) {
  16534. return;
  16535. }
  16536. _this._workingCanvas.width = width;
  16537. _this._workingCanvas.height = height;
  16538. var faces = [
  16539. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16540. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16541. ];
  16542. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16543. _this._unpackFlipY(false);
  16544. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16545. for (var index = 0; index < faces.length; index++) {
  16546. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16547. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16548. }
  16549. if (!noMipmap) {
  16550. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16551. }
  16552. _this._setCubeMapTextureParams(!noMipmap);
  16553. texture.width = width;
  16554. texture.height = height;
  16555. texture.isReady = true;
  16556. if (format) {
  16557. texture.format = format;
  16558. }
  16559. texture.onLoadedObservable.notifyObservers(texture);
  16560. texture.onLoadedObservable.clear();
  16561. if (onLoad) {
  16562. onLoad();
  16563. }
  16564. }, files, onError);
  16565. }
  16566. this._internalTexturesCache.push(texture);
  16567. return texture;
  16568. };
  16569. /**
  16570. * @hidden
  16571. */
  16572. Engine.prototype._setCubeMapTextureParams = function (loadMipmap) {
  16573. var gl = this._gl;
  16574. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16575. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16576. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16577. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16578. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16579. // this.resetTextureCache();
  16580. };
  16581. /**
  16582. * Update a raw cube texture
  16583. * @param texture defines the texture to udpdate
  16584. * @param data defines the data to store
  16585. * @param format defines the data format
  16586. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16587. * @param invertY defines if data must be stored with Y axis inverted
  16588. * @param compression defines the compression used (null by default)
  16589. * @param level defines which level of the texture to update
  16590. */
  16591. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16592. if (compression === void 0) { compression = null; }
  16593. if (level === void 0) { level = 0; }
  16594. texture._bufferViewArray = data;
  16595. texture.format = format;
  16596. texture.type = type;
  16597. texture.invertY = invertY;
  16598. texture._compression = compression;
  16599. var gl = this._gl;
  16600. var textureType = this._getWebGLTextureType(type);
  16601. var internalFormat = this._getInternalFormat(format);
  16602. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16603. var needConversion = false;
  16604. if (internalFormat === gl.RGB) {
  16605. internalFormat = gl.RGBA;
  16606. needConversion = true;
  16607. }
  16608. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16609. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16610. if (texture.width % 4 !== 0) {
  16611. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16612. }
  16613. // Data are known to be in +X +Y +Z -X -Y -Z
  16614. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16615. var faceData = data[faceIndex];
  16616. if (compression) {
  16617. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16618. }
  16619. else {
  16620. if (needConversion) {
  16621. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16622. }
  16623. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16624. }
  16625. }
  16626. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16627. if (isPot && texture.generateMipMaps && level === 0) {
  16628. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16629. }
  16630. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16631. // this.resetTextureCache();
  16632. texture.isReady = true;
  16633. };
  16634. /**
  16635. * Creates a new raw cube texture
  16636. * @param data defines the array of data to use to create each face
  16637. * @param size defines the size of the textures
  16638. * @param format defines the format of the data
  16639. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16640. * @param generateMipMaps defines if the engine should generate the mip levels
  16641. * @param invertY defines if data must be stored with Y axis inverted
  16642. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16643. * @param compression defines the compression used (null by default)
  16644. * @returns the cube texture as an InternalTexture
  16645. */
  16646. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16647. if (compression === void 0) { compression = null; }
  16648. var gl = this._gl;
  16649. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16650. texture.isCube = true;
  16651. texture.format = format;
  16652. texture.type = type;
  16653. if (!this._doNotHandleContextLost) {
  16654. texture._bufferViewArray = data;
  16655. }
  16656. var textureType = this._getWebGLTextureType(type);
  16657. var internalFormat = this._getInternalFormat(format);
  16658. if (internalFormat === gl.RGB) {
  16659. internalFormat = gl.RGBA;
  16660. }
  16661. // Mipmap generation needs a sized internal format that is both color-renderable and texture-filterable
  16662. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16663. generateMipMaps = false;
  16664. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16665. BABYLON.Tools.Warn("Float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16666. }
  16667. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16668. generateMipMaps = false;
  16669. samplingMode = Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  16670. BABYLON.Tools.Warn("Half float texture filtering is not supported. Mipmap generation and sampling mode are forced to false and TEXTURE_NEAREST_SAMPLINGMODE, respectively.");
  16671. }
  16672. else if (textureType === gl.FLOAT && !this._caps.textureFloatRender) {
  16673. generateMipMaps = false;
  16674. BABYLON.Tools.Warn("Render to float textures is not supported. Mipmap generation forced to false.");
  16675. }
  16676. else if (textureType === gl.HALF_FLOAT && !this._caps.colorBufferFloat) {
  16677. generateMipMaps = false;
  16678. BABYLON.Tools.Warn("Render to half float textures is not supported. Mipmap generation forced to false.");
  16679. }
  16680. var width = size;
  16681. var height = width;
  16682. texture.width = width;
  16683. texture.height = height;
  16684. // Double check on POT to generate Mips.
  16685. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16686. if (!isPot) {
  16687. generateMipMaps = false;
  16688. }
  16689. // Upload data if needed. The texture won't be ready until then.
  16690. if (data) {
  16691. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16692. }
  16693. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16694. // Filters
  16695. if (data && generateMipMaps) {
  16696. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16697. }
  16698. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16699. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16700. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16701. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16702. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16703. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16704. texture.generateMipMaps = generateMipMaps;
  16705. return texture;
  16706. };
  16707. /**
  16708. * Creates a new raw cube texture from a specified url
  16709. * @param url defines the url where the data is located
  16710. * @param scene defines the current scene
  16711. * @param size defines the size of the textures
  16712. * @param format defines the format of the data
  16713. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16714. * @param noMipmap defines if the engine should avoid generating the mip levels
  16715. * @param callback defines a callback used to extract texture data from loaded data
  16716. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16717. * @param onLoad defines a callback called when texture is loaded
  16718. * @param onError defines a callback called if there is an error
  16719. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16720. * @param invertY defines if data must be stored with Y axis inverted
  16721. * @returns the cube texture as an InternalTexture
  16722. */
  16723. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16724. var _this = this;
  16725. if (onLoad === void 0) { onLoad = null; }
  16726. if (onError === void 0) { onError = null; }
  16727. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16728. if (invertY === void 0) { invertY = false; }
  16729. var gl = this._gl;
  16730. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16731. scene._addPendingData(texture);
  16732. texture.url = url;
  16733. this._internalTexturesCache.push(texture);
  16734. var onerror = function (request, exception) {
  16735. scene._removePendingData(texture);
  16736. if (onError && request) {
  16737. onError(request.status + " " + request.statusText, exception);
  16738. }
  16739. };
  16740. var internalCallback = function (data) {
  16741. var width = texture.width;
  16742. var faceDataArrays = callback(data);
  16743. if (!faceDataArrays) {
  16744. return;
  16745. }
  16746. if (mipmapGenerator) {
  16747. var textureType = _this._getWebGLTextureType(type);
  16748. var internalFormat = _this._getInternalFormat(format);
  16749. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16750. var needConversion = false;
  16751. if (internalFormat === gl.RGB) {
  16752. internalFormat = gl.RGBA;
  16753. needConversion = true;
  16754. }
  16755. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16756. _this._unpackFlipY(false);
  16757. var mipData = mipmapGenerator(faceDataArrays);
  16758. for (var level = 0; level < mipData.length; level++) {
  16759. var mipSize = width >> level;
  16760. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16761. var mipFaceData = mipData[level][faceIndex];
  16762. if (needConversion) {
  16763. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16764. }
  16765. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16766. }
  16767. }
  16768. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16769. }
  16770. else {
  16771. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16772. }
  16773. texture.isReady = true;
  16774. // this.resetTextureCache();
  16775. scene._removePendingData(texture);
  16776. if (onLoad) {
  16777. onLoad();
  16778. }
  16779. };
  16780. this._loadFile(url, function (data) {
  16781. internalCallback(data);
  16782. }, undefined, scene.database, true, onerror);
  16783. return texture;
  16784. };
  16785. ;
  16786. /**
  16787. * Update a raw 3D texture
  16788. * @param texture defines the texture to update
  16789. * @param data defines the data to store
  16790. * @param format defines the data format
  16791. * @param invertY defines if data must be stored with Y axis inverted
  16792. * @param compression defines the used compression (can be null)
  16793. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16794. */
  16795. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16796. if (compression === void 0) { compression = null; }
  16797. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16798. var internalType = this._getWebGLTextureType(textureType);
  16799. var internalFormat = this._getInternalFormat(format);
  16800. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16801. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16802. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16803. if (!this._doNotHandleContextLost) {
  16804. texture._bufferView = data;
  16805. texture.format = format;
  16806. texture.invertY = invertY;
  16807. texture._compression = compression;
  16808. }
  16809. if (texture.width % 4 !== 0) {
  16810. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16811. }
  16812. if (compression && data) {
  16813. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16814. }
  16815. else {
  16816. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16817. }
  16818. if (texture.generateMipMaps) {
  16819. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16820. }
  16821. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16822. // this.resetTextureCache();
  16823. texture.isReady = true;
  16824. };
  16825. /**
  16826. * Creates a new raw 3D texture
  16827. * @param data defines the data used to create the texture
  16828. * @param width defines the width of the texture
  16829. * @param height defines the height of the texture
  16830. * @param depth defines the depth of the texture
  16831. * @param format defines the format of the texture
  16832. * @param generateMipMaps defines if the engine must generate mip levels
  16833. * @param invertY defines if data must be stored with Y axis inverted
  16834. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16835. * @param compression defines the compressed used (can be null)
  16836. * @param textureType defines the compressed used (can be null)
  16837. * @returns a new raw 3D texture (stored in an InternalTexture)
  16838. */
  16839. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16840. if (compression === void 0) { compression = null; }
  16841. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16842. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16843. texture.baseWidth = width;
  16844. texture.baseHeight = height;
  16845. texture.baseDepth = depth;
  16846. texture.width = width;
  16847. texture.height = height;
  16848. texture.depth = depth;
  16849. texture.format = format;
  16850. texture.type = textureType;
  16851. texture.generateMipMaps = generateMipMaps;
  16852. texture.samplingMode = samplingMode;
  16853. texture.is3D = true;
  16854. if (!this._doNotHandleContextLost) {
  16855. texture._bufferView = data;
  16856. }
  16857. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16858. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16859. // Filters
  16860. var filters = this._getSamplingParameters(samplingMode, generateMipMaps);
  16861. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16862. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16863. if (generateMipMaps) {
  16864. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16865. }
  16866. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16867. this._internalTexturesCache.push(texture);
  16868. return texture;
  16869. };
  16870. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16871. var gl = this._gl;
  16872. if (!gl) {
  16873. return;
  16874. }
  16875. var filters = this._getSamplingParameters(samplingMode, !noMipmap);
  16876. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16877. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16878. if (!noMipmap && !isCompressed) {
  16879. gl.generateMipmap(gl.TEXTURE_2D);
  16880. }
  16881. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16882. // this.resetTextureCache();
  16883. if (scene) {
  16884. scene._removePendingData(texture);
  16885. }
  16886. texture.onLoadedObservable.notifyObservers(texture);
  16887. texture.onLoadedObservable.clear();
  16888. };
  16889. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16890. var _this = this;
  16891. if (samplingMode === void 0) { samplingMode = Engine.TEXTURE_TRILINEAR_SAMPLINGMODE; }
  16892. var maxTextureSize = this.getCaps().maxTextureSize;
  16893. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16894. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16895. var gl = this._gl;
  16896. if (!gl) {
  16897. return;
  16898. }
  16899. if (!texture._webGLTexture) {
  16900. // this.resetTextureCache();
  16901. if (scene) {
  16902. scene._removePendingData(texture);
  16903. }
  16904. return;
  16905. }
  16906. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16907. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16908. texture.baseWidth = width;
  16909. texture.baseHeight = height;
  16910. texture.width = potWidth;
  16911. texture.height = potHeight;
  16912. texture.isReady = true;
  16913. if (processFunction(potWidth, potHeight, function () {
  16914. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16915. })) {
  16916. // Returning as texture needs extra async steps
  16917. return;
  16918. }
  16919. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16920. };
  16921. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16922. // Create new RGBA data container.
  16923. var rgbaData;
  16924. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16925. rgbaData = new Float32Array(width * height * 4);
  16926. }
  16927. else {
  16928. rgbaData = new Uint32Array(width * height * 4);
  16929. }
  16930. // Convert each pixel.
  16931. for (var x = 0; x < width; x++) {
  16932. for (var y = 0; y < height; y++) {
  16933. var index = (y * width + x) * 3;
  16934. var newIndex = (y * width + x) * 4;
  16935. // Map Old Value to new value.
  16936. rgbaData[newIndex + 0] = rgbData[index + 0];
  16937. rgbaData[newIndex + 1] = rgbData[index + 1];
  16938. rgbaData[newIndex + 2] = rgbData[index + 2];
  16939. // Add fully opaque alpha channel.
  16940. rgbaData[newIndex + 3] = 1;
  16941. }
  16942. }
  16943. return rgbaData;
  16944. };
  16945. /** @hidden */
  16946. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16947. var gl = this._gl;
  16948. if (texture._framebuffer) {
  16949. gl.deleteFramebuffer(texture._framebuffer);
  16950. texture._framebuffer = null;
  16951. }
  16952. if (texture._depthStencilBuffer) {
  16953. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16954. texture._depthStencilBuffer = null;
  16955. }
  16956. if (texture._MSAAFramebuffer) {
  16957. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16958. texture._MSAAFramebuffer = null;
  16959. }
  16960. if (texture._MSAARenderBuffer) {
  16961. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16962. texture._MSAARenderBuffer = null;
  16963. }
  16964. };
  16965. /** @hidden */
  16966. Engine.prototype._releaseTexture = function (texture) {
  16967. var gl = this._gl;
  16968. this._releaseFramebufferObjects(texture);
  16969. gl.deleteTexture(texture._webGLTexture);
  16970. // Unbind channels
  16971. this.unbindAllTextures();
  16972. var index = this._internalTexturesCache.indexOf(texture);
  16973. if (index !== -1) {
  16974. this._internalTexturesCache.splice(index, 1);
  16975. }
  16976. // Integrated fixed lod samplers.
  16977. if (texture._lodTextureHigh) {
  16978. texture._lodTextureHigh.dispose();
  16979. }
  16980. if (texture._lodTextureMid) {
  16981. texture._lodTextureMid.dispose();
  16982. }
  16983. if (texture._lodTextureLow) {
  16984. texture._lodTextureLow.dispose();
  16985. }
  16986. // Set output texture of post process to null if the texture has been released/disposed
  16987. this.scenes.forEach(function (scene) {
  16988. scene.postProcesses.forEach(function (postProcess) {
  16989. if (postProcess._outputTexture == texture) {
  16990. postProcess._outputTexture = null;
  16991. }
  16992. });
  16993. scene.cameras.forEach(function (camera) {
  16994. camera._postProcesses.forEach(function (postProcess) {
  16995. if (postProcess) {
  16996. if (postProcess._outputTexture == texture) {
  16997. postProcess._outputTexture = null;
  16998. }
  16999. }
  17000. });
  17001. });
  17002. });
  17003. };
  17004. Engine.prototype.setProgram = function (program) {
  17005. if (this._currentProgram !== program) {
  17006. this._gl.useProgram(program);
  17007. this._currentProgram = program;
  17008. }
  17009. };
  17010. /**
  17011. * Binds an effect to the webGL context
  17012. * @param effect defines the effect to bind
  17013. */
  17014. Engine.prototype.bindSamplers = function (effect) {
  17015. this.setProgram(effect.getProgram());
  17016. var samplers = effect.getSamplers();
  17017. for (var index = 0; index < samplers.length; index++) {
  17018. var uniform = effect.getUniform(samplers[index]);
  17019. if (uniform) {
  17020. this._boundUniforms[index] = uniform;
  17021. }
  17022. }
  17023. this._currentEffect = null;
  17024. };
  17025. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  17026. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  17027. return;
  17028. }
  17029. // Remove
  17030. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17031. // Bind last to it
  17032. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  17033. // Bind to dummy
  17034. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  17035. };
  17036. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  17037. if (!internalTexture) {
  17038. return -1;
  17039. }
  17040. internalTexture._initialSlot = channel;
  17041. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  17042. if (channel !== internalTexture._designatedSlot) {
  17043. this._textureCollisions.addCount(1, false);
  17044. }
  17045. }
  17046. else {
  17047. if (channel !== internalTexture._designatedSlot) {
  17048. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  17049. return internalTexture._designatedSlot;
  17050. }
  17051. else {
  17052. // No slot for this texture, let's pick a new one (if we find a free slot)
  17053. if (this._nextFreeTextureSlots.length) {
  17054. return this._nextFreeTextureSlots[0];
  17055. }
  17056. // We need to recycle the oldest bound texture, sorry.
  17057. this._textureCollisions.addCount(1, false);
  17058. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  17059. }
  17060. }
  17061. }
  17062. return channel;
  17063. };
  17064. Engine.prototype._linkTrackers = function (previous, next) {
  17065. previous.next = next;
  17066. next.previous = previous;
  17067. };
  17068. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  17069. var currentSlot = internalTexture._designatedSlot;
  17070. if (currentSlot === -1) {
  17071. return -1;
  17072. }
  17073. internalTexture._designatedSlot = -1;
  17074. if (this.disableTextureBindingOptimization) {
  17075. return -1;
  17076. }
  17077. // Remove from bound list
  17078. this._linkTrackers(internalTexture.previous, internalTexture.next);
  17079. // Free the slot
  17080. this._boundTexturesCache[currentSlot] = null;
  17081. this._nextFreeTextureSlots.push(currentSlot);
  17082. return currentSlot;
  17083. };
  17084. Engine.prototype._activateCurrentTexture = function () {
  17085. if (this._currentTextureChannel !== this._activeChannel) {
  17086. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  17087. this._currentTextureChannel = this._activeChannel;
  17088. }
  17089. };
  17090. /** @hidden */
  17091. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  17092. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  17093. if (force === void 0) { force = false; }
  17094. var wasPreviouslyBound = false;
  17095. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  17096. this._activeChannel = texture._designatedSlot;
  17097. }
  17098. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  17099. var isTextureForRendering = texture && texture._initialSlot > -1;
  17100. if (currentTextureBound !== texture || force) {
  17101. if (currentTextureBound) {
  17102. this._removeDesignatedSlot(currentTextureBound);
  17103. }
  17104. this._activateCurrentTexture();
  17105. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  17106. this._boundTexturesCache[this._activeChannel] = texture;
  17107. if (texture) {
  17108. if (!this.disableTextureBindingOptimization) {
  17109. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  17110. if (slotIndex > -1) {
  17111. this._nextFreeTextureSlots.splice(slotIndex, 1);
  17112. }
  17113. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  17114. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  17115. }
  17116. texture._designatedSlot = this._activeChannel;
  17117. }
  17118. }
  17119. else if (forTextureDataUpdate) {
  17120. wasPreviouslyBound = true;
  17121. this._activateCurrentTexture();
  17122. }
  17123. if (isTextureForRendering && !forTextureDataUpdate) {
  17124. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  17125. }
  17126. return wasPreviouslyBound;
  17127. };
  17128. /** @hidden */
  17129. Engine.prototype._bindTexture = function (channel, texture) {
  17130. if (channel < 0) {
  17131. return;
  17132. }
  17133. if (texture) {
  17134. channel = this._getCorrectTextureChannel(channel, texture);
  17135. }
  17136. this._activeChannel = channel;
  17137. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  17138. };
  17139. /**
  17140. * Sets a texture to the webGL context from a postprocess
  17141. * @param channel defines the channel to use
  17142. * @param postProcess defines the source postprocess
  17143. */
  17144. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  17145. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  17146. };
  17147. /**
  17148. * Binds the output of the passed in post process to the texture channel specified
  17149. * @param channel The channel the texture should be bound to
  17150. * @param postProcess The post process which's output should be bound
  17151. */
  17152. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  17153. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  17154. };
  17155. /**
  17156. * Unbind all textures from the webGL context
  17157. */
  17158. Engine.prototype.unbindAllTextures = function () {
  17159. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  17160. this._activeChannel = channel;
  17161. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17162. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17163. if (this.webGLVersion > 1) {
  17164. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17165. }
  17166. }
  17167. };
  17168. /**
  17169. * Sets a texture to the according uniform.
  17170. * @param channel The texture channel
  17171. * @param uniform The uniform to set
  17172. * @param texture The texture to apply
  17173. */
  17174. Engine.prototype.setTexture = function (channel, uniform, texture) {
  17175. if (channel < 0) {
  17176. return;
  17177. }
  17178. if (uniform) {
  17179. this._boundUniforms[channel] = uniform;
  17180. }
  17181. this._setTexture(channel, texture);
  17182. };
  17183. /**
  17184. * Sets a depth stencil texture from a render target to the according uniform.
  17185. * @param channel The texture channel
  17186. * @param uniform The uniform to set
  17187. * @param texture The render target texture containing the depth stencil texture to apply
  17188. */
  17189. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  17190. if (channel < 0) {
  17191. return;
  17192. }
  17193. if (uniform) {
  17194. this._boundUniforms[channel] = uniform;
  17195. }
  17196. if (!texture || !texture.depthStencilTexture) {
  17197. this._setTexture(channel, null);
  17198. }
  17199. else {
  17200. this._setTexture(channel, texture, false, true);
  17201. }
  17202. };
  17203. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  17204. var uniform = this._boundUniforms[sourceSlot];
  17205. if (uniform._currentState === destination) {
  17206. return;
  17207. }
  17208. this._gl.uniform1i(uniform, destination);
  17209. uniform._currentState = destination;
  17210. };
  17211. Engine.prototype._getTextureWrapMode = function (mode) {
  17212. switch (mode) {
  17213. case Engine.TEXTURE_WRAP_ADDRESSMODE:
  17214. return this._gl.REPEAT;
  17215. case Engine.TEXTURE_CLAMP_ADDRESSMODE:
  17216. return this._gl.CLAMP_TO_EDGE;
  17217. case Engine.TEXTURE_MIRROR_ADDRESSMODE:
  17218. return this._gl.MIRRORED_REPEAT;
  17219. }
  17220. return this._gl.REPEAT;
  17221. };
  17222. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  17223. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  17224. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  17225. // Not ready?
  17226. if (!texture) {
  17227. if (this._boundTexturesCache[channel] != null) {
  17228. this._activeChannel = channel;
  17229. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  17230. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  17231. if (this.webGLVersion > 1) {
  17232. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  17233. }
  17234. }
  17235. return false;
  17236. }
  17237. // Video
  17238. if (texture.video) {
  17239. this._activeChannel = channel;
  17240. texture.update();
  17241. }
  17242. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  17243. texture.delayLoad();
  17244. return false;
  17245. }
  17246. var internalTexture;
  17247. if (depthStencilTexture) {
  17248. internalTexture = texture.depthStencilTexture;
  17249. }
  17250. else if (texture.isReady()) {
  17251. internalTexture = texture.getInternalTexture();
  17252. }
  17253. else if (texture.isCube) {
  17254. internalTexture = this.emptyCubeTexture;
  17255. }
  17256. else if (texture.is3D) {
  17257. internalTexture = this.emptyTexture3D;
  17258. }
  17259. else {
  17260. internalTexture = this.emptyTexture;
  17261. }
  17262. if (!isPartOfTextureArray) {
  17263. channel = this._getCorrectTextureChannel(channel, internalTexture);
  17264. }
  17265. var needToBind = true;
  17266. if (this._boundTexturesCache[channel] === internalTexture) {
  17267. this._moveBoundTextureOnTop(internalTexture);
  17268. if (!isPartOfTextureArray) {
  17269. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  17270. }
  17271. needToBind = false;
  17272. }
  17273. this._activeChannel = channel;
  17274. if (internalTexture && internalTexture.is3D) {
  17275. if (needToBind) {
  17276. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  17277. }
  17278. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17279. internalTexture._cachedWrapU = texture.wrapU;
  17280. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17281. }
  17282. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17283. internalTexture._cachedWrapV = texture.wrapV;
  17284. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17285. }
  17286. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  17287. internalTexture._cachedWrapR = texture.wrapR;
  17288. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  17289. }
  17290. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  17291. }
  17292. else if (internalTexture && internalTexture.isCube) {
  17293. if (needToBind) {
  17294. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  17295. }
  17296. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  17297. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  17298. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  17299. var textureWrapMode = (texture.coordinatesMode !== Engine.TEXTURE_CUBIC_MODE && texture.coordinatesMode !== Engine.TEXTURE_SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  17300. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  17301. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  17302. }
  17303. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  17304. }
  17305. else {
  17306. if (needToBind) {
  17307. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  17308. }
  17309. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  17310. internalTexture._cachedWrapU = texture.wrapU;
  17311. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  17312. }
  17313. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  17314. internalTexture._cachedWrapV = texture.wrapV;
  17315. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  17316. }
  17317. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  17318. }
  17319. return true;
  17320. };
  17321. /**
  17322. * Sets an array of texture to the webGL context
  17323. * @param channel defines the channel where the texture array must be set
  17324. * @param uniform defines the associated uniform location
  17325. * @param textures defines the array of textures to bind
  17326. */
  17327. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  17328. if (channel < 0 || !uniform) {
  17329. return;
  17330. }
  17331. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  17332. this._textureUnits = new Int32Array(textures.length);
  17333. }
  17334. for (var i = 0; i < textures.length; i++) {
  17335. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  17336. }
  17337. this._gl.uniform1iv(uniform, this._textureUnits);
  17338. for (var index = 0; index < textures.length; index++) {
  17339. this._setTexture(this._textureUnits[index], textures[index], true);
  17340. }
  17341. };
  17342. /** @hidden */
  17343. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  17344. var internalTexture = texture.getInternalTexture();
  17345. if (!internalTexture) {
  17346. return;
  17347. }
  17348. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  17349. var value = texture.anisotropicFilteringLevel;
  17350. if (internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST
  17351. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR
  17352. && internalTexture.samplingMode !== Engine.TEXTURE_LINEAR_LINEAR) {
  17353. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  17354. }
  17355. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  17356. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  17357. internalTexture._cachedAnisotropicFilteringLevel = value;
  17358. }
  17359. };
  17360. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  17361. this._bindTextureDirectly(target, texture, true, true);
  17362. this._gl.texParameterf(target, parameter, value);
  17363. };
  17364. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  17365. if (texture) {
  17366. this._bindTextureDirectly(target, texture, true, true);
  17367. }
  17368. this._gl.texParameteri(target, parameter, value);
  17369. };
  17370. /**
  17371. * Reads pixels from the current frame buffer. Please note that this function can be slow
  17372. * @param x defines the x coordinate of the rectangle where pixels must be read
  17373. * @param y defines the y coordinate of the rectangle where pixels must be read
  17374. * @param width defines the width of the rectangle where pixels must be read
  17375. * @param height defines the height of the rectangle where pixels must be read
  17376. * @returns a Uint8Array containing RGBA colors
  17377. */
  17378. Engine.prototype.readPixels = function (x, y, width, height) {
  17379. var data = new Uint8Array(height * width * 4);
  17380. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  17381. return data;
  17382. };
  17383. /**
  17384. * Add an externaly attached data from its key.
  17385. * This method call will fail and return false, if such key already exists.
  17386. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  17387. * @param key the unique key that identifies the data
  17388. * @param data the data object to associate to the key for this Engine instance
  17389. * @return true if no such key were already present and the data was added successfully, false otherwise
  17390. */
  17391. Engine.prototype.addExternalData = function (key, data) {
  17392. if (!this._externalData) {
  17393. this._externalData = new BABYLON.StringDictionary();
  17394. }
  17395. return this._externalData.add(key, data);
  17396. };
  17397. /**
  17398. * Get an externaly attached data from its key
  17399. * @param key the unique key that identifies the data
  17400. * @return the associated data, if present (can be null), or undefined if not present
  17401. */
  17402. Engine.prototype.getExternalData = function (key) {
  17403. if (!this._externalData) {
  17404. this._externalData = new BABYLON.StringDictionary();
  17405. }
  17406. return this._externalData.get(key);
  17407. };
  17408. /**
  17409. * Get an externaly attached data from its key, create it using a factory if it's not already present
  17410. * @param key the unique key that identifies the data
  17411. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  17412. * @return the associated data, can be null if the factory returned null.
  17413. */
  17414. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  17415. if (!this._externalData) {
  17416. this._externalData = new BABYLON.StringDictionary();
  17417. }
  17418. return this._externalData.getOrAddWithFactory(key, factory);
  17419. };
  17420. /**
  17421. * Remove an externaly attached data from the Engine instance
  17422. * @param key the unique key that identifies the data
  17423. * @return true if the data was successfully removed, false if it doesn't exist
  17424. */
  17425. Engine.prototype.removeExternalData = function (key) {
  17426. if (!this._externalData) {
  17427. this._externalData = new BABYLON.StringDictionary();
  17428. }
  17429. return this._externalData.remove(key);
  17430. };
  17431. /**
  17432. * Unbind all vertex attributes from the webGL context
  17433. */
  17434. Engine.prototype.unbindAllAttributes = function () {
  17435. if (this._mustWipeVertexAttributes) {
  17436. this._mustWipeVertexAttributes = false;
  17437. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  17438. this._gl.disableVertexAttribArray(i);
  17439. this._vertexAttribArraysEnabled[i] = false;
  17440. this._currentBufferPointers[i].active = false;
  17441. }
  17442. return;
  17443. }
  17444. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  17445. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  17446. continue;
  17447. }
  17448. this._gl.disableVertexAttribArray(i);
  17449. this._vertexAttribArraysEnabled[i] = false;
  17450. this._currentBufferPointers[i].active = false;
  17451. }
  17452. };
  17453. /**
  17454. * 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
  17455. */
  17456. Engine.prototype.releaseEffects = function () {
  17457. for (var name in this._compiledEffects) {
  17458. this._deleteProgram(this._compiledEffects[name]._program);
  17459. }
  17460. this._compiledEffects = {};
  17461. };
  17462. /**
  17463. * Dispose and release all associated resources
  17464. */
  17465. Engine.prototype.dispose = function () {
  17466. this.hideLoadingUI();
  17467. this.stopRenderLoop();
  17468. // Release postProcesses
  17469. while (this.postProcesses.length) {
  17470. this.postProcesses[0].dispose();
  17471. }
  17472. // Empty texture
  17473. if (this._emptyTexture) {
  17474. this._releaseTexture(this._emptyTexture);
  17475. this._emptyTexture = null;
  17476. }
  17477. if (this._emptyCubeTexture) {
  17478. this._releaseTexture(this._emptyCubeTexture);
  17479. this._emptyCubeTexture = null;
  17480. }
  17481. // Rescale PP
  17482. if (this._rescalePostProcess) {
  17483. this._rescalePostProcess.dispose();
  17484. }
  17485. // Release scenes
  17486. while (this.scenes.length) {
  17487. this.scenes[0].dispose();
  17488. }
  17489. // Release audio engine
  17490. if (Engine.Instances.length === 1 && Engine.audioEngine) {
  17491. Engine.audioEngine.dispose();
  17492. }
  17493. // Release effects
  17494. this.releaseEffects();
  17495. // Unbind
  17496. this.unbindAllAttributes();
  17497. this._boundUniforms = [];
  17498. if (this._dummyFramebuffer) {
  17499. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17500. }
  17501. //WebVR
  17502. this.disableVR();
  17503. // Events
  17504. if (BABYLON.Tools.IsWindowObjectExist()) {
  17505. window.removeEventListener("blur", this._onBlur);
  17506. window.removeEventListener("focus", this._onFocus);
  17507. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17508. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17509. if (this._renderingCanvas) {
  17510. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17511. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17512. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17513. if (!this._doNotHandleContextLost) {
  17514. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17515. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17516. }
  17517. }
  17518. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17519. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17520. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17521. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17522. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17523. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17524. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17525. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17526. if (this._onVrDisplayConnect) {
  17527. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17528. if (this._onVrDisplayDisconnect) {
  17529. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17530. }
  17531. if (this._onVrDisplayPresentChange) {
  17532. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17533. }
  17534. this._onVrDisplayConnect = null;
  17535. this._onVrDisplayDisconnect = null;
  17536. }
  17537. }
  17538. // Remove from Instances
  17539. var index = Engine.Instances.indexOf(this);
  17540. if (index >= 0) {
  17541. Engine.Instances.splice(index, 1);
  17542. }
  17543. this._workingCanvas = null;
  17544. this._workingContext = null;
  17545. this._currentBufferPointers = [];
  17546. this._renderingCanvas = null;
  17547. this._currentProgram = null;
  17548. this._bindedRenderFunction = null;
  17549. this.onResizeObservable.clear();
  17550. this.onCanvasBlurObservable.clear();
  17551. this.onCanvasFocusObservable.clear();
  17552. this.onCanvasPointerOutObservable.clear();
  17553. this.onBeginFrameObservable.clear();
  17554. this.onEndFrameObservable.clear();
  17555. BABYLON.Effect.ResetCache();
  17556. // Abort active requests
  17557. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17558. var request = _a[_i];
  17559. request.abort();
  17560. }
  17561. };
  17562. // Loading screen
  17563. /**
  17564. * Display the loading screen
  17565. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17566. */
  17567. Engine.prototype.displayLoadingUI = function () {
  17568. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17569. return;
  17570. }
  17571. var loadingScreen = this.loadingScreen;
  17572. if (loadingScreen) {
  17573. loadingScreen.displayLoadingUI();
  17574. }
  17575. };
  17576. /**
  17577. * Hide the loading screen
  17578. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17579. */
  17580. Engine.prototype.hideLoadingUI = function () {
  17581. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17582. return;
  17583. }
  17584. var loadingScreen = this.loadingScreen;
  17585. if (loadingScreen) {
  17586. loadingScreen.hideLoadingUI();
  17587. }
  17588. };
  17589. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17590. /**
  17591. * Gets the current loading screen object
  17592. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17593. */
  17594. get: function () {
  17595. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17596. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17597. return this._loadingScreen;
  17598. },
  17599. /**
  17600. * Sets the current loading screen object
  17601. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17602. */
  17603. set: function (loadingScreen) {
  17604. this._loadingScreen = loadingScreen;
  17605. },
  17606. enumerable: true,
  17607. configurable: true
  17608. });
  17609. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17610. /**
  17611. * Sets the current loading screen text
  17612. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17613. */
  17614. set: function (text) {
  17615. this.loadingScreen.loadingUIText = text;
  17616. },
  17617. enumerable: true,
  17618. configurable: true
  17619. });
  17620. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17621. /**
  17622. * Sets the current loading screen background color
  17623. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17624. */
  17625. set: function (color) {
  17626. this.loadingScreen.loadingUIBackgroundColor = color;
  17627. },
  17628. enumerable: true,
  17629. configurable: true
  17630. });
  17631. /**
  17632. * Attach a new callback raised when context lost event is fired
  17633. * @param callback defines the callback to call
  17634. */
  17635. Engine.prototype.attachContextLostEvent = function (callback) {
  17636. if (this._renderingCanvas) {
  17637. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17638. }
  17639. };
  17640. /**
  17641. * Attach a new callback raised when context restored event is fired
  17642. * @param callback defines the callback to call
  17643. */
  17644. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17645. if (this._renderingCanvas) {
  17646. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17647. }
  17648. };
  17649. /**
  17650. * Gets the source code of the vertex shader associated with a specific webGL program
  17651. * @param program defines the program to use
  17652. * @returns a string containing the source code of the vertex shader associated with the program
  17653. */
  17654. Engine.prototype.getVertexShaderSource = function (program) {
  17655. var shaders = this._gl.getAttachedShaders(program);
  17656. if (!shaders) {
  17657. return null;
  17658. }
  17659. return this._gl.getShaderSource(shaders[0]);
  17660. };
  17661. /**
  17662. * Gets the source code of the fragment shader associated with a specific webGL program
  17663. * @param program defines the program to use
  17664. * @returns a string containing the source code of the fragment shader associated with the program
  17665. */
  17666. Engine.prototype.getFragmentShaderSource = function (program) {
  17667. var shaders = this._gl.getAttachedShaders(program);
  17668. if (!shaders) {
  17669. return null;
  17670. }
  17671. return this._gl.getShaderSource(shaders[1]);
  17672. };
  17673. /**
  17674. * Get the current error code of the webGL context
  17675. * @returns the error code
  17676. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17677. */
  17678. Engine.prototype.getError = function () {
  17679. return this._gl.getError();
  17680. };
  17681. // FPS
  17682. /**
  17683. * Gets the current framerate
  17684. * @returns a number representing the framerate
  17685. */
  17686. Engine.prototype.getFps = function () {
  17687. return this._fps;
  17688. };
  17689. /**
  17690. * Gets the time spent between current and previous frame
  17691. * @returns a number representing the delta time in ms
  17692. */
  17693. Engine.prototype.getDeltaTime = function () {
  17694. return this._deltaTime;
  17695. };
  17696. Engine.prototype._measureFps = function () {
  17697. this._performanceMonitor.sampleFrame();
  17698. this._fps = this._performanceMonitor.averageFPS;
  17699. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17700. };
  17701. /** @hidden */
  17702. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level, buffer) {
  17703. if (faceIndex === void 0) { faceIndex = -1; }
  17704. if (level === void 0) { level = 0; }
  17705. if (buffer === void 0) { buffer = null; }
  17706. var gl = this._gl;
  17707. if (!this._dummyFramebuffer) {
  17708. var dummy = gl.createFramebuffer();
  17709. if (!dummy) {
  17710. throw new Error("Unable to create dummy framebuffer");
  17711. }
  17712. this._dummyFramebuffer = dummy;
  17713. }
  17714. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17715. if (faceIndex > -1) {
  17716. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17717. }
  17718. else {
  17719. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17720. }
  17721. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17722. switch (readType) {
  17723. case gl.UNSIGNED_BYTE:
  17724. if (!buffer) {
  17725. buffer = new Uint8Array(4 * width * height);
  17726. }
  17727. readType = gl.UNSIGNED_BYTE;
  17728. break;
  17729. default:
  17730. if (!buffer) {
  17731. buffer = new Float32Array(4 * width * height);
  17732. }
  17733. readType = gl.FLOAT;
  17734. break;
  17735. }
  17736. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17737. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17738. return buffer;
  17739. };
  17740. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17741. if (this._webGLVersion > 1) {
  17742. return this._caps.colorBufferFloat;
  17743. }
  17744. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17745. };
  17746. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17747. if (this._webGLVersion > 1) {
  17748. return this._caps.colorBufferFloat;
  17749. }
  17750. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17751. };
  17752. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17753. Engine.prototype._canRenderToFramebuffer = function (type) {
  17754. var gl = this._gl;
  17755. //clear existing errors
  17756. while (gl.getError() !== gl.NO_ERROR) { }
  17757. var successful = true;
  17758. var texture = gl.createTexture();
  17759. gl.bindTexture(gl.TEXTURE_2D, texture);
  17760. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17761. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17762. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17763. var fb = gl.createFramebuffer();
  17764. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17765. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17766. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17767. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17768. successful = successful && (gl.getError() === gl.NO_ERROR);
  17769. //try render by clearing frame buffer's color buffer
  17770. if (successful) {
  17771. gl.clear(gl.COLOR_BUFFER_BIT);
  17772. successful = successful && (gl.getError() === gl.NO_ERROR);
  17773. }
  17774. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17775. if (successful) {
  17776. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17777. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17778. var readFormat = gl.RGBA;
  17779. var readType = gl.UNSIGNED_BYTE;
  17780. var buffer = new Uint8Array(4);
  17781. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17782. successful = successful && (gl.getError() === gl.NO_ERROR);
  17783. }
  17784. //clean up
  17785. gl.deleteTexture(texture);
  17786. gl.deleteFramebuffer(fb);
  17787. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17788. //clear accumulated errors
  17789. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17790. return successful;
  17791. };
  17792. /** @hidden */
  17793. Engine.prototype._getWebGLTextureType = function (type) {
  17794. if (this._webGLVersion === 1) {
  17795. switch (type) {
  17796. case Engine.TEXTURETYPE_FLOAT:
  17797. return this._gl.FLOAT;
  17798. case Engine.TEXTURETYPE_HALF_FLOAT:
  17799. return this._gl.HALF_FLOAT_OES;
  17800. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17801. return this._gl.UNSIGNED_BYTE;
  17802. }
  17803. return this._gl.UNSIGNED_BYTE;
  17804. }
  17805. switch (type) {
  17806. case Engine.TEXTURETYPE_BYTE:
  17807. return this._gl.BYTE;
  17808. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17809. return this._gl.UNSIGNED_BYTE;
  17810. case Engine.TEXTURETYPE_SHORT:
  17811. return this._gl.SHORT;
  17812. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17813. return this._gl.UNSIGNED_SHORT;
  17814. case Engine.TEXTURETYPE_INT:
  17815. return this._gl.INT;
  17816. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17817. return this._gl.UNSIGNED_INT;
  17818. case Engine.TEXTURETYPE_FLOAT:
  17819. return this._gl.FLOAT;
  17820. case Engine.TEXTURETYPE_HALF_FLOAT:
  17821. return this._gl.HALF_FLOAT;
  17822. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  17823. return this._gl.UNSIGNED_SHORT_4_4_4_4;
  17824. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  17825. return this._gl.UNSIGNED_SHORT_5_5_5_1;
  17826. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  17827. return this._gl.UNSIGNED_SHORT_5_6_5;
  17828. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  17829. return this._gl.UNSIGNED_INT_2_10_10_10_REV;
  17830. case Engine.TEXTURETYPE_UNSIGNED_INT_24_8:
  17831. return this._gl.UNSIGNED_INT_24_8;
  17832. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  17833. return this._gl.UNSIGNED_INT_10F_11F_11F_REV;
  17834. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  17835. return this._gl.UNSIGNED_INT_5_9_9_9_REV;
  17836. case Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV:
  17837. return this._gl.FLOAT_32_UNSIGNED_INT_24_8_REV;
  17838. }
  17839. return this._gl.UNSIGNED_BYTE;
  17840. };
  17841. ;
  17842. Engine.prototype._getInternalFormat = function (format) {
  17843. var internalFormat = this._gl.RGBA;
  17844. switch (format) {
  17845. case Engine.TEXTUREFORMAT_ALPHA:
  17846. internalFormat = this._gl.ALPHA;
  17847. break;
  17848. case Engine.TEXTUREFORMAT_LUMINANCE:
  17849. internalFormat = this._gl.LUMINANCE;
  17850. break;
  17851. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17852. internalFormat = this._gl.LUMINANCE_ALPHA;
  17853. break;
  17854. case Engine.TEXTUREFORMAT_RED:
  17855. internalFormat = this._gl.RED;
  17856. break;
  17857. case Engine.TEXTUREFORMAT_RG:
  17858. internalFormat = this._gl.RG;
  17859. break;
  17860. case Engine.TEXTUREFORMAT_RGB:
  17861. internalFormat = this._gl.RGB;
  17862. break;
  17863. case Engine.TEXTUREFORMAT_RGBA:
  17864. internalFormat = this._gl.RGBA;
  17865. break;
  17866. }
  17867. if (this._webGLVersion > 1) {
  17868. switch (format) {
  17869. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17870. internalFormat = this._gl.RED_INTEGER;
  17871. break;
  17872. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17873. internalFormat = this._gl.RG_INTEGER;
  17874. break;
  17875. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17876. internalFormat = this._gl.RGB_INTEGER;
  17877. break;
  17878. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17879. internalFormat = this._gl.RGBA_INTEGER;
  17880. break;
  17881. }
  17882. }
  17883. return internalFormat;
  17884. };
  17885. /** @hidden */
  17886. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17887. if (this._webGLVersion === 1) {
  17888. if (format !== undefined) {
  17889. switch (format) {
  17890. case Engine.TEXTUREFORMAT_ALPHA:
  17891. return this._gl.ALPHA;
  17892. case Engine.TEXTUREFORMAT_LUMINANCE:
  17893. return this._gl.LUMINANCE;
  17894. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17895. return this._gl.LUMINANCE_ALPHA;
  17896. }
  17897. }
  17898. return this._gl.RGBA;
  17899. }
  17900. switch (type) {
  17901. case Engine.TEXTURETYPE_BYTE:
  17902. switch (format) {
  17903. case Engine.TEXTUREFORMAT_RED:
  17904. return this._gl.R8_SNORM;
  17905. case Engine.TEXTUREFORMAT_RG:
  17906. return this._gl.RG8_SNORM;
  17907. case Engine.TEXTUREFORMAT_RGB:
  17908. return this._gl.RGB8_SNORM;
  17909. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17910. return this._gl.R8I;
  17911. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17912. return this._gl.RG8I;
  17913. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17914. return this._gl.RGB8I;
  17915. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17916. return this._gl.RGBA8I;
  17917. default:
  17918. return this._gl.RGBA8_SNORM;
  17919. }
  17920. case Engine.TEXTURETYPE_UNSIGNED_BYTE:
  17921. switch (format) {
  17922. case Engine.TEXTUREFORMAT_RED:
  17923. return this._gl.R8;
  17924. case Engine.TEXTUREFORMAT_RG:
  17925. return this._gl.RG8;
  17926. case Engine.TEXTUREFORMAT_RGB:
  17927. return this._gl.RGB8; // By default. Other possibilities are RGB565, SRGB8.
  17928. case Engine.TEXTUREFORMAT_RGBA:
  17929. return this._gl.RGBA8; // By default. Other possibilities are RGB5_A1, RGBA4, SRGB8_ALPHA8.
  17930. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17931. return this._gl.R8UI;
  17932. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17933. return this._gl.RG8UI;
  17934. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17935. return this._gl.RGB8UI;
  17936. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17937. return this._gl.RGBA8UI;
  17938. default:
  17939. return this._gl.RGBA8;
  17940. }
  17941. case Engine.TEXTURETYPE_SHORT:
  17942. switch (format) {
  17943. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17944. return this._gl.R16I;
  17945. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17946. return this._gl.RG16I;
  17947. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17948. return this._gl.RGB16I;
  17949. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17950. return this._gl.RGBA16I;
  17951. default:
  17952. return this._gl.RGBA16I;
  17953. }
  17954. case Engine.TEXTURETYPE_UNSIGNED_SHORT:
  17955. switch (format) {
  17956. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17957. return this._gl.R16UI;
  17958. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17959. return this._gl.RG16UI;
  17960. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17961. return this._gl.RGB16UI;
  17962. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17963. return this._gl.RGBA16UI;
  17964. default:
  17965. return this._gl.RGBA16UI;
  17966. }
  17967. case Engine.TEXTURETYPE_INT:
  17968. switch (format) {
  17969. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17970. return this._gl.R32I;
  17971. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17972. return this._gl.RG32I;
  17973. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17974. return this._gl.RGB32I;
  17975. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17976. return this._gl.RGBA32I;
  17977. default:
  17978. return this._gl.RGBA32I;
  17979. }
  17980. case Engine.TEXTURETYPE_UNSIGNED_INTEGER: // Refers to UNSIGNED_INT
  17981. switch (format) {
  17982. case Engine.TEXTUREFORMAT_RED_INTEGER:
  17983. return this._gl.R32UI;
  17984. case Engine.TEXTUREFORMAT_RG_INTEGER:
  17985. return this._gl.RG32UI;
  17986. case Engine.TEXTUREFORMAT_RGB_INTEGER:
  17987. return this._gl.RGB32UI;
  17988. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  17989. return this._gl.RGBA32UI;
  17990. default:
  17991. return this._gl.RGBA32UI;
  17992. }
  17993. case Engine.TEXTURETYPE_FLOAT:
  17994. switch (format) {
  17995. case Engine.TEXTUREFORMAT_RED:
  17996. return this._gl.R32F; // By default. Other possibility is R16F.
  17997. case Engine.TEXTUREFORMAT_RG:
  17998. return this._gl.RG32F; // By default. Other possibility is RG16F.
  17999. case Engine.TEXTUREFORMAT_RGB:
  18000. return this._gl.RGB32F; // By default. Other possibilities are RGB16F, R11F_G11F_B10F, RGB9_E5.
  18001. case Engine.TEXTUREFORMAT_RGBA:
  18002. return this._gl.RGBA32F; // By default. Other possibility is RGBA16F.
  18003. default:
  18004. return this._gl.RGBA32F;
  18005. }
  18006. case Engine.TEXTURETYPE_HALF_FLOAT:
  18007. switch (format) {
  18008. case Engine.TEXTUREFORMAT_RED:
  18009. return this._gl.R16F;
  18010. case Engine.TEXTUREFORMAT_RG:
  18011. return this._gl.RG16F;
  18012. case Engine.TEXTUREFORMAT_RGB:
  18013. return this._gl.RGB16F; // By default. Other possibilities are R11F_G11F_B10F, RGB9_E5.
  18014. case Engine.TEXTUREFORMAT_RGBA:
  18015. return this._gl.RGBA16F;
  18016. default:
  18017. return this._gl.RGBA16F;
  18018. }
  18019. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5:
  18020. return this._gl.RGB565;
  18021. case Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV:
  18022. return this._gl.R11F_G11F_B10F;
  18023. case Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV:
  18024. return this._gl.RGB9_E5;
  18025. case Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4:
  18026. return this._gl.RGBA4;
  18027. case Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1:
  18028. return this._gl.RGB5_A1;
  18029. case Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV:
  18030. switch (format) {
  18031. case Engine.TEXTUREFORMAT_RGBA:
  18032. return this._gl.RGB10_A2; // By default. Other possibility is RGB5_A1.
  18033. case Engine.TEXTUREFORMAT_RGBA_INTEGER:
  18034. return this._gl.RGB10_A2UI;
  18035. default:
  18036. return this._gl.RGB10_A2;
  18037. }
  18038. }
  18039. return this._gl.RGBA8;
  18040. };
  18041. ;
  18042. /** @hidden */
  18043. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  18044. if (type === Engine.TEXTURETYPE_FLOAT) {
  18045. return this._gl.RGBA32F;
  18046. }
  18047. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  18048. return this._gl.RGBA16F;
  18049. }
  18050. return this._gl.RGBA8;
  18051. };
  18052. ;
  18053. /** @hidden */
  18054. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  18055. var _this = this;
  18056. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  18057. this._activeRequests.push(request);
  18058. request.onCompleteObservable.add(function (request) {
  18059. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  18060. });
  18061. return request;
  18062. };
  18063. /** @hidden */
  18064. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  18065. var _this = this;
  18066. return new Promise(function (resolve, reject) {
  18067. _this._loadFile(url, function (data) {
  18068. resolve(data);
  18069. }, undefined, database, useArrayBuffer, function (request, exception) {
  18070. reject(exception);
  18071. });
  18072. });
  18073. };
  18074. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  18075. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  18076. var onload = function (data) {
  18077. loadedFiles[index] = data;
  18078. loadedFiles._internalCount++;
  18079. if (loadedFiles._internalCount === 6) {
  18080. onfinish(loadedFiles);
  18081. }
  18082. };
  18083. var onerror = function (request, exception) {
  18084. if (onErrorCallBack && request) {
  18085. onErrorCallBack(request.status + " " + request.statusText, exception);
  18086. }
  18087. };
  18088. this._loadFile(url, onload, undefined, undefined, true, onerror);
  18089. };
  18090. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  18091. if (onError === void 0) { onError = null; }
  18092. var loadedFiles = [];
  18093. loadedFiles._internalCount = 0;
  18094. for (var index = 0; index < 6; index++) {
  18095. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  18096. }
  18097. };
  18098. // Statics
  18099. /**
  18100. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  18101. * @returns true if the engine can be created
  18102. * @ignorenaming
  18103. */
  18104. Engine.isSupported = function () {
  18105. try {
  18106. var tempcanvas = document.createElement("canvas");
  18107. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  18108. return gl != null && !!window.WebGLRenderingContext;
  18109. }
  18110. catch (e) {
  18111. return false;
  18112. }
  18113. };
  18114. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  18115. Engine.ExceptionList = [
  18116. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  18117. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18118. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  18119. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18120. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  18121. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  18122. ];
  18123. /** Gets the list of created engines */
  18124. Engine.Instances = new Array();
  18125. /**
  18126. * Hidden
  18127. */
  18128. Engine._TextureLoaders = [];
  18129. // Const statics
  18130. /** Defines that alpha blending is disabled */
  18131. Engine.ALPHA_DISABLE = 0;
  18132. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  18133. Engine.ALPHA_ADD = 1;
  18134. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  18135. Engine.ALPHA_COMBINE = 2;
  18136. /** Defines that alpha blending to DEST - SRC * DEST */
  18137. Engine.ALPHA_SUBTRACT = 3;
  18138. /** Defines that alpha blending to SRC * DEST */
  18139. Engine.ALPHA_MULTIPLY = 4;
  18140. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  18141. Engine.ALPHA_MAXIMIZED = 5;
  18142. /** Defines that alpha blending to SRC + DEST */
  18143. Engine.ALPHA_ONEONE = 6;
  18144. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  18145. Engine.ALPHA_PREMULTIPLIED = 7;
  18146. /**
  18147. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  18148. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  18149. */
  18150. Engine.ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  18151. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  18152. Engine.ALPHA_INTERPOLATE = 9;
  18153. /**
  18154. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  18155. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  18156. */
  18157. Engine.ALPHA_SCREENMODE = 10;
  18158. /** Defines that the ressource is not delayed*/
  18159. Engine.DELAYLOADSTATE_NONE = 0;
  18160. /** Defines that the ressource was successfully delay loaded */
  18161. Engine.DELAYLOADSTATE_LOADED = 1;
  18162. /** Defines that the ressource is currently delay loading */
  18163. Engine.DELAYLOADSTATE_LOADING = 2;
  18164. /** Defines that the ressource is delayed and has not started loading */
  18165. Engine.DELAYLOADSTATE_NOTLOADED = 4;
  18166. // Depht or Stencil test Constants.
  18167. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  18168. Engine.NEVER = 0x0200;
  18169. /** 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 */
  18170. Engine.ALWAYS = 0x0207;
  18171. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  18172. Engine.LESS = 0x0201;
  18173. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  18174. Engine.EQUAL = 0x0202;
  18175. /** 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 */
  18176. Engine.LEQUAL = 0x0203;
  18177. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  18178. Engine.GREATER = 0x0204;
  18179. /** 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 */
  18180. Engine.GEQUAL = 0x0206;
  18181. /** 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 */
  18182. Engine.NOTEQUAL = 0x0205;
  18183. // Stencil Actions Constants.
  18184. /** Passed to stencilOperation to specify that stencil value must be kept */
  18185. Engine.KEEP = 0x1E00;
  18186. /** Passed to stencilOperation to specify that stencil value must be replaced */
  18187. Engine.REPLACE = 0x1E01;
  18188. /** Passed to stencilOperation to specify that stencil value must be incremented */
  18189. Engine.INCR = 0x1E02;
  18190. /** Passed to stencilOperation to specify that stencil value must be decremented */
  18191. Engine.DECR = 0x1E03;
  18192. /** Passed to stencilOperation to specify that stencil value must be inverted */
  18193. Engine.INVERT = 0x150A;
  18194. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  18195. Engine.INCR_WRAP = 0x8507;
  18196. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  18197. Engine.DECR_WRAP = 0x8508;
  18198. /** Texture is not repeating outside of 0..1 UVs */
  18199. Engine.TEXTURE_CLAMP_ADDRESSMODE = 0;
  18200. /** Texture is repeating outside of 0..1 UVs */
  18201. Engine.TEXTURE_WRAP_ADDRESSMODE = 1;
  18202. /** Texture is repeating and mirrored */
  18203. Engine.TEXTURE_MIRROR_ADDRESSMODE = 2;
  18204. /** ALPHA */
  18205. Engine.TEXTUREFORMAT_ALPHA = 0;
  18206. /** LUMINANCE */
  18207. Engine.TEXTUREFORMAT_LUMINANCE = 1;
  18208. /** LUMINANCE_ALPHA */
  18209. Engine.TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  18210. /** RGB */
  18211. Engine.TEXTUREFORMAT_RGB = 4;
  18212. /** RGBA */
  18213. Engine.TEXTUREFORMAT_RGBA = 5;
  18214. /** RED */
  18215. Engine.TEXTUREFORMAT_RED = 6;
  18216. /** RED (2nd reference) */
  18217. Engine.TEXTUREFORMAT_R = 6;
  18218. /** RG */
  18219. Engine.TEXTUREFORMAT_RG = 7;
  18220. /** RED_INTEGER */
  18221. Engine.TEXTUREFORMAT_RED_INTEGER = 8;
  18222. /** RED_INTEGER (2nd reference) */
  18223. Engine.TEXTUREFORMAT_R_INTEGER = 8;
  18224. /** RG_INTEGER */
  18225. Engine.TEXTUREFORMAT_RG_INTEGER = 9;
  18226. /** RGB_INTEGER */
  18227. Engine.TEXTUREFORMAT_RGB_INTEGER = 10;
  18228. /** RGBA_INTEGER */
  18229. Engine.TEXTUREFORMAT_RGBA_INTEGER = 11;
  18230. /** UNSIGNED_BYTE */
  18231. Engine.TEXTURETYPE_UNSIGNED_BYTE = 0;
  18232. /** UNSIGNED_BYTE (2nd reference) */
  18233. Engine.TEXTURETYPE_UNSIGNED_INT = 0;
  18234. /** FLOAT */
  18235. Engine.TEXTURETYPE_FLOAT = 1;
  18236. /** HALF_FLOAT */
  18237. Engine.TEXTURETYPE_HALF_FLOAT = 2;
  18238. /** BYTE */
  18239. Engine.TEXTURETYPE_BYTE = 3;
  18240. /** SHORT */
  18241. Engine.TEXTURETYPE_SHORT = 4;
  18242. /** UNSIGNED_SHORT */
  18243. Engine.TEXTURETYPE_UNSIGNED_SHORT = 5;
  18244. /** INT */
  18245. Engine.TEXTURETYPE_INT = 6;
  18246. /** UNSIGNED_INT */
  18247. Engine.TEXTURETYPE_UNSIGNED_INTEGER = 7;
  18248. /** UNSIGNED_SHORT_4_4_4_4 */
  18249. Engine.TEXTURETYPE_UNSIGNED_SHORT_4_4_4_4 = 8;
  18250. /** UNSIGNED_SHORT_5_5_5_1 */
  18251. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_5_5_1 = 9;
  18252. /** UNSIGNED_SHORT_5_6_5 */
  18253. Engine.TEXTURETYPE_UNSIGNED_SHORT_5_6_5 = 10;
  18254. /** UNSIGNED_INT_2_10_10_10_REV */
  18255. Engine.TEXTURETYPE_UNSIGNED_INT_2_10_10_10_REV = 11;
  18256. /** UNSIGNED_INT_24_8 */
  18257. Engine.TEXTURETYPE_UNSIGNED_INT_24_8 = 12;
  18258. /** UNSIGNED_INT_10F_11F_11F_REV */
  18259. Engine.TEXTURETYPE_UNSIGNED_INT_10F_11F_11F_REV = 13;
  18260. /** UNSIGNED_INT_5_9_9_9_REV */
  18261. Engine.TEXTURETYPE_UNSIGNED_INT_5_9_9_9_REV = 14;
  18262. /** FLOAT_32_UNSIGNED_INT_24_8_REV */
  18263. Engine.TEXTURETYPE_FLOAT_32_UNSIGNED_INT_24_8_REV = 15;
  18264. /** nearest is mag = nearest and min = nearest and mip = linear */
  18265. Engine.TEXTURE_NEAREST_SAMPLINGMODE = 1;
  18266. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18267. Engine.TEXTURE_BILINEAR_SAMPLINGMODE = 2;
  18268. /** Trilinear is mag = linear and min = linear and mip = linear */
  18269. Engine.TEXTURE_TRILINEAR_SAMPLINGMODE = 3;
  18270. /** nearest is mag = nearest and min = nearest and mip = linear */
  18271. Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR = 1;
  18272. /** Bilinear is mag = linear and min = linear and mip = nearest */
  18273. Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST = 2;
  18274. /** Trilinear is mag = linear and min = linear and mip = linear */
  18275. Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR = 3;
  18276. /** mag = nearest and min = nearest and mip = nearest */
  18277. Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST = 4;
  18278. /** mag = nearest and min = linear and mip = nearest */
  18279. Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST = 5;
  18280. /** mag = nearest and min = linear and mip = linear */
  18281. Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR = 6;
  18282. /** mag = nearest and min = linear and mip = none */
  18283. Engine.TEXTURE_NEAREST_LINEAR = 7;
  18284. /** mag = nearest and min = nearest and mip = none */
  18285. Engine.TEXTURE_NEAREST_NEAREST = 8;
  18286. /** mag = linear and min = nearest and mip = nearest */
  18287. Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST = 9;
  18288. /** mag = linear and min = nearest and mip = linear */
  18289. Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR = 10;
  18290. /** mag = linear and min = linear and mip = none */
  18291. Engine.TEXTURE_LINEAR_LINEAR = 11;
  18292. /** mag = linear and min = nearest and mip = none */
  18293. Engine.TEXTURE_LINEAR_NEAREST = 12;
  18294. /** Explicit coordinates mode */
  18295. Engine.TEXTURE_EXPLICIT_MODE = 0;
  18296. /** Spherical coordinates mode */
  18297. Engine.TEXTURE_SPHERICAL_MODE = 1;
  18298. /** Planar coordinates mode */
  18299. Engine.TEXTURE_PLANAR_MODE = 2;
  18300. /** Cubic coordinates mode */
  18301. Engine.TEXTURE_CUBIC_MODE = 3;
  18302. /** Projection coordinates mode */
  18303. Engine.TEXTURE_PROJECTION_MODE = 4;
  18304. /** Skybox coordinates mode */
  18305. Engine.TEXTURE_SKYBOX_MODE = 5;
  18306. /** Inverse Cubic coordinates mode */
  18307. Engine.TEXTURE_INVCUBIC_MODE = 6;
  18308. /** Equirectangular coordinates mode */
  18309. Engine.TEXTURE_EQUIRECTANGULAR_MODE = 7;
  18310. /** Equirectangular Fixed coordinates mode */
  18311. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE = 8;
  18312. /** Equirectangular Fixed Mirrored coordinates mode */
  18313. Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  18314. // Texture rescaling mode
  18315. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  18316. Engine.SCALEMODE_FLOOR = 1;
  18317. /** Defines that texture rescaling will look for the nearest power of 2 size */
  18318. Engine.SCALEMODE_NEAREST = 2;
  18319. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  18320. Engine.SCALEMODE_CEILING = 3;
  18321. // Updatable statics so stick with vars here
  18322. /**
  18323. * Gets or sets the epsilon value used by collision engine
  18324. */
  18325. Engine.CollisionsEpsilon = 0.001;
  18326. /**
  18327. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  18328. */
  18329. Engine.CodeRepository = "src/";
  18330. /**
  18331. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  18332. */
  18333. Engine.ShadersRepository = "src/Shaders/";
  18334. return Engine;
  18335. }());
  18336. BABYLON.Engine = Engine;
  18337. })(BABYLON || (BABYLON = {}));
  18338. //# sourceMappingURL=babylon.engine.js.map
  18339. var BABYLON;
  18340. (function (BABYLON) {
  18341. /**
  18342. * Node is the basic class for all scene objects (Mesh, Light, Camera.)
  18343. */
  18344. var Node = /** @class */ (function () {
  18345. /**
  18346. * Creates a new Node
  18347. * @param name the name and id to be given to this node
  18348. * @param scene the scene this node will be added to
  18349. */
  18350. function Node(name, scene) {
  18351. if (scene === void 0) { scene = null; }
  18352. /**
  18353. * Gets or sets a string used to store user defined state for the node
  18354. */
  18355. this.state = "";
  18356. /**
  18357. * Gets or sets an object used to store user defined information for the node
  18358. */
  18359. this.metadata = null;
  18360. /**
  18361. * Gets or sets a boolean used to define if the node must be serialized
  18362. */
  18363. this.doNotSerialize = false;
  18364. /** @hidden */
  18365. this._isDisposed = false;
  18366. /**
  18367. * Gets a list of Animations associated with the node
  18368. */
  18369. this.animations = new Array();
  18370. this._ranges = {};
  18371. this._isEnabled = true;
  18372. this._isParentEnabled = true;
  18373. this._isReady = true;
  18374. /** @hidden */
  18375. this._currentRenderId = -1;
  18376. this._parentRenderId = -1;
  18377. this._childRenderId = -1;
  18378. /** @hidden */
  18379. this._worldMatrix = BABYLON.Matrix.Identity();
  18380. /** @hidden */
  18381. this._worldMatrixDeterminant = 0;
  18382. /** @hidden */
  18383. this._sceneRootNodesIndex = -1;
  18384. this._animationPropertiesOverride = null;
  18385. /**
  18386. * An event triggered when the mesh is disposed
  18387. */
  18388. this.onDisposeObservable = new BABYLON.Observable();
  18389. // Behaviors
  18390. this._behaviors = new Array();
  18391. this.name = name;
  18392. this.id = name;
  18393. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  18394. this.uniqueId = this._scene.getUniqueId();
  18395. this._initCache();
  18396. this.addToSceneRootNodes();
  18397. }
  18398. /**
  18399. * Add a new node constructor
  18400. * @param type defines the type name of the node to construct
  18401. * @param constructorFunc defines the constructor function
  18402. */
  18403. Node.AddNodeConstructor = function (type, constructorFunc) {
  18404. this._NodeConstructors[type] = constructorFunc;
  18405. };
  18406. /**
  18407. * Returns a node constructor based on type name
  18408. * @param type defines the type name
  18409. * @param name defines the new node name
  18410. * @param scene defines the hosting scene
  18411. * @param options defines optional options to transmit to constructors
  18412. * @returns the new constructor or null
  18413. */
  18414. Node.Construct = function (type, name, scene, options) {
  18415. var constructorFunc = this._NodeConstructors[type];
  18416. if (!constructorFunc) {
  18417. return null;
  18418. }
  18419. return constructorFunc(name, scene, options);
  18420. };
  18421. /**
  18422. * Gets a boolean indicating if the node has been disposed
  18423. * @returns true if the node was disposed
  18424. */
  18425. Node.prototype.isDisposed = function () {
  18426. return this._isDisposed;
  18427. };
  18428. Object.defineProperty(Node.prototype, "parent", {
  18429. get: function () {
  18430. return this._parentNode;
  18431. },
  18432. /**
  18433. * Gets or sets the parent of the node
  18434. */
  18435. set: function (parent) {
  18436. if (this._parentNode === parent) {
  18437. return;
  18438. }
  18439. var previousParentNode = this._parentNode;
  18440. // Remove self from list of children of parent
  18441. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  18442. var index = this._parentNode._children.indexOf(this);
  18443. if (index !== -1) {
  18444. this._parentNode._children.splice(index, 1);
  18445. }
  18446. if (!parent) {
  18447. this.addToSceneRootNodes();
  18448. }
  18449. }
  18450. // Store new parent
  18451. this._parentNode = parent;
  18452. // Add as child to new parent
  18453. if (this._parentNode) {
  18454. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  18455. this._parentNode._children = new Array();
  18456. }
  18457. this._parentNode._children.push(this);
  18458. if (!previousParentNode) {
  18459. this.removeFromSceneRootNodes();
  18460. }
  18461. }
  18462. // Enabled state
  18463. this._syncParentEnabledState();
  18464. },
  18465. enumerable: true,
  18466. configurable: true
  18467. });
  18468. Node.prototype.addToSceneRootNodes = function () {
  18469. if (this._sceneRootNodesIndex === -1) {
  18470. this._sceneRootNodesIndex = this._scene.rootNodes.length;
  18471. this._scene.rootNodes.push(this);
  18472. }
  18473. };
  18474. Node.prototype.removeFromSceneRootNodes = function () {
  18475. if (this._sceneRootNodesIndex !== -1) {
  18476. var rootNodes = this._scene.rootNodes;
  18477. var lastIdx = rootNodes.length - 1;
  18478. rootNodes[this._sceneRootNodesIndex] = rootNodes[lastIdx];
  18479. rootNodes[this._sceneRootNodesIndex]._sceneRootNodesIndex = this._sceneRootNodesIndex;
  18480. this._scene.rootNodes.pop();
  18481. this._sceneRootNodesIndex = -1;
  18482. }
  18483. };
  18484. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  18485. /**
  18486. * Gets or sets the animation properties override
  18487. */
  18488. get: function () {
  18489. if (!this._animationPropertiesOverride) {
  18490. return this._scene.animationPropertiesOverride;
  18491. }
  18492. return this._animationPropertiesOverride;
  18493. },
  18494. set: function (value) {
  18495. this._animationPropertiesOverride = value;
  18496. },
  18497. enumerable: true,
  18498. configurable: true
  18499. });
  18500. /**
  18501. * Gets a string idenfifying the name of the class
  18502. * @returns "Node" string
  18503. */
  18504. Node.prototype.getClassName = function () {
  18505. return "Node";
  18506. };
  18507. Object.defineProperty(Node.prototype, "onDispose", {
  18508. /**
  18509. * Sets a callback that will be raised when the node will be disposed
  18510. */
  18511. set: function (callback) {
  18512. if (this._onDisposeObserver) {
  18513. this.onDisposeObservable.remove(this._onDisposeObserver);
  18514. }
  18515. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  18516. },
  18517. enumerable: true,
  18518. configurable: true
  18519. });
  18520. /**
  18521. * Gets the scene of the node
  18522. * @returns a scene
  18523. */
  18524. Node.prototype.getScene = function () {
  18525. return this._scene;
  18526. };
  18527. /**
  18528. * Gets the engine of the node
  18529. * @returns a Engine
  18530. */
  18531. Node.prototype.getEngine = function () {
  18532. return this._scene.getEngine();
  18533. };
  18534. /**
  18535. * Attach a behavior to the node
  18536. * @see http://doc.babylonjs.com/features/behaviour
  18537. * @param behavior defines the behavior to attach
  18538. * @param attachImmediately defines that the behavior must be attached even if the scene is still loading
  18539. * @returns the current Node
  18540. */
  18541. Node.prototype.addBehavior = function (behavior, attachImmediately) {
  18542. var _this = this;
  18543. if (attachImmediately === void 0) { attachImmediately = false; }
  18544. var index = this._behaviors.indexOf(behavior);
  18545. if (index !== -1) {
  18546. return this;
  18547. }
  18548. behavior.init();
  18549. if (this._scene.isLoading && !attachImmediately) {
  18550. // We defer the attach when the scene will be loaded
  18551. this._scene.onDataLoadedObservable.addOnce(function () {
  18552. behavior.attach(_this);
  18553. });
  18554. }
  18555. else {
  18556. behavior.attach(this);
  18557. }
  18558. this._behaviors.push(behavior);
  18559. return this;
  18560. };
  18561. /**
  18562. * Remove an attached behavior
  18563. * @see http://doc.babylonjs.com/features/behaviour
  18564. * @param behavior defines the behavior to attach
  18565. * @returns the current Node
  18566. */
  18567. Node.prototype.removeBehavior = function (behavior) {
  18568. var index = this._behaviors.indexOf(behavior);
  18569. if (index === -1) {
  18570. return this;
  18571. }
  18572. this._behaviors[index].detach();
  18573. this._behaviors.splice(index, 1);
  18574. return this;
  18575. };
  18576. Object.defineProperty(Node.prototype, "behaviors", {
  18577. /**
  18578. * Gets the list of attached behaviors
  18579. * @see http://doc.babylonjs.com/features/behaviour
  18580. */
  18581. get: function () {
  18582. return this._behaviors;
  18583. },
  18584. enumerable: true,
  18585. configurable: true
  18586. });
  18587. /**
  18588. * Gets an attached behavior by name
  18589. * @param name defines the name of the behavior to look for
  18590. * @see http://doc.babylonjs.com/features/behaviour
  18591. * @returns null if behavior was not found else the requested behavior
  18592. */
  18593. Node.prototype.getBehaviorByName = function (name) {
  18594. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  18595. var behavior = _a[_i];
  18596. if (behavior.name === name) {
  18597. return behavior;
  18598. }
  18599. }
  18600. return null;
  18601. };
  18602. /**
  18603. * Returns the latest update of the World matrix
  18604. * @returns a Matrix
  18605. */
  18606. Node.prototype.getWorldMatrix = function () {
  18607. if (this._currentRenderId !== this._scene.getRenderId()) {
  18608. this.computeWorldMatrix();
  18609. }
  18610. return this._worldMatrix;
  18611. };
  18612. /** @hidden */
  18613. Node.prototype._getWorldMatrixDeterminant = function () {
  18614. return this._worldMatrixDeterminant;
  18615. };
  18616. Object.defineProperty(Node.prototype, "worldMatrixFromCache", {
  18617. /**
  18618. * Returns directly the latest state of the mesh World matrix.
  18619. * A Matrix is returned.
  18620. */
  18621. get: function () {
  18622. return this._worldMatrix;
  18623. },
  18624. enumerable: true,
  18625. configurable: true
  18626. });
  18627. // override it in derived class if you add new variables to the cache
  18628. // and call the parent class method
  18629. /** @hidden */
  18630. Node.prototype._initCache = function () {
  18631. this._cache = {};
  18632. this._cache.parent = undefined;
  18633. };
  18634. /** @hidden */
  18635. Node.prototype.updateCache = function (force) {
  18636. if (!force && this.isSynchronized())
  18637. return;
  18638. this._cache.parent = this.parent;
  18639. this._updateCache();
  18640. };
  18641. // override it in derived class if you add new variables to the cache
  18642. // and call the parent class method if !ignoreParentClass
  18643. /** @hidden */
  18644. Node.prototype._updateCache = function (ignoreParentClass) {
  18645. };
  18646. // override it in derived class if you add new variables to the cache
  18647. /** @hidden */
  18648. Node.prototype._isSynchronized = function () {
  18649. return true;
  18650. };
  18651. /** @hidden */
  18652. Node.prototype._markSyncedWithParent = function () {
  18653. if (this._parentNode) {
  18654. this._parentRenderId = this._parentNode._childRenderId;
  18655. }
  18656. };
  18657. /** @hidden */
  18658. Node.prototype.isSynchronizedWithParent = function () {
  18659. if (!this._parentNode) {
  18660. return true;
  18661. }
  18662. if (this._parentRenderId !== this._parentNode._childRenderId) {
  18663. return false;
  18664. }
  18665. return this._parentNode.isSynchronized();
  18666. };
  18667. /** @hidden */
  18668. Node.prototype.isSynchronized = function () {
  18669. if (this._cache.parent != this._parentNode) {
  18670. this._cache.parent = this._parentNode;
  18671. return false;
  18672. }
  18673. if (this._parentNode && !this.isSynchronizedWithParent()) {
  18674. return false;
  18675. }
  18676. return this._isSynchronized();
  18677. };
  18678. /**
  18679. * Is this node ready to be used/rendered
  18680. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18681. * @return true if the node is ready
  18682. */
  18683. Node.prototype.isReady = function (completeCheck) {
  18684. if (completeCheck === void 0) { completeCheck = false; }
  18685. return this._isReady;
  18686. };
  18687. /**
  18688. * Is this node enabled?
  18689. * 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
  18690. * @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
  18691. * @return whether this node (and its parent) is enabled
  18692. */
  18693. Node.prototype.isEnabled = function (checkAncestors) {
  18694. if (checkAncestors === void 0) { checkAncestors = true; }
  18695. if (checkAncestors === false) {
  18696. return this._isEnabled;
  18697. }
  18698. if (!this._isEnabled) {
  18699. return false;
  18700. }
  18701. return this._isParentEnabled;
  18702. };
  18703. /** @hidden */
  18704. Node.prototype._syncParentEnabledState = function () {
  18705. this._isParentEnabled = this._parentNode ? this._parentNode.isEnabled() : true;
  18706. if (this._children) {
  18707. this._children.forEach(function (c) {
  18708. c._syncParentEnabledState(); // Force children to update accordingly
  18709. });
  18710. }
  18711. };
  18712. /**
  18713. * Set the enabled state of this node
  18714. * @param value defines the new enabled state
  18715. */
  18716. Node.prototype.setEnabled = function (value) {
  18717. this._isEnabled = value;
  18718. this._syncParentEnabledState();
  18719. };
  18720. /**
  18721. * Is this node a descendant of the given node?
  18722. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18723. * @param ancestor defines the parent node to inspect
  18724. * @returns a boolean indicating if this node is a descendant of the given node
  18725. */
  18726. Node.prototype.isDescendantOf = function (ancestor) {
  18727. if (this.parent) {
  18728. if (this.parent === ancestor) {
  18729. return true;
  18730. }
  18731. return this.parent.isDescendantOf(ancestor);
  18732. }
  18733. return false;
  18734. };
  18735. /** @hidden */
  18736. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18737. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18738. if (!this._children) {
  18739. return;
  18740. }
  18741. for (var index = 0; index < this._children.length; index++) {
  18742. var item = this._children[index];
  18743. if (!predicate || predicate(item)) {
  18744. results.push(item);
  18745. }
  18746. if (!directDescendantsOnly) {
  18747. item._getDescendants(results, false, predicate);
  18748. }
  18749. }
  18750. };
  18751. /**
  18752. * Will return all nodes that have this node as ascendant
  18753. * @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
  18754. * @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
  18755. * @return all children nodes of all types
  18756. */
  18757. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18758. var results = new Array();
  18759. this._getDescendants(results, directDescendantsOnly, predicate);
  18760. return results;
  18761. };
  18762. /**
  18763. * Get all child-meshes of this node
  18764. * @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
  18765. * @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
  18766. * @returns an array of AbstractMesh
  18767. */
  18768. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18769. var results = [];
  18770. this._getDescendants(results, directDescendantsOnly, function (node) {
  18771. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18772. });
  18773. return results;
  18774. };
  18775. /**
  18776. * Get all child-transformNodes of this node
  18777. * @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
  18778. * @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
  18779. * @returns an array of TransformNode
  18780. */
  18781. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18782. var results = [];
  18783. this._getDescendants(results, directDescendantsOnly, function (node) {
  18784. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18785. });
  18786. return results;
  18787. };
  18788. /**
  18789. * Get all direct children of this node
  18790. * @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
  18791. * @returns an array of Node
  18792. */
  18793. Node.prototype.getChildren = function (predicate) {
  18794. return this.getDescendants(true, predicate);
  18795. };
  18796. /** @hidden */
  18797. Node.prototype._setReady = function (state) {
  18798. if (state === this._isReady) {
  18799. return;
  18800. }
  18801. if (!state) {
  18802. this._isReady = false;
  18803. return;
  18804. }
  18805. if (this.onReady) {
  18806. this.onReady(this);
  18807. }
  18808. this._isReady = true;
  18809. };
  18810. /**
  18811. * Get an animation by name
  18812. * @param name defines the name of the animation to look for
  18813. * @returns null if not found else the requested animation
  18814. */
  18815. Node.prototype.getAnimationByName = function (name) {
  18816. for (var i = 0; i < this.animations.length; i++) {
  18817. var animation = this.animations[i];
  18818. if (animation.name === name) {
  18819. return animation;
  18820. }
  18821. }
  18822. return null;
  18823. };
  18824. /**
  18825. * Creates an animation range for this node
  18826. * @param name defines the name of the range
  18827. * @param from defines the starting key
  18828. * @param to defines the end key
  18829. */
  18830. Node.prototype.createAnimationRange = function (name, from, to) {
  18831. // check name not already in use
  18832. if (!this._ranges[name]) {
  18833. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18834. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18835. if (this.animations[i]) {
  18836. this.animations[i].createRange(name, from, to);
  18837. }
  18838. }
  18839. }
  18840. };
  18841. /**
  18842. * Delete a specific animation range
  18843. * @param name defines the name of the range to delete
  18844. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18845. */
  18846. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18847. if (deleteFrames === void 0) { deleteFrames = true; }
  18848. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18849. if (this.animations[i]) {
  18850. this.animations[i].deleteRange(name, deleteFrames);
  18851. }
  18852. }
  18853. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18854. };
  18855. /**
  18856. * Get an animation range by name
  18857. * @param name defines the name of the animation range to look for
  18858. * @returns null if not found else the requested animation range
  18859. */
  18860. Node.prototype.getAnimationRange = function (name) {
  18861. return this._ranges[name];
  18862. };
  18863. /**
  18864. * Will start the animation sequence
  18865. * @param name defines the range frames for animation sequence
  18866. * @param loop defines if the animation should loop (false by default)
  18867. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18868. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18869. * @returns the object created for this animation. If range does not exist, it will return null
  18870. */
  18871. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18872. var range = this.getAnimationRange(name);
  18873. if (!range) {
  18874. return null;
  18875. }
  18876. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18877. };
  18878. /**
  18879. * Serialize animation ranges into a JSON compatible object
  18880. * @returns serialization object
  18881. */
  18882. Node.prototype.serializeAnimationRanges = function () {
  18883. var serializationRanges = [];
  18884. for (var name in this._ranges) {
  18885. var localRange = this._ranges[name];
  18886. if (!localRange) {
  18887. continue;
  18888. }
  18889. var range = {};
  18890. range.name = name;
  18891. range.from = localRange.from;
  18892. range.to = localRange.to;
  18893. serializationRanges.push(range);
  18894. }
  18895. return serializationRanges;
  18896. };
  18897. /**
  18898. * Computes the world matrix of the node
  18899. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18900. * @returns the world matrix
  18901. */
  18902. Node.prototype.computeWorldMatrix = function (force) {
  18903. if (!this._worldMatrix) {
  18904. this._worldMatrix = BABYLON.Matrix.Identity();
  18905. }
  18906. return this._worldMatrix;
  18907. };
  18908. /**
  18909. * Releases resources associated with this node.
  18910. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18911. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18912. */
  18913. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18914. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18915. if (!doNotRecurse) {
  18916. var nodes = this.getDescendants(true);
  18917. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18918. var node = nodes_1[_i];
  18919. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18920. }
  18921. }
  18922. else {
  18923. var transformNodes = this.getChildTransformNodes(true);
  18924. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18925. var transformNode = transformNodes_1[_a];
  18926. transformNode.parent = null;
  18927. transformNode.computeWorldMatrix(true);
  18928. }
  18929. }
  18930. if (!this.parent) {
  18931. this.removeFromSceneRootNodes();
  18932. }
  18933. else {
  18934. this.parent = null;
  18935. }
  18936. // Callback
  18937. this.onDisposeObservable.notifyObservers(this);
  18938. this.onDisposeObservable.clear();
  18939. // Behaviors
  18940. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18941. var behavior = _c[_b];
  18942. behavior.detach();
  18943. }
  18944. this._behaviors = [];
  18945. this._isDisposed = true;
  18946. };
  18947. /**
  18948. * Parse animation range data from a serialization object and store them into a given node
  18949. * @param node defines where to store the animation ranges
  18950. * @param parsedNode defines the serialization object to read data from
  18951. * @param scene defines the hosting scene
  18952. */
  18953. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18954. if (parsedNode.ranges) {
  18955. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18956. var data = parsedNode.ranges[index];
  18957. node.createAnimationRange(data.name, data.from, data.to);
  18958. }
  18959. }
  18960. };
  18961. Node._NodeConstructors = {};
  18962. __decorate([
  18963. BABYLON.serialize()
  18964. ], Node.prototype, "name", void 0);
  18965. __decorate([
  18966. BABYLON.serialize()
  18967. ], Node.prototype, "id", void 0);
  18968. __decorate([
  18969. BABYLON.serialize()
  18970. ], Node.prototype, "uniqueId", void 0);
  18971. __decorate([
  18972. BABYLON.serialize()
  18973. ], Node.prototype, "state", void 0);
  18974. __decorate([
  18975. BABYLON.serialize()
  18976. ], Node.prototype, "metadata", void 0);
  18977. return Node;
  18978. }());
  18979. BABYLON.Node = Node;
  18980. })(BABYLON || (BABYLON = {}));
  18981. //# sourceMappingURL=babylon.node.js.map
  18982. var BABYLON;
  18983. (function (BABYLON) {
  18984. // This matrix is used as a value to reset the bounding box.
  18985. var _identityMatrix = BABYLON.Matrix.Identity();
  18986. /**
  18987. * Class used to store bounding sphere information
  18988. */
  18989. var BoundingSphere = /** @class */ (function () {
  18990. /**
  18991. * Creates a new bounding sphere
  18992. * @param min defines the minimum vector (in local space)
  18993. * @param max defines the maximum vector (in local space)
  18994. */
  18995. function BoundingSphere(min, max) {
  18996. /**
  18997. * Gets the center of the bounding sphere in local space
  18998. */
  18999. this.center = BABYLON.Vector3.Zero();
  19000. /**
  19001. * Gets the center of the bounding sphere in world space
  19002. */
  19003. this.centerWorld = BABYLON.Vector3.Zero();
  19004. /**
  19005. * Gets the minimum vector in local space
  19006. */
  19007. this.minimum = BABYLON.Vector3.Zero();
  19008. /**
  19009. * Gets the maximum vector in local space
  19010. */
  19011. this.maximum = BABYLON.Vector3.Zero();
  19012. this.reConstruct(min, max);
  19013. }
  19014. /**
  19015. * Recreates the entire bounding sphere from scratch
  19016. * @param min defines the new minimum vector (in local space)
  19017. * @param max defines the new maximum vector (in local space)
  19018. */
  19019. BoundingSphere.prototype.reConstruct = function (min, max) {
  19020. this.minimum.copyFrom(min);
  19021. this.maximum.copyFrom(max);
  19022. var distance = BABYLON.Vector3.Distance(min, max);
  19023. BABYLON.Vector3.LerpToRef(min, max, 0.5, this.center);
  19024. this.radius = distance * 0.5;
  19025. this.centerWorld.set(0, 0, 0);
  19026. this._update(_identityMatrix);
  19027. };
  19028. /**
  19029. * Scale the current bounding sphere by applying a scale factor
  19030. * @param factor defines the scale factor to apply
  19031. * @returns the current bounding box
  19032. */
  19033. BoundingSphere.prototype.scale = function (factor) {
  19034. var newRadius = this.radius * factor;
  19035. var tempRadiusVector = BABYLON.Tmp.Vector3[0].set(newRadius, newRadius, newRadius);
  19036. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(tempRadiusVector);
  19037. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(tempRadiusVector);
  19038. this.reConstruct(min, max);
  19039. return this;
  19040. };
  19041. // Methods
  19042. /** @hidden */
  19043. BoundingSphere.prototype._update = function (world) {
  19044. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  19045. var tempVector = BABYLON.Tmp.Vector3[0];
  19046. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, tempVector);
  19047. this.radiusWorld = Math.max(Math.abs(tempVector.x), Math.abs(tempVector.y), Math.abs(tempVector.z)) * this.radius;
  19048. };
  19049. /**
  19050. * Tests if the bounding sphere is intersecting the frustum planes
  19051. * @param frustumPlanes defines the frustum planes to test
  19052. * @returns true if there is an intersection
  19053. */
  19054. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  19055. for (var i = 0; i < 6; i++) {
  19056. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  19057. return false;
  19058. }
  19059. return true;
  19060. };
  19061. /**
  19062. * Tests if a point is inside the bounding sphere
  19063. * @param point defines the point to test
  19064. * @returns true if the point is inside the bounding sphere
  19065. */
  19066. BoundingSphere.prototype.intersectsPoint = function (point) {
  19067. var x = this.centerWorld.x - point.x;
  19068. var y = this.centerWorld.y - point.y;
  19069. var z = this.centerWorld.z - point.z;
  19070. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19071. if (this.radiusWorld < distance)
  19072. return false;
  19073. return true;
  19074. };
  19075. // Statics
  19076. /**
  19077. * Checks if two sphere intersct
  19078. * @param sphere0 sphere 0
  19079. * @param sphere1 sphere 1
  19080. * @returns true if the speres intersect
  19081. */
  19082. BoundingSphere.Intersects = function (sphere0, sphere1) {
  19083. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  19084. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  19085. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  19086. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  19087. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  19088. return false;
  19089. return true;
  19090. };
  19091. return BoundingSphere;
  19092. }());
  19093. BABYLON.BoundingSphere = BoundingSphere;
  19094. })(BABYLON || (BABYLON = {}));
  19095. //# sourceMappingURL=babylon.boundingSphere.js.map
  19096. var BABYLON;
  19097. (function (BABYLON) {
  19098. /**
  19099. * Class used to store bounding box information
  19100. */
  19101. var BoundingBox = /** @class */ (function () {
  19102. /**
  19103. * Creates a new bounding box
  19104. * @param min defines the minimum vector (in local space)
  19105. * @param max defines the maximum vector (in local space)
  19106. */
  19107. function BoundingBox(min, max) {
  19108. /**
  19109. * Gets the 8 vectors representing the bounding box in local space
  19110. */
  19111. 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()];
  19112. /**
  19113. * Gets the center of the bounding box in local space
  19114. */
  19115. this.center = BABYLON.Vector3.Zero();
  19116. /**
  19117. * Gets the center of the bounding box in world space
  19118. */
  19119. this.centerWorld = BABYLON.Vector3.Zero();
  19120. /**
  19121. * Gets the extend size in local space
  19122. */
  19123. this.extendSize = BABYLON.Vector3.Zero();
  19124. /**
  19125. * Gets the extend size in world space
  19126. */
  19127. this.extendSizeWorld = BABYLON.Vector3.Zero();
  19128. /**
  19129. * Gets the OBB (object bounding box) directions
  19130. */
  19131. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  19132. /**
  19133. * Gets the 8 vectors representing the bounding box in world space
  19134. */
  19135. 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()];
  19136. /**
  19137. * Gets the minimum vector in world space
  19138. */
  19139. this.minimumWorld = BABYLON.Vector3.Zero();
  19140. /**
  19141. * Gets the maximum vector in world space
  19142. */
  19143. this.maximumWorld = BABYLON.Vector3.Zero();
  19144. /**
  19145. * Gets the minimum vector in local space
  19146. */
  19147. this.minimum = BABYLON.Vector3.Zero();
  19148. /**
  19149. * Gets the maximum vector in local space
  19150. */
  19151. this.maximum = BABYLON.Vector3.Zero();
  19152. this.reConstruct(min, max);
  19153. }
  19154. ;
  19155. // Methods
  19156. /**
  19157. * Recreates the entire bounding box from scratch
  19158. * @param min defines the new minimum vector (in local space)
  19159. * @param max defines the new maximum vector (in local space)
  19160. */
  19161. BoundingBox.prototype.reConstruct = function (min, max) {
  19162. this.minimum.copyFrom(min);
  19163. this.maximum.copyFrom(max);
  19164. // Bounding vectors
  19165. this.vectors[0].copyFrom(this.minimum);
  19166. this.vectors[1].copyFrom(this.maximum);
  19167. this.vectors[2].copyFrom(this.minimum);
  19168. this.vectors[3].copyFrom(this.minimum);
  19169. this.vectors[4].copyFrom(this.minimum);
  19170. this.vectors[5].copyFrom(this.maximum);
  19171. this.vectors[6].copyFrom(this.maximum);
  19172. this.vectors[7].copyFrom(this.maximum);
  19173. this.vectors[2].x = this.maximum.x;
  19174. this.vectors[3].y = this.maximum.y;
  19175. this.vectors[4].z = this.maximum.z;
  19176. this.vectors[5].z = this.minimum.z;
  19177. this.vectors[6].x = this.minimum.x;
  19178. this.vectors[7].y = this.minimum.y;
  19179. // OBB
  19180. this.center.copyFrom(this.maximum).addInPlace(this.minimum).scaleInPlace(0.5);
  19181. this.extendSize.copyFrom(this.maximum).subtractInPlace(this.minimum).scaleInPlace(0.5);
  19182. for (var index = 0; index < 3; index++) {
  19183. this.directions[index].copyFromFloats(0, 0, 0);
  19184. }
  19185. // World
  19186. for (var index = 0; index < 8; index++) {
  19187. this.vectorsWorld[index].copyFromFloats(0, 0, 0);
  19188. }
  19189. this.minimumWorld.copyFromFloats(0, 0, 0);
  19190. this.maximumWorld.copyFromFloats(0, 0, 0);
  19191. this.centerWorld.copyFromFloats(0, 0, 0);
  19192. this.extendSizeWorld.copyFromFloats(0, 0, 0);
  19193. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  19194. };
  19195. /**
  19196. * Scale the current bounding box by applying a scale factor
  19197. * @param factor defines the scale factor to apply
  19198. * @returns the current bounding box
  19199. */
  19200. BoundingBox.prototype.scale = function (factor) {
  19201. var diff = BABYLON.Tmp.Vector3[0].copyFrom(this.maximum).subtractInPlace(this.minimum);
  19202. var distance = diff.length() * factor;
  19203. diff.normalize();
  19204. var newRadius = diff.scaleInPlace(distance * 0.5);
  19205. var min = BABYLON.Tmp.Vector3[1].copyFrom(this.center).subtractInPlace(newRadius);
  19206. var max = BABYLON.Tmp.Vector3[2].copyFrom(this.center).addInPlace(newRadius);
  19207. this.reConstruct(min, max);
  19208. return this;
  19209. };
  19210. /**
  19211. * Gets the world matrix of the bounding box
  19212. * @returns a matrix
  19213. */
  19214. BoundingBox.prototype.getWorldMatrix = function () {
  19215. return this._worldMatrix;
  19216. };
  19217. /**
  19218. * Sets the world matrix stored in the bounding box
  19219. * @param matrix defines the matrix to store
  19220. * @returns current bounding box
  19221. */
  19222. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  19223. this._worldMatrix.copyFrom(matrix);
  19224. return this;
  19225. };
  19226. /** @hidden */
  19227. BoundingBox.prototype._update = function (world) {
  19228. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  19229. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  19230. for (var index = 0; index < 8; index++) {
  19231. var v = this.vectorsWorld[index];
  19232. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  19233. this.minimumWorld.minimizeInPlace(v);
  19234. this.maximumWorld.maximizeInPlace(v);
  19235. }
  19236. // Extend
  19237. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  19238. this.extendSizeWorld.scaleInPlace(0.5);
  19239. // OBB
  19240. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  19241. this.centerWorld.scaleInPlace(0.5);
  19242. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  19243. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  19244. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  19245. this._worldMatrix = world;
  19246. };
  19247. /**
  19248. * Tests if the bounding box is intersecting the frustum planes
  19249. * @param frustumPlanes defines the frustum planes to test
  19250. * @returns true if there is an intersection
  19251. */
  19252. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  19253. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  19254. };
  19255. /**
  19256. * Tests if the bounding box is entirely inside the frustum planes
  19257. * @param frustumPlanes defines the frustum planes to test
  19258. * @returns true if there is an inclusion
  19259. */
  19260. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19261. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  19262. };
  19263. /**
  19264. * Tests if a point is inside the bounding box
  19265. * @param point defines the point to test
  19266. * @returns true if the point is inside the bounding box
  19267. */
  19268. BoundingBox.prototype.intersectsPoint = function (point) {
  19269. var delta = -BABYLON.Epsilon;
  19270. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  19271. return false;
  19272. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  19273. return false;
  19274. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  19275. return false;
  19276. return true;
  19277. };
  19278. /**
  19279. * Tests if the bounding box intersects with a bounding sphere
  19280. * @param sphere defines the sphere to test
  19281. * @returns true if there is an intersection
  19282. */
  19283. BoundingBox.prototype.intersectsSphere = function (sphere) {
  19284. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  19285. };
  19286. /**
  19287. * Tests if the bounding box intersects with a box defined by a min and max vectors
  19288. * @param min defines the min vector to use
  19289. * @param max defines the max vector to use
  19290. * @returns true if there is an intersection
  19291. */
  19292. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  19293. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  19294. return false;
  19295. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  19296. return false;
  19297. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  19298. return false;
  19299. return true;
  19300. };
  19301. // Statics
  19302. /**
  19303. * Tests if two bounding boxes are intersections
  19304. * @param box0 defines the first box to test
  19305. * @param box1 defines the second box to test
  19306. * @returns true if there is an intersection
  19307. */
  19308. BoundingBox.Intersects = function (box0, box1) {
  19309. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  19310. return false;
  19311. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  19312. return false;
  19313. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  19314. return false;
  19315. return true;
  19316. };
  19317. /**
  19318. * Tests if a bounding box defines by a min/max vectors intersects a sphere
  19319. * @param minPoint defines the minimum vector of the bounding box
  19320. * @param maxPoint defines the maximum vector of the bounding box
  19321. * @param sphereCenter defines the sphere center
  19322. * @param sphereRadius defines the sphere radius
  19323. * @returns true if there is an intersection
  19324. */
  19325. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  19326. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  19327. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  19328. return (num <= (sphereRadius * sphereRadius));
  19329. };
  19330. /**
  19331. * Tests if a bounding box defined with 8 vectors is entirely inside frustum planes
  19332. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19333. * @param frustumPlanes defines the frustum planes to test
  19334. * @return true if there is an inclusion
  19335. */
  19336. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  19337. for (var p = 0; p < 6; p++) {
  19338. for (var i = 0; i < 8; i++) {
  19339. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19340. return false;
  19341. }
  19342. }
  19343. }
  19344. return true;
  19345. };
  19346. /**
  19347. * Tests if a bounding box defined with 8 vectors intersects frustum planes
  19348. * @param boundingVectors defines an array of 8 vectors representing a bounding box
  19349. * @param frustumPlanes defines the frustum planes to test
  19350. * @return true if there is an intersection
  19351. */
  19352. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  19353. for (var p = 0; p < 6; p++) {
  19354. var inCount = 8;
  19355. for (var i = 0; i < 8; i++) {
  19356. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  19357. --inCount;
  19358. }
  19359. else {
  19360. break;
  19361. }
  19362. }
  19363. if (inCount === 0)
  19364. return false;
  19365. }
  19366. return true;
  19367. };
  19368. return BoundingBox;
  19369. }());
  19370. BABYLON.BoundingBox = BoundingBox;
  19371. })(BABYLON || (BABYLON = {}));
  19372. //# sourceMappingURL=babylon.boundingBox.js.map
  19373. var BABYLON;
  19374. (function (BABYLON) {
  19375. var computeBoxExtents = function (axis, box) {
  19376. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  19377. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  19378. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  19379. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  19380. var r = r0 + r1 + r2;
  19381. return {
  19382. min: p - r,
  19383. max: p + r
  19384. };
  19385. };
  19386. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  19387. var axisOverlap = function (axis, box0, box1) {
  19388. var result0 = computeBoxExtents(axis, box0);
  19389. var result1 = computeBoxExtents(axis, box1);
  19390. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  19391. };
  19392. /**
  19393. * Info for a bounding data of a mesh
  19394. */
  19395. var BoundingInfo = /** @class */ (function () {
  19396. /**
  19397. * Constructs bounding info
  19398. * @param minimum min vector of the bounding box/sphere
  19399. * @param maximum max vector of the bounding box/sphere
  19400. */
  19401. function BoundingInfo(minimum, maximum) {
  19402. this._isLocked = false;
  19403. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  19404. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  19405. }
  19406. Object.defineProperty(BoundingInfo.prototype, "minimum", {
  19407. /**
  19408. * min vector of the bounding box/sphere
  19409. */
  19410. get: function () {
  19411. return this.boundingBox.minimum;
  19412. },
  19413. enumerable: true,
  19414. configurable: true
  19415. });
  19416. Object.defineProperty(BoundingInfo.prototype, "maximum", {
  19417. /**
  19418. * max vector of the bounding box/sphere
  19419. */
  19420. get: function () {
  19421. return this.boundingBox.maximum;
  19422. },
  19423. enumerable: true,
  19424. configurable: true
  19425. });
  19426. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  19427. /**
  19428. * If the info is locked and won't be updated to avoid perf overhead
  19429. */
  19430. get: function () {
  19431. return this._isLocked;
  19432. },
  19433. set: function (value) {
  19434. this._isLocked = value;
  19435. },
  19436. enumerable: true,
  19437. configurable: true
  19438. });
  19439. // Methods
  19440. /**
  19441. * Updates the boudning sphere and box
  19442. * @param world world matrix to be used to update
  19443. */
  19444. BoundingInfo.prototype.update = function (world) {
  19445. if (this._isLocked) {
  19446. return;
  19447. }
  19448. this.boundingBox._update(world);
  19449. this.boundingSphere._update(world);
  19450. };
  19451. /**
  19452. * Recreate the bounding info to be centered around a specific point given a specific extend.
  19453. * @param center New center of the bounding info
  19454. * @param extend New extend of the bounding info
  19455. * @returns the current bounding info
  19456. */
  19457. BoundingInfo.prototype.centerOn = function (center, extend) {
  19458. var minimum = BABYLON.Tmp.Vector3[0].copyFrom(center).subtractInPlace(extend);
  19459. var maximum = BABYLON.Tmp.Vector3[1].copyFrom(center).addInPlace(extend);
  19460. this.boundingBox.reConstruct(minimum, maximum);
  19461. this.boundingSphere.reConstruct(minimum, maximum);
  19462. return this;
  19463. };
  19464. /**
  19465. * Scale the current bounding info by applying a scale factor
  19466. * @param factor defines the scale factor to apply
  19467. * @returns the current bounding info
  19468. */
  19469. BoundingInfo.prototype.scale = function (factor) {
  19470. this.boundingBox.scale(factor);
  19471. this.boundingSphere.scale(factor);
  19472. return this;
  19473. };
  19474. /**
  19475. * Returns `true` if the bounding info is within the frustum defined by the passed array of planes.
  19476. * @param frustumPlanes defines the frustum to test
  19477. * @param strategy defines the strategy to use for the culling (default is BABYLON.Scene.CULLINGSTRATEGY_STANDARD)
  19478. * @returns true if the bounding info is in the frustum planes
  19479. */
  19480. BoundingInfo.prototype.isInFrustum = function (frustumPlanes, strategy) {
  19481. if (strategy === void 0) { strategy = BABYLON.AbstractMesh.CULLINGSTRATEGY_STANDARD; }
  19482. if (!this.boundingSphere.isInFrustum(frustumPlanes)) {
  19483. return false;
  19484. }
  19485. if (strategy === BABYLON.AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY) {
  19486. return true;
  19487. }
  19488. return this.boundingBox.isInFrustum(frustumPlanes);
  19489. };
  19490. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  19491. /**
  19492. * Gets the world distance between the min and max points of the bounding box
  19493. */
  19494. get: function () {
  19495. var boundingBox = this.boundingBox;
  19496. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  19497. return size.length();
  19498. },
  19499. enumerable: true,
  19500. configurable: true
  19501. });
  19502. /**
  19503. * Checks if a cullable object (mesh...) is in the camera frustum
  19504. * Unlike isInFrustum this cheks the full bounding box
  19505. * @param frustumPlanes Camera near/planes
  19506. * @returns true if the object is in frustum otherwise false
  19507. */
  19508. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  19509. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  19510. };
  19511. /** @hidden */
  19512. BoundingInfo.prototype._checkCollision = function (collider) {
  19513. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  19514. };
  19515. /**
  19516. * Checks if a point is inside the bounding box and bounding sphere or the mesh
  19517. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19518. * @param point the point to check intersection with
  19519. * @returns if the point intersects
  19520. */
  19521. BoundingInfo.prototype.intersectsPoint = function (point) {
  19522. if (!this.boundingSphere.centerWorld) {
  19523. return false;
  19524. }
  19525. if (!this.boundingSphere.intersectsPoint(point)) {
  19526. return false;
  19527. }
  19528. if (!this.boundingBox.intersectsPoint(point)) {
  19529. return false;
  19530. }
  19531. return true;
  19532. };
  19533. /**
  19534. * Checks if another bounding info intersects the bounding box and bounding sphere or the mesh
  19535. * @see https://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  19536. * @param boundingInfo the bounding info to check intersection with
  19537. * @param precise if the intersection should be done using OBB
  19538. * @returns if the bounding info intersects
  19539. */
  19540. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  19541. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  19542. return false;
  19543. }
  19544. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  19545. return false;
  19546. }
  19547. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  19548. return false;
  19549. }
  19550. if (!precise) {
  19551. return true;
  19552. }
  19553. var box0 = this.boundingBox;
  19554. var box1 = boundingInfo.boundingBox;
  19555. if (!axisOverlap(box0.directions[0], box0, box1))
  19556. return false;
  19557. if (!axisOverlap(box0.directions[1], box0, box1))
  19558. return false;
  19559. if (!axisOverlap(box0.directions[2], box0, box1))
  19560. return false;
  19561. if (!axisOverlap(box1.directions[0], box0, box1))
  19562. return false;
  19563. if (!axisOverlap(box1.directions[1], box0, box1))
  19564. return false;
  19565. if (!axisOverlap(box1.directions[2], box0, box1))
  19566. return false;
  19567. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  19568. return false;
  19569. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  19570. return false;
  19571. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  19572. return false;
  19573. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  19574. return false;
  19575. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  19576. return false;
  19577. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  19578. return false;
  19579. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  19580. return false;
  19581. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  19582. return false;
  19583. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  19584. return false;
  19585. return true;
  19586. };
  19587. return BoundingInfo;
  19588. }());
  19589. BABYLON.BoundingInfo = BoundingInfo;
  19590. })(BABYLON || (BABYLON = {}));
  19591. //# sourceMappingURL=babylon.boundingInfo.js.map
  19592. var BABYLON;
  19593. (function (BABYLON) {
  19594. /**
  19595. * A TransformNode is an object that is not rendered but can be used as a center of transformation. This can decrease memory usage and increase rendering speed compared to using an empty mesh as a parent and is less complicated than using a pivot matrix.
  19596. * @see https://doc.babylonjs.com/how_to/transformnode
  19597. */
  19598. var TransformNode = /** @class */ (function (_super) {
  19599. __extends(TransformNode, _super);
  19600. function TransformNode(name, scene, isPure) {
  19601. if (scene === void 0) { scene = null; }
  19602. if (isPure === void 0) { isPure = true; }
  19603. var _this = _super.call(this, name, scene) || this;
  19604. _this._forward = new BABYLON.Vector3(0, 0, 1);
  19605. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  19606. _this._up = new BABYLON.Vector3(0, 1, 0);
  19607. _this._right = new BABYLON.Vector3(1, 0, 0);
  19608. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  19609. // Properties
  19610. _this._position = BABYLON.Vector3.Zero();
  19611. _this._rotation = BABYLON.Vector3.Zero();
  19612. _this._scaling = BABYLON.Vector3.One();
  19613. _this._isDirty = false;
  19614. /**
  19615. * Set the billboard mode. Default is 0.
  19616. *
  19617. * | Value | Type | Description |
  19618. * | --- | --- | --- |
  19619. * | 0 | BILLBOARDMODE_NONE | |
  19620. * | 1 | BILLBOARDMODE_X | |
  19621. * | 2 | BILLBOARDMODE_Y | |
  19622. * | 4 | BILLBOARDMODE_Z | |
  19623. * | 7 | BILLBOARDMODE_ALL | |
  19624. *
  19625. */
  19626. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  19627. /**
  19628. * Multiplication factor on scale x/y/z when computing the world matrix. Eg. for a 1x1x1 cube setting this to 2 will make it a 2x2x2 cube
  19629. */
  19630. _this.scalingDeterminant = 1;
  19631. /**
  19632. * Sets the distance of the object to max, often used by skybox
  19633. */
  19634. _this.infiniteDistance = false;
  19635. /**
  19636. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  19637. * By default the system will update normals to compensate
  19638. */
  19639. _this.ignoreNonUniformScaling = false;
  19640. _this._localWorld = BABYLON.Matrix.Zero();
  19641. _this._absolutePosition = BABYLON.Vector3.Zero();
  19642. _this._pivotMatrix = BABYLON.Matrix.Identity();
  19643. _this._postMultiplyPivotMatrix = false;
  19644. _this._isWorldMatrixFrozen = false;
  19645. /**
  19646. * An event triggered after the world matrix is updated
  19647. */
  19648. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  19649. _this._nonUniformScaling = false;
  19650. if (isPure) {
  19651. _this.getScene().addTransformNode(_this);
  19652. }
  19653. return _this;
  19654. }
  19655. /**
  19656. * Gets a string identifying the name of the class
  19657. * @returns "TransformNode" string
  19658. */
  19659. TransformNode.prototype.getClassName = function () {
  19660. return "TransformNode";
  19661. };
  19662. Object.defineProperty(TransformNode.prototype, "position", {
  19663. /**
  19664. * Gets or set the node position (default is (0.0, 0.0, 0.0))
  19665. */
  19666. get: function () {
  19667. return this._position;
  19668. },
  19669. set: function (newPosition) {
  19670. this._position = newPosition;
  19671. this._isDirty = true;
  19672. },
  19673. enumerable: true,
  19674. configurable: true
  19675. });
  19676. Object.defineProperty(TransformNode.prototype, "rotation", {
  19677. /**
  19678. * 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)).
  19679. * If rotation quaternion is set, this Vector3 will be ignored and copy from the quaternion
  19680. */
  19681. get: function () {
  19682. return this._rotation;
  19683. },
  19684. set: function (newRotation) {
  19685. this._rotation = newRotation;
  19686. this._isDirty = true;
  19687. },
  19688. enumerable: true,
  19689. configurable: true
  19690. });
  19691. Object.defineProperty(TransformNode.prototype, "scaling", {
  19692. /**
  19693. * 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)).
  19694. */
  19695. get: function () {
  19696. return this._scaling;
  19697. },
  19698. set: function (newScaling) {
  19699. this._scaling = newScaling;
  19700. this._isDirty = true;
  19701. },
  19702. enumerable: true,
  19703. configurable: true
  19704. });
  19705. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  19706. /**
  19707. * Gets or sets the rotation Quaternion property : this a Quaternion object defining the node rotation by using a unit quaternion (null by default).
  19708. * If set, only the rotationQuaternion is then used to compute the node rotation (ie. node.rotation will be ignored)
  19709. */
  19710. get: function () {
  19711. return this._rotationQuaternion;
  19712. },
  19713. set: function (quaternion) {
  19714. this._rotationQuaternion = quaternion;
  19715. //reset the rotation vector.
  19716. if (quaternion && this.rotation.length()) {
  19717. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  19718. }
  19719. },
  19720. enumerable: true,
  19721. configurable: true
  19722. });
  19723. Object.defineProperty(TransformNode.prototype, "forward", {
  19724. /**
  19725. * The forward direction of that transform in world space.
  19726. */
  19727. get: function () {
  19728. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  19729. },
  19730. enumerable: true,
  19731. configurable: true
  19732. });
  19733. Object.defineProperty(TransformNode.prototype, "up", {
  19734. /**
  19735. * The up direction of that transform in world space.
  19736. */
  19737. get: function () {
  19738. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  19739. },
  19740. enumerable: true,
  19741. configurable: true
  19742. });
  19743. Object.defineProperty(TransformNode.prototype, "right", {
  19744. /**
  19745. * The right direction of that transform in world space.
  19746. */
  19747. get: function () {
  19748. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  19749. },
  19750. enumerable: true,
  19751. configurable: true
  19752. });
  19753. /**
  19754. * Copies the parameter passed Matrix into the mesh Pose matrix.
  19755. * @param matrix the matrix to copy the pose from
  19756. * @returns this TransformNode.
  19757. */
  19758. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  19759. this._poseMatrix.copyFrom(matrix);
  19760. return this;
  19761. };
  19762. /**
  19763. * Returns the mesh Pose matrix.
  19764. * @returns the pose matrix
  19765. */
  19766. TransformNode.prototype.getPoseMatrix = function () {
  19767. return this._poseMatrix;
  19768. };
  19769. /** @hidden */
  19770. TransformNode.prototype._isSynchronized = function () {
  19771. if (this._isDirty) {
  19772. return false;
  19773. }
  19774. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  19775. return false;
  19776. if (this._cache.pivotMatrixUpdated) {
  19777. return false;
  19778. }
  19779. if (this.infiniteDistance) {
  19780. return false;
  19781. }
  19782. if (!this._cache.position.equals(this._position))
  19783. return false;
  19784. if (this._rotationQuaternion) {
  19785. if (!this._cache.rotationQuaternion.equals(this._rotationQuaternion))
  19786. return false;
  19787. }
  19788. if (!this._cache.rotation.equals(this._rotation))
  19789. return false;
  19790. if (!this._cache.scaling.equals(this._scaling))
  19791. return false;
  19792. return true;
  19793. };
  19794. /** @hidden */
  19795. TransformNode.prototype._initCache = function () {
  19796. _super.prototype._initCache.call(this);
  19797. this._cache.localMatrixUpdated = false;
  19798. this._cache.position = BABYLON.Vector3.Zero();
  19799. this._cache.scaling = BABYLON.Vector3.Zero();
  19800. this._cache.rotation = BABYLON.Vector3.Zero();
  19801. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  19802. this._cache.billboardMode = -1;
  19803. };
  19804. /**
  19805. * Flag the transform node as dirty (Forcing it to update everything)
  19806. * @param property if set to "rotation" the objects rotationQuaternion will be set to null
  19807. * @returns this transform node
  19808. */
  19809. TransformNode.prototype.markAsDirty = function (property) {
  19810. if (property === "rotation") {
  19811. this.rotationQuaternion = null;
  19812. }
  19813. this._currentRenderId = Number.MAX_VALUE;
  19814. this._isDirty = true;
  19815. return this;
  19816. };
  19817. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  19818. /**
  19819. * Returns the current mesh absolute position.
  19820. * Returns a Vector3.
  19821. */
  19822. get: function () {
  19823. return this._absolutePosition;
  19824. },
  19825. enumerable: true,
  19826. configurable: true
  19827. });
  19828. /**
  19829. * Sets a new matrix to apply before all other transformation
  19830. * @param matrix defines the transform matrix
  19831. * @returns the current TransformNode
  19832. */
  19833. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  19834. return this.setPivotMatrix(matrix, false);
  19835. };
  19836. /**
  19837. * Sets a new pivot matrix to the current node
  19838. * @param matrix defines the new pivot matrix to use
  19839. * @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
  19840. * @returns the current TransformNode
  19841. */
  19842. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  19843. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  19844. this._pivotMatrix = matrix.clone();
  19845. this._cache.pivotMatrixUpdated = true;
  19846. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  19847. if (this._postMultiplyPivotMatrix) {
  19848. if (!this._pivotMatrixInverse) {
  19849. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  19850. }
  19851. else {
  19852. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  19853. }
  19854. }
  19855. return this;
  19856. };
  19857. /**
  19858. * Returns the mesh pivot matrix.
  19859. * Default : Identity.
  19860. * @returns the matrix
  19861. */
  19862. TransformNode.prototype.getPivotMatrix = function () {
  19863. return this._pivotMatrix;
  19864. };
  19865. /**
  19866. * Prevents the World matrix to be computed any longer.
  19867. * @returns the TransformNode.
  19868. */
  19869. TransformNode.prototype.freezeWorldMatrix = function () {
  19870. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  19871. this.computeWorldMatrix(true);
  19872. this._isWorldMatrixFrozen = true;
  19873. return this;
  19874. };
  19875. /**
  19876. * Allows back the World matrix computation.
  19877. * @returns the TransformNode.
  19878. */
  19879. TransformNode.prototype.unfreezeWorldMatrix = function () {
  19880. this._isWorldMatrixFrozen = false;
  19881. this.computeWorldMatrix(true);
  19882. return this;
  19883. };
  19884. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19885. /**
  19886. * True if the World matrix has been frozen.
  19887. */
  19888. get: function () {
  19889. return this._isWorldMatrixFrozen;
  19890. },
  19891. enumerable: true,
  19892. configurable: true
  19893. });
  19894. /**
  19895. * Retuns the mesh absolute position in the World.
  19896. * @returns a Vector3.
  19897. */
  19898. TransformNode.prototype.getAbsolutePosition = function () {
  19899. this.computeWorldMatrix();
  19900. return this._absolutePosition;
  19901. };
  19902. /**
  19903. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19904. * @param absolutePosition the absolute position to set
  19905. * @returns the TransformNode.
  19906. */
  19907. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19908. if (!absolutePosition) {
  19909. return this;
  19910. }
  19911. var absolutePositionX;
  19912. var absolutePositionY;
  19913. var absolutePositionZ;
  19914. if (absolutePosition.x === undefined) {
  19915. if (arguments.length < 3) {
  19916. return this;
  19917. }
  19918. absolutePositionX = arguments[0];
  19919. absolutePositionY = arguments[1];
  19920. absolutePositionZ = arguments[2];
  19921. }
  19922. else {
  19923. absolutePositionX = absolutePosition.x;
  19924. absolutePositionY = absolutePosition.y;
  19925. absolutePositionZ = absolutePosition.z;
  19926. }
  19927. if (this.parent) {
  19928. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19929. invertParentWorldMatrix.invert();
  19930. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19931. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19932. }
  19933. else {
  19934. this.position.x = absolutePositionX;
  19935. this.position.y = absolutePositionY;
  19936. this.position.z = absolutePositionZ;
  19937. }
  19938. return this;
  19939. };
  19940. /**
  19941. * Sets the mesh position in its local space.
  19942. * @param vector3 the position to set in localspace
  19943. * @returns the TransformNode.
  19944. */
  19945. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19946. this.computeWorldMatrix();
  19947. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19948. return this;
  19949. };
  19950. /**
  19951. * Returns the mesh position in the local space from the current World matrix values.
  19952. * @returns a new Vector3.
  19953. */
  19954. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19955. this.computeWorldMatrix();
  19956. var invLocalWorldMatrix = this._localWorld.clone();
  19957. invLocalWorldMatrix.invert();
  19958. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19959. };
  19960. /**
  19961. * Translates the mesh along the passed Vector3 in its local space.
  19962. * @param vector3 the distance to translate in localspace
  19963. * @returns the TransformNode.
  19964. */
  19965. TransformNode.prototype.locallyTranslate = function (vector3) {
  19966. this.computeWorldMatrix(true);
  19967. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19968. return this;
  19969. };
  19970. /**
  19971. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19972. * @param targetPoint the position (must be in same space as current mesh) to look at
  19973. * @param yawCor optional yaw (y-axis) correction in radians
  19974. * @param pitchCor optional pitch (x-axis) correction in radians
  19975. * @param rollCor optional roll (z-axis) correction in radians
  19976. * @param space the choosen space of the target
  19977. * @returns the TransformNode.
  19978. */
  19979. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19980. if (yawCor === void 0) { yawCor = 0; }
  19981. if (pitchCor === void 0) { pitchCor = 0; }
  19982. if (rollCor === void 0) { rollCor = 0; }
  19983. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19984. var dv = TransformNode._lookAtVectorCache;
  19985. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19986. targetPoint.subtractToRef(pos, dv);
  19987. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19988. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19989. var pitch = Math.atan2(dv.y, len);
  19990. if (this.rotationQuaternion) {
  19991. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19992. }
  19993. else {
  19994. this.rotation.x = pitch + pitchCor;
  19995. this.rotation.y = yaw + yawCor;
  19996. this.rotation.z = rollCor;
  19997. }
  19998. return this;
  19999. };
  20000. /**
  20001. * Returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20002. * This Vector3 is expressed in the World space.
  20003. * @param localAxis axis to rotate
  20004. * @returns a new Vector3 that is the localAxis, expressed in the mesh local space, rotated like the mesh.
  20005. */
  20006. TransformNode.prototype.getDirection = function (localAxis) {
  20007. var result = BABYLON.Vector3.Zero();
  20008. this.getDirectionToRef(localAxis, result);
  20009. return result;
  20010. };
  20011. /**
  20012. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  20013. * localAxis is expressed in the mesh local space.
  20014. * result is computed in the Wordl space from the mesh World matrix.
  20015. * @param localAxis axis to rotate
  20016. * @param result the resulting transformnode
  20017. * @returns this TransformNode.
  20018. */
  20019. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  20020. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  20021. return this;
  20022. };
  20023. /**
  20024. * Sets a new pivot point to the current node
  20025. * @param point defines the new pivot point to use
  20026. * @param space defines if the point is in world or local space (local by default)
  20027. * @returns the current TransformNode
  20028. */
  20029. TransformNode.prototype.setPivotPoint = function (point, space) {
  20030. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  20031. if (this.getScene().getRenderId() == 0) {
  20032. this.computeWorldMatrix(true);
  20033. }
  20034. var wm = this.getWorldMatrix();
  20035. if (space == BABYLON.Space.WORLD) {
  20036. var tmat = BABYLON.Tmp.Matrix[0];
  20037. wm.invertToRef(tmat);
  20038. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  20039. }
  20040. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  20041. };
  20042. /**
  20043. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  20044. * @returns the pivot point
  20045. */
  20046. TransformNode.prototype.getPivotPoint = function () {
  20047. var point = BABYLON.Vector3.Zero();
  20048. this.getPivotPointToRef(point);
  20049. return point;
  20050. };
  20051. /**
  20052. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  20053. * @param result the vector3 to store the result
  20054. * @returns this TransformNode.
  20055. */
  20056. TransformNode.prototype.getPivotPointToRef = function (result) {
  20057. result.x = -this._pivotMatrix.m[12];
  20058. result.y = -this._pivotMatrix.m[13];
  20059. result.z = -this._pivotMatrix.m[14];
  20060. return this;
  20061. };
  20062. /**
  20063. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  20064. * @returns a new Vector3 set with the mesh pivot point World coordinates.
  20065. */
  20066. TransformNode.prototype.getAbsolutePivotPoint = function () {
  20067. var point = BABYLON.Vector3.Zero();
  20068. this.getAbsolutePivotPointToRef(point);
  20069. return point;
  20070. };
  20071. /**
  20072. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  20073. * @param result vector3 to store the result
  20074. * @returns this TransformNode.
  20075. */
  20076. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  20077. result.x = this._pivotMatrix.m[12];
  20078. result.y = this._pivotMatrix.m[13];
  20079. result.z = this._pivotMatrix.m[14];
  20080. this.getPivotPointToRef(result);
  20081. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  20082. return this;
  20083. };
  20084. /**
  20085. * Defines the passed node as the parent of the current node.
  20086. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  20087. * @param node the node ot set as the parent
  20088. * @returns this TransformNode.
  20089. */
  20090. TransformNode.prototype.setParent = function (node) {
  20091. if (!node && !this.parent) {
  20092. return this;
  20093. }
  20094. if (!node) {
  20095. var rotation = BABYLON.Tmp.Quaternion[0];
  20096. var position = BABYLON.Tmp.Vector3[0];
  20097. var scale = BABYLON.Tmp.Vector3[1];
  20098. if (this.parent && this.parent.computeWorldMatrix) {
  20099. this.parent.computeWorldMatrix(true);
  20100. }
  20101. this.computeWorldMatrix(true);
  20102. this.getWorldMatrix().decompose(scale, rotation, position);
  20103. if (this.rotationQuaternion) {
  20104. this.rotationQuaternion.copyFrom(rotation);
  20105. }
  20106. else {
  20107. rotation.toEulerAnglesToRef(this.rotation);
  20108. }
  20109. this.scaling.x = scale.x;
  20110. this.scaling.y = scale.y;
  20111. this.scaling.z = scale.z;
  20112. this.position.x = position.x;
  20113. this.position.y = position.y;
  20114. this.position.z = position.z;
  20115. }
  20116. else {
  20117. var rotation = BABYLON.Tmp.Quaternion[0];
  20118. var position = BABYLON.Tmp.Vector3[0];
  20119. var scale = BABYLON.Tmp.Vector3[1];
  20120. var diffMatrix = BABYLON.Tmp.Matrix[0];
  20121. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  20122. this.computeWorldMatrix(true);
  20123. node.computeWorldMatrix(true);
  20124. node.getWorldMatrix().invertToRef(invParentMatrix);
  20125. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  20126. diffMatrix.decompose(scale, rotation, position);
  20127. if (this.rotationQuaternion) {
  20128. this.rotationQuaternion.copyFrom(rotation);
  20129. }
  20130. else {
  20131. rotation.toEulerAnglesToRef(this.rotation);
  20132. }
  20133. this.position.x = position.x;
  20134. this.position.y = position.y;
  20135. this.position.z = position.z;
  20136. this.scaling.x = scale.x;
  20137. this.scaling.y = scale.y;
  20138. this.scaling.z = scale.z;
  20139. }
  20140. this.parent = node;
  20141. return this;
  20142. };
  20143. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  20144. /**
  20145. * True if the scaling property of this object is non uniform eg. (1,2,1)
  20146. */
  20147. get: function () {
  20148. return this._nonUniformScaling;
  20149. },
  20150. enumerable: true,
  20151. configurable: true
  20152. });
  20153. /** @hidden */
  20154. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  20155. if (this._nonUniformScaling === value) {
  20156. return false;
  20157. }
  20158. this._nonUniformScaling = value;
  20159. return true;
  20160. };
  20161. /**
  20162. * Attach the current TransformNode to another TransformNode associated with a bone
  20163. * @param bone Bone affecting the TransformNode
  20164. * @param affectedTransformNode TransformNode associated with the bone
  20165. * @returns this object
  20166. */
  20167. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  20168. this._transformToBoneReferal = affectedTransformNode;
  20169. this.parent = bone;
  20170. if (bone.getWorldMatrix().determinant() < 0) {
  20171. this.scalingDeterminant *= -1;
  20172. }
  20173. return this;
  20174. };
  20175. /**
  20176. * Detach the transform node if its associated with a bone
  20177. * @returns this object
  20178. */
  20179. TransformNode.prototype.detachFromBone = function () {
  20180. if (!this.parent) {
  20181. return this;
  20182. }
  20183. if (this.parent.getWorldMatrix().determinant() < 0) {
  20184. this.scalingDeterminant *= -1;
  20185. }
  20186. this._transformToBoneReferal = null;
  20187. this.parent = null;
  20188. return this;
  20189. };
  20190. /**
  20191. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  20192. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20193. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20194. * The passed axis is also normalized.
  20195. * @param axis the axis to rotate around
  20196. * @param amount the amount to rotate in radians
  20197. * @param space Space to rotate in (Default: local)
  20198. * @returns the TransformNode.
  20199. */
  20200. TransformNode.prototype.rotate = function (axis, amount, space) {
  20201. axis.normalize();
  20202. if (!this.rotationQuaternion) {
  20203. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20204. this.rotation = BABYLON.Vector3.Zero();
  20205. }
  20206. var rotationQuaternion;
  20207. if (!space || space === BABYLON.Space.LOCAL) {
  20208. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20209. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  20210. }
  20211. else {
  20212. if (this.parent) {
  20213. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  20214. invertParentWorldMatrix.invert();
  20215. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  20216. }
  20217. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  20218. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20219. }
  20220. return this;
  20221. };
  20222. /**
  20223. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  20224. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  20225. * The passed axis is also normalized. .
  20226. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  20227. * @param point the point to rotate around
  20228. * @param axis the axis to rotate around
  20229. * @param amount the amount to rotate in radians
  20230. * @returns the TransformNode
  20231. */
  20232. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  20233. axis.normalize();
  20234. if (!this.rotationQuaternion) {
  20235. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20236. this.rotation.copyFromFloats(0, 0, 0);
  20237. }
  20238. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  20239. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  20240. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  20241. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  20242. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  20243. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  20244. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  20245. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  20246. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  20247. return this;
  20248. };
  20249. /**
  20250. * Translates the mesh along the axis vector for the passed distance in the given space.
  20251. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  20252. * @param axis the axis to translate in
  20253. * @param distance the distance to translate
  20254. * @param space Space to rotate in (Default: local)
  20255. * @returns the TransformNode.
  20256. */
  20257. TransformNode.prototype.translate = function (axis, distance, space) {
  20258. var displacementVector = axis.scale(distance);
  20259. if (!space || space === BABYLON.Space.LOCAL) {
  20260. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  20261. this.setPositionWithLocalVector(tempV3);
  20262. }
  20263. else {
  20264. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  20265. }
  20266. return this;
  20267. };
  20268. /**
  20269. * Adds a rotation step to the mesh current rotation.
  20270. * x, y, z are Euler angles expressed in radians.
  20271. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  20272. * This means this rotation is made in the mesh local space only.
  20273. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  20274. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  20275. * ```javascript
  20276. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  20277. * ```
  20278. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  20279. * 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.
  20280. * @param x Rotation to add
  20281. * @param y Rotation to add
  20282. * @param z Rotation to add
  20283. * @returns the TransformNode.
  20284. */
  20285. TransformNode.prototype.addRotation = function (x, y, z) {
  20286. var rotationQuaternion;
  20287. if (this.rotationQuaternion) {
  20288. rotationQuaternion = this.rotationQuaternion;
  20289. }
  20290. else {
  20291. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  20292. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  20293. }
  20294. var accumulation = BABYLON.Tmp.Quaternion[0];
  20295. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  20296. rotationQuaternion.multiplyInPlace(accumulation);
  20297. if (!this.rotationQuaternion) {
  20298. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  20299. }
  20300. return this;
  20301. };
  20302. /**
  20303. * Computes the world matrix of the node
  20304. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  20305. * @returns the world matrix
  20306. */
  20307. TransformNode.prototype.computeWorldMatrix = function (force) {
  20308. if (this._isWorldMatrixFrozen) {
  20309. return this._worldMatrix;
  20310. }
  20311. if (!force && this.isSynchronized()) {
  20312. this._currentRenderId = this.getScene().getRenderId();
  20313. return this._worldMatrix;
  20314. }
  20315. this._updateCache();
  20316. this._cache.position.copyFrom(this.position);
  20317. this._cache.scaling.copyFrom(this.scaling);
  20318. this._cache.pivotMatrixUpdated = false;
  20319. this._cache.billboardMode = this.billboardMode;
  20320. this._currentRenderId = this.getScene().getRenderId();
  20321. this._childRenderId = this.getScene().getRenderId();
  20322. this._isDirty = false;
  20323. // Scaling
  20324. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  20325. // Rotation
  20326. //rotate, if quaternion is set and rotation was used
  20327. if (this.rotationQuaternion) {
  20328. var len = this.rotation.length();
  20329. if (len) {
  20330. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  20331. this.rotation.copyFromFloats(0, 0, 0);
  20332. }
  20333. }
  20334. if (this.rotationQuaternion) {
  20335. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  20336. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  20337. }
  20338. else {
  20339. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  20340. this._cache.rotation.copyFrom(this.rotation);
  20341. }
  20342. // Translation
  20343. var camera = this.getScene().activeCamera;
  20344. if (this.infiniteDistance && !this.parent && camera) {
  20345. var cameraWorldMatrix = camera.getWorldMatrix();
  20346. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  20347. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  20348. }
  20349. else {
  20350. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  20351. }
  20352. // Composing transformations
  20353. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  20354. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20355. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  20356. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  20357. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  20358. // Need to decompose each rotation here
  20359. var currentPosition = BABYLON.Tmp.Vector3[3];
  20360. if (this.parent && this.parent.getWorldMatrix) {
  20361. if (this._transformToBoneReferal) {
  20362. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20363. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  20364. }
  20365. else {
  20366. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  20367. }
  20368. }
  20369. else {
  20370. currentPosition.copyFrom(this.position);
  20371. }
  20372. currentPosition.subtractInPlace(camera.globalPosition);
  20373. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  20374. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  20375. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  20376. }
  20377. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  20378. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  20379. }
  20380. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  20381. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  20382. }
  20383. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  20384. }
  20385. else {
  20386. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  20387. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  20388. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  20389. }
  20390. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  20391. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  20392. }
  20393. // Post multiply inverse of pivotMatrix
  20394. if (this._postMultiplyPivotMatrix) {
  20395. BABYLON.Tmp.Matrix[5].multiplyToRef(this._pivotMatrixInverse, BABYLON.Tmp.Matrix[5]);
  20396. }
  20397. // Local world
  20398. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  20399. // Parent
  20400. if (this.parent && this.parent.getWorldMatrix) {
  20401. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  20402. if (this._transformToBoneReferal) {
  20403. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20404. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  20405. }
  20406. else {
  20407. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  20408. }
  20409. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  20410. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  20411. this._worldMatrix.copyFrom(this._localWorld);
  20412. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  20413. }
  20414. else {
  20415. if (this._transformToBoneReferal) {
  20416. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  20417. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  20418. }
  20419. else {
  20420. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  20421. }
  20422. }
  20423. this._markSyncedWithParent();
  20424. }
  20425. else {
  20426. this._worldMatrix.copyFrom(this._localWorld);
  20427. }
  20428. // Normal matrix
  20429. if (!this.ignoreNonUniformScaling) {
  20430. if (this.scaling.isNonUniform) {
  20431. this._updateNonUniformScalingState(true);
  20432. }
  20433. else if (this.parent && this.parent._nonUniformScaling) {
  20434. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  20435. }
  20436. else {
  20437. this._updateNonUniformScalingState(false);
  20438. }
  20439. }
  20440. else {
  20441. this._updateNonUniformScalingState(false);
  20442. }
  20443. this._afterComputeWorldMatrix();
  20444. // Absolute position
  20445. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  20446. // Callbacks
  20447. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  20448. if (!this._poseMatrix) {
  20449. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  20450. }
  20451. // Cache the determinant
  20452. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  20453. return this._worldMatrix;
  20454. };
  20455. TransformNode.prototype._afterComputeWorldMatrix = function () {
  20456. };
  20457. /**
  20458. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  20459. * @param func callback function to add
  20460. *
  20461. * @returns the TransformNode.
  20462. */
  20463. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  20464. this.onAfterWorldMatrixUpdateObservable.add(func);
  20465. return this;
  20466. };
  20467. /**
  20468. * Removes a registered callback function.
  20469. * @param func callback function to remove
  20470. * @returns the TransformNode.
  20471. */
  20472. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  20473. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  20474. return this;
  20475. };
  20476. /**
  20477. * Clone the current transform node
  20478. * @param name Name of the new clone
  20479. * @param newParent New parent for the clone
  20480. * @param doNotCloneChildren Do not clone children hierarchy
  20481. * @returns the new transform node
  20482. */
  20483. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20484. var _this = this;
  20485. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  20486. result.name = name;
  20487. result.id = name;
  20488. if (newParent) {
  20489. result.parent = newParent;
  20490. }
  20491. if (!doNotCloneChildren) {
  20492. // Children
  20493. var directDescendants = this.getDescendants(true);
  20494. for (var index = 0; index < directDescendants.length; index++) {
  20495. var child = directDescendants[index];
  20496. if (child.clone) {
  20497. child.clone(name + "." + child.name, result);
  20498. }
  20499. }
  20500. }
  20501. return result;
  20502. };
  20503. /**
  20504. * Serializes the objects information.
  20505. * @param currentSerializationObject defines the object to serialize in
  20506. * @returns the serialized object
  20507. */
  20508. TransformNode.prototype.serialize = function (currentSerializationObject) {
  20509. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  20510. serializationObject.type = this.getClassName();
  20511. // Parent
  20512. if (this.parent) {
  20513. serializationObject.parentId = this.parent.id;
  20514. }
  20515. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  20516. serializationObject.tags = BABYLON.Tags.GetTags(this);
  20517. }
  20518. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  20519. serializationObject.isEnabled = this.isEnabled();
  20520. // Parent
  20521. if (this.parent) {
  20522. serializationObject.parentId = this.parent.id;
  20523. }
  20524. return serializationObject;
  20525. };
  20526. // Statics
  20527. /**
  20528. * Returns a new TransformNode object parsed from the source provided.
  20529. * @param parsedTransformNode is the source.
  20530. * @param scene the scne the object belongs to
  20531. * @param rootUrl is a string, it's the root URL to prefix the `delayLoadingFile` property with
  20532. * @returns a new TransformNode object parsed from the source provided.
  20533. */
  20534. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  20535. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  20536. if (BABYLON.Tags) {
  20537. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  20538. }
  20539. if (parsedTransformNode.localMatrix) {
  20540. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  20541. }
  20542. else if (parsedTransformNode.pivotMatrix) {
  20543. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  20544. }
  20545. transformNode.setEnabled(parsedTransformNode.isEnabled);
  20546. // Parent
  20547. if (parsedTransformNode.parentId) {
  20548. transformNode._waitingParentId = parsedTransformNode.parentId;
  20549. }
  20550. return transformNode;
  20551. };
  20552. /**
  20553. * Releases resources associated with this transform node.
  20554. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20555. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20556. */
  20557. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20558. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20559. // Animations
  20560. this.getScene().stopAnimation(this);
  20561. // Remove from scene
  20562. this.getScene().removeTransformNode(this);
  20563. this.onAfterWorldMatrixUpdateObservable.clear();
  20564. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20565. };
  20566. // Statics
  20567. /**
  20568. * Object will not rotate to face the camera
  20569. */
  20570. TransformNode.BILLBOARDMODE_NONE = 0;
  20571. /**
  20572. * Object will rotate to face the camera but only on the x axis
  20573. */
  20574. TransformNode.BILLBOARDMODE_X = 1;
  20575. /**
  20576. * Object will rotate to face the camera but only on the y axis
  20577. */
  20578. TransformNode.BILLBOARDMODE_Y = 2;
  20579. /**
  20580. * Object will rotate to face the camera but only on the z axis
  20581. */
  20582. TransformNode.BILLBOARDMODE_Z = 4;
  20583. /**
  20584. * Object will rotate to face the camera
  20585. */
  20586. TransformNode.BILLBOARDMODE_ALL = 7;
  20587. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  20588. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  20589. __decorate([
  20590. BABYLON.serializeAsVector3("position")
  20591. ], TransformNode.prototype, "_position", void 0);
  20592. __decorate([
  20593. BABYLON.serializeAsVector3("rotation")
  20594. ], TransformNode.prototype, "_rotation", void 0);
  20595. __decorate([
  20596. BABYLON.serializeAsQuaternion("rotationQuaternion")
  20597. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  20598. __decorate([
  20599. BABYLON.serializeAsVector3("scaling")
  20600. ], TransformNode.prototype, "_scaling", void 0);
  20601. __decorate([
  20602. BABYLON.serialize()
  20603. ], TransformNode.prototype, "billboardMode", void 0);
  20604. __decorate([
  20605. BABYLON.serialize()
  20606. ], TransformNode.prototype, "scalingDeterminant", void 0);
  20607. __decorate([
  20608. BABYLON.serialize()
  20609. ], TransformNode.prototype, "infiniteDistance", void 0);
  20610. __decorate([
  20611. BABYLON.serialize()
  20612. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  20613. return TransformNode;
  20614. }(BABYLON.Node));
  20615. BABYLON.TransformNode = TransformNode;
  20616. })(BABYLON || (BABYLON = {}));
  20617. //# sourceMappingURL=babylon.transformNode.js.map
  20618. var BABYLON;
  20619. (function (BABYLON) {
  20620. /** @hidden */
  20621. var _FacetDataStorage = /** @class */ (function () {
  20622. function _FacetDataStorage() {
  20623. this.facetNb = 0; // facet number
  20624. this.partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  20625. this.partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  20626. this.facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  20627. this.facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  20628. this.bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  20629. this.subDiv = {
  20630. max: 1,
  20631. X: 1,
  20632. Y: 1,
  20633. Z: 1
  20634. };
  20635. this.facetDepthSort = false; // is the facet depth sort to be computed
  20636. this.facetDepthSortEnabled = false; // is the facet depth sort initialized
  20637. }
  20638. return _FacetDataStorage;
  20639. }());
  20640. /**
  20641. * Class used to store all common mesh properties
  20642. */
  20643. var AbstractMesh = /** @class */ (function (_super) {
  20644. __extends(AbstractMesh, _super);
  20645. // Constructor
  20646. /**
  20647. * Creates a new AbstractMesh
  20648. * @param name defines the name of the mesh
  20649. * @param scene defines the hosting scene
  20650. */
  20651. function AbstractMesh(name, scene) {
  20652. if (scene === void 0) { scene = null; }
  20653. var _this = _super.call(this, name, scene, false) || this;
  20654. _this._facetData = new _FacetDataStorage();
  20655. /** Gets ot sets the culling strategy to use to find visible meshes */
  20656. _this.cullingStrategy = AbstractMesh.CULLINGSTRATEGY_STANDARD;
  20657. // Events
  20658. /**
  20659. * An event triggered when this mesh collides with another one
  20660. */
  20661. _this.onCollideObservable = new BABYLON.Observable();
  20662. /**
  20663. * An event triggered when the collision's position changes
  20664. */
  20665. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  20666. /**
  20667. * An event triggered when material is changed
  20668. */
  20669. _this.onMaterialChangedObservable = new BABYLON.Observable();
  20670. // Properties
  20671. /**
  20672. * Gets or sets the orientation for POV movement & rotation
  20673. */
  20674. _this.definedFacingForward = true;
  20675. _this._visibility = 1.0;
  20676. /** Gets or sets the alpha index used to sort transparent meshes
  20677. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  20678. */
  20679. _this.alphaIndex = Number.MAX_VALUE;
  20680. /**
  20681. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  20682. */
  20683. _this.isVisible = true;
  20684. /**
  20685. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  20686. */
  20687. _this.isPickable = true;
  20688. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  20689. _this.showSubMeshesBoundingBox = false;
  20690. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  20691. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  20692. */
  20693. _this.isBlocker = false;
  20694. /**
  20695. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  20696. */
  20697. _this.enablePointerMoveEvents = false;
  20698. /**
  20699. * Specifies the rendering group id for this mesh (0 by default)
  20700. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  20701. */
  20702. _this.renderingGroupId = 0;
  20703. _this._receiveShadows = false;
  20704. /** Defines color to use when rendering outline */
  20705. _this.outlineColor = BABYLON.Color3.Red();
  20706. /** Define width to use when rendering outline */
  20707. _this.outlineWidth = 0.02;
  20708. /** Defines color to use when rendering overlay */
  20709. _this.overlayColor = BABYLON.Color3.Red();
  20710. /** Defines alpha to use when rendering overlay */
  20711. _this.overlayAlpha = 0.5;
  20712. _this._hasVertexAlpha = false;
  20713. _this._useVertexColors = true;
  20714. _this._computeBonesUsingShaders = true;
  20715. _this._numBoneInfluencers = 4;
  20716. _this._applyFog = true;
  20717. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  20718. _this.useOctreeForRenderingSelection = true;
  20719. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  20720. _this.useOctreeForPicking = true;
  20721. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  20722. _this.useOctreeForCollisions = true;
  20723. _this._layerMask = 0x0FFFFFFF;
  20724. /**
  20725. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  20726. */
  20727. _this.alwaysSelectAsActiveMesh = false;
  20728. /**
  20729. * Gets or sets the current action manager
  20730. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  20731. */
  20732. _this.actionManager = null;
  20733. // Collisions
  20734. _this._checkCollisions = false;
  20735. _this._collisionMask = -1;
  20736. _this._collisionGroup = -1;
  20737. /**
  20738. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  20739. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20740. */
  20741. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  20742. /**
  20743. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  20744. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20745. */
  20746. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  20747. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20748. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  20749. // Edges
  20750. /**
  20751. * Defines edge width used when edgesRenderer is enabled
  20752. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20753. */
  20754. _this.edgesWidth = 1;
  20755. /**
  20756. * Defines edge color used when edgesRenderer is enabled
  20757. * @see https://www.babylonjs-playground.com/#10OJSG#13
  20758. */
  20759. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  20760. /** @hidden */
  20761. _this._renderId = 0;
  20762. /** @hidden */
  20763. _this._intersectionsInProgress = new Array();
  20764. /** @hidden */
  20765. _this._unIndexed = false;
  20766. /** @hidden */
  20767. _this._lightSources = new Array();
  20768. /**
  20769. * An event triggered when the mesh is rebuilt.
  20770. */
  20771. _this.onRebuildObservable = new BABYLON.Observable();
  20772. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  20773. if (collidedMesh === void 0) { collidedMesh = null; }
  20774. //TODO move this to the collision coordinator!
  20775. if (_this.getScene().workerCollisions)
  20776. newPosition.multiplyInPlace(_this._collider._radius);
  20777. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  20778. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  20779. _this.position.addInPlace(_this._diffPositionForCollisions);
  20780. }
  20781. if (collidedMesh) {
  20782. _this.onCollideObservable.notifyObservers(collidedMesh);
  20783. }
  20784. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  20785. };
  20786. _this.getScene().addMesh(_this);
  20787. _this._resyncLightSources();
  20788. return _this;
  20789. }
  20790. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  20791. /**
  20792. * No billboard
  20793. */
  20794. get: function () {
  20795. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  20796. },
  20797. enumerable: true,
  20798. configurable: true
  20799. });
  20800. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  20801. /** Billboard on X axis */
  20802. get: function () {
  20803. return BABYLON.TransformNode.BILLBOARDMODE_X;
  20804. },
  20805. enumerable: true,
  20806. configurable: true
  20807. });
  20808. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  20809. /** Billboard on Y axis */
  20810. get: function () {
  20811. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  20812. },
  20813. enumerable: true,
  20814. configurable: true
  20815. });
  20816. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  20817. /** Billboard on Z axis */
  20818. get: function () {
  20819. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  20820. },
  20821. enumerable: true,
  20822. configurable: true
  20823. });
  20824. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  20825. /** Billboard on all axes */
  20826. get: function () {
  20827. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  20828. },
  20829. enumerable: true,
  20830. configurable: true
  20831. });
  20832. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  20833. /**
  20834. * Gets the number of facets in the mesh
  20835. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20836. */
  20837. get: function () {
  20838. return this._facetData.facetNb;
  20839. },
  20840. enumerable: true,
  20841. configurable: true
  20842. });
  20843. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  20844. /**
  20845. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  20846. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20847. */
  20848. get: function () {
  20849. return this._facetData.partitioningSubdivisions;
  20850. },
  20851. set: function (nb) {
  20852. this._facetData.partitioningSubdivisions = nb;
  20853. },
  20854. enumerable: true,
  20855. configurable: true
  20856. });
  20857. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  20858. /**
  20859. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  20860. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  20861. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  20862. */
  20863. get: function () {
  20864. return this._facetData.partitioningBBoxRatio;
  20865. },
  20866. set: function (ratio) {
  20867. this._facetData.partitioningBBoxRatio = ratio;
  20868. },
  20869. enumerable: true,
  20870. configurable: true
  20871. });
  20872. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  20873. /**
  20874. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  20875. * Works only for updatable meshes.
  20876. * Doesn't work with multi-materials
  20877. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20878. */
  20879. get: function () {
  20880. return this._facetData.facetDepthSort;
  20881. },
  20882. set: function (sort) {
  20883. this._facetData.facetDepthSort = sort;
  20884. },
  20885. enumerable: true,
  20886. configurable: true
  20887. });
  20888. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  20889. /**
  20890. * The location (Vector3) where the facet depth sort must be computed from.
  20891. * By default, the active camera position.
  20892. * Used only when facet depth sort is enabled
  20893. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  20894. */
  20895. get: function () {
  20896. return this._facetData.facetDepthSortFrom;
  20897. },
  20898. set: function (location) {
  20899. this._facetData.facetDepthSortFrom = location;
  20900. },
  20901. enumerable: true,
  20902. configurable: true
  20903. });
  20904. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20905. /**
  20906. * gets a boolean indicating if facetData is enabled
  20907. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20908. */
  20909. get: function () {
  20910. return this._facetData.facetDataEnabled;
  20911. },
  20912. enumerable: true,
  20913. configurable: true
  20914. });
  20915. /** @hidden */
  20916. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20917. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20918. return false;
  20919. }
  20920. this._markSubMeshesAsMiscDirty();
  20921. return true;
  20922. };
  20923. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20924. /** Set a function to call when this mesh collides with another one */
  20925. set: function (callback) {
  20926. if (this._onCollideObserver) {
  20927. this.onCollideObservable.remove(this._onCollideObserver);
  20928. }
  20929. this._onCollideObserver = this.onCollideObservable.add(callback);
  20930. },
  20931. enumerable: true,
  20932. configurable: true
  20933. });
  20934. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20935. /** Set a function to call when the collision's position changes */
  20936. set: function (callback) {
  20937. if (this._onCollisionPositionChangeObserver) {
  20938. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20939. }
  20940. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20941. },
  20942. enumerable: true,
  20943. configurable: true
  20944. });
  20945. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20946. /**
  20947. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20948. */
  20949. get: function () {
  20950. return this._visibility;
  20951. },
  20952. /**
  20953. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20954. */
  20955. set: function (value) {
  20956. if (this._visibility === value) {
  20957. return;
  20958. }
  20959. this._visibility = value;
  20960. this._markSubMeshesAsMiscDirty();
  20961. },
  20962. enumerable: true,
  20963. configurable: true
  20964. });
  20965. Object.defineProperty(AbstractMesh.prototype, "material", {
  20966. /** Gets or sets current material */
  20967. get: function () {
  20968. return this._material;
  20969. },
  20970. set: function (value) {
  20971. if (this._material === value) {
  20972. return;
  20973. }
  20974. this._material = value;
  20975. if (this.onMaterialChangedObservable.hasObservers) {
  20976. this.onMaterialChangedObservable.notifyObservers(this);
  20977. }
  20978. if (!this.subMeshes) {
  20979. return;
  20980. }
  20981. this._unBindEffect();
  20982. },
  20983. enumerable: true,
  20984. configurable: true
  20985. });
  20986. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20987. /**
  20988. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20989. * @see http://doc.babylonjs.com/babylon101/shadows
  20990. */
  20991. get: function () {
  20992. return this._receiveShadows;
  20993. },
  20994. set: function (value) {
  20995. if (this._receiveShadows === value) {
  20996. return;
  20997. }
  20998. this._receiveShadows = value;
  20999. this._markSubMeshesAsLightDirty();
  21000. },
  21001. enumerable: true,
  21002. configurable: true
  21003. });
  21004. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  21005. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  21006. get: function () {
  21007. return this._hasVertexAlpha;
  21008. },
  21009. set: function (value) {
  21010. if (this._hasVertexAlpha === value) {
  21011. return;
  21012. }
  21013. this._hasVertexAlpha = value;
  21014. this._markSubMeshesAsAttributesDirty();
  21015. this._markSubMeshesAsMiscDirty();
  21016. },
  21017. enumerable: true,
  21018. configurable: true
  21019. });
  21020. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  21021. /** 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) */
  21022. get: function () {
  21023. return this._useVertexColors;
  21024. },
  21025. set: function (value) {
  21026. if (this._useVertexColors === value) {
  21027. return;
  21028. }
  21029. this._useVertexColors = value;
  21030. this._markSubMeshesAsAttributesDirty();
  21031. },
  21032. enumerable: true,
  21033. configurable: true
  21034. });
  21035. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  21036. /**
  21037. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  21038. */
  21039. get: function () {
  21040. return this._computeBonesUsingShaders;
  21041. },
  21042. set: function (value) {
  21043. if (this._computeBonesUsingShaders === value) {
  21044. return;
  21045. }
  21046. this._computeBonesUsingShaders = value;
  21047. this._markSubMeshesAsAttributesDirty();
  21048. },
  21049. enumerable: true,
  21050. configurable: true
  21051. });
  21052. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  21053. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  21054. get: function () {
  21055. return this._numBoneInfluencers;
  21056. },
  21057. set: function (value) {
  21058. if (this._numBoneInfluencers === value) {
  21059. return;
  21060. }
  21061. this._numBoneInfluencers = value;
  21062. this._markSubMeshesAsAttributesDirty();
  21063. },
  21064. enumerable: true,
  21065. configurable: true
  21066. });
  21067. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  21068. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  21069. get: function () {
  21070. return this._applyFog;
  21071. },
  21072. set: function (value) {
  21073. if (this._applyFog === value) {
  21074. return;
  21075. }
  21076. this._applyFog = value;
  21077. this._markSubMeshesAsMiscDirty();
  21078. },
  21079. enumerable: true,
  21080. configurable: true
  21081. });
  21082. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  21083. /**
  21084. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  21085. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  21086. */
  21087. get: function () {
  21088. return this._layerMask;
  21089. },
  21090. set: function (value) {
  21091. if (value === this._layerMask) {
  21092. return;
  21093. }
  21094. this._layerMask = value;
  21095. this._resyncLightSources();
  21096. },
  21097. enumerable: true,
  21098. configurable: true
  21099. });
  21100. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  21101. /**
  21102. * Gets or sets a collision mask used to mask collisions (default is -1).
  21103. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21104. */
  21105. get: function () {
  21106. return this._collisionMask;
  21107. },
  21108. set: function (mask) {
  21109. this._collisionMask = !isNaN(mask) ? mask : -1;
  21110. },
  21111. enumerable: true,
  21112. configurable: true
  21113. });
  21114. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  21115. /**
  21116. * Gets or sets the current collision group mask (-1 by default).
  21117. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  21118. */
  21119. get: function () {
  21120. return this._collisionGroup;
  21121. },
  21122. set: function (mask) {
  21123. this._collisionGroup = !isNaN(mask) ? mask : -1;
  21124. },
  21125. enumerable: true,
  21126. configurable: true
  21127. });
  21128. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  21129. /** @hidden */
  21130. get: function () {
  21131. return null;
  21132. },
  21133. enumerable: true,
  21134. configurable: true
  21135. });
  21136. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  21137. get: function () {
  21138. return this._skeleton;
  21139. },
  21140. /**
  21141. * Gets or sets a skeleton to apply skining transformations
  21142. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  21143. */
  21144. set: function (value) {
  21145. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  21146. this._skeleton._unregisterMeshWithPoseMatrix(this);
  21147. }
  21148. if (value && value.needInitialSkinMatrix) {
  21149. value._registerMeshWithPoseMatrix(this);
  21150. }
  21151. this._skeleton = value;
  21152. if (!this._skeleton) {
  21153. this._bonesTransformMatrices = null;
  21154. }
  21155. this._markSubMeshesAsAttributesDirty();
  21156. },
  21157. enumerable: true,
  21158. configurable: true
  21159. });
  21160. /**
  21161. * Returns the string "AbstractMesh"
  21162. * @returns "AbstractMesh"
  21163. */
  21164. AbstractMesh.prototype.getClassName = function () {
  21165. return "AbstractMesh";
  21166. };
  21167. /**
  21168. * Gets a string representation of the current mesh
  21169. * @param fullDetails defines a boolean indicating if full details must be included
  21170. * @returns a string representation of the current mesh
  21171. */
  21172. AbstractMesh.prototype.toString = function (fullDetails) {
  21173. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  21174. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  21175. if (this._skeleton) {
  21176. ret += ", skeleton: " + this._skeleton.name;
  21177. }
  21178. if (fullDetails) {
  21179. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  21180. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  21181. }
  21182. return ret;
  21183. };
  21184. /** @hidden */
  21185. AbstractMesh.prototype._rebuild = function () {
  21186. this.onRebuildObservable.notifyObservers(this);
  21187. if (this._occlusionQuery) {
  21188. this._occlusionQuery = null;
  21189. }
  21190. if (!this.subMeshes) {
  21191. return;
  21192. }
  21193. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21194. var subMesh = _a[_i];
  21195. subMesh._rebuild();
  21196. }
  21197. };
  21198. /** @hidden */
  21199. AbstractMesh.prototype._resyncLightSources = function () {
  21200. this._lightSources.length = 0;
  21201. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  21202. var light = _a[_i];
  21203. if (!light.isEnabled()) {
  21204. continue;
  21205. }
  21206. if (light.canAffectMesh(this)) {
  21207. this._lightSources.push(light);
  21208. }
  21209. }
  21210. this._markSubMeshesAsLightDirty();
  21211. };
  21212. /** @hidden */
  21213. AbstractMesh.prototype._resyncLighSource = function (light) {
  21214. var isIn = light.isEnabled() && light.canAffectMesh(this);
  21215. var index = this._lightSources.indexOf(light);
  21216. if (index === -1) {
  21217. if (!isIn) {
  21218. return;
  21219. }
  21220. this._lightSources.push(light);
  21221. }
  21222. else {
  21223. if (isIn) {
  21224. return;
  21225. }
  21226. this._lightSources.splice(index, 1);
  21227. }
  21228. this._markSubMeshesAsLightDirty();
  21229. };
  21230. /** @hidden */
  21231. AbstractMesh.prototype._unBindEffect = function () {
  21232. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21233. var subMesh = _a[_i];
  21234. subMesh.setEffect(null);
  21235. }
  21236. };
  21237. /** @hidden */
  21238. AbstractMesh.prototype._removeLightSource = function (light) {
  21239. var index = this._lightSources.indexOf(light);
  21240. if (index === -1) {
  21241. return;
  21242. }
  21243. this._lightSources.splice(index, 1);
  21244. this._markSubMeshesAsLightDirty();
  21245. };
  21246. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  21247. if (!this.subMeshes) {
  21248. return;
  21249. }
  21250. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21251. var subMesh = _a[_i];
  21252. if (subMesh._materialDefines) {
  21253. func(subMesh._materialDefines);
  21254. }
  21255. }
  21256. };
  21257. /** @hidden */
  21258. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  21259. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  21260. };
  21261. /** @hidden */
  21262. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  21263. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  21264. };
  21265. /** @hidden */
  21266. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  21267. if (!this.subMeshes) {
  21268. return;
  21269. }
  21270. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21271. var subMesh = _a[_i];
  21272. var material = subMesh.getMaterial();
  21273. if (material) {
  21274. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  21275. }
  21276. }
  21277. };
  21278. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  21279. /**
  21280. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  21281. */
  21282. get: function () {
  21283. return this._scaling;
  21284. },
  21285. set: function (newScaling) {
  21286. this._scaling = newScaling;
  21287. if (this.physicsImpostor) {
  21288. this.physicsImpostor.forceUpdate();
  21289. }
  21290. },
  21291. enumerable: true,
  21292. configurable: true
  21293. });
  21294. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  21295. // Methods
  21296. /**
  21297. * Returns true if the mesh is blocked. Implemented by child classes
  21298. */
  21299. get: function () {
  21300. return false;
  21301. },
  21302. enumerable: true,
  21303. configurable: true
  21304. });
  21305. /**
  21306. * Returns the mesh itself by default. Implemented by child classes
  21307. * @param camera defines the camera to use to pick the right LOD level
  21308. * @returns the currentAbstractMesh
  21309. */
  21310. AbstractMesh.prototype.getLOD = function (camera) {
  21311. return this;
  21312. };
  21313. /**
  21314. * Returns 0 by default. Implemented by child classes
  21315. * @returns an integer
  21316. */
  21317. AbstractMesh.prototype.getTotalVertices = function () {
  21318. return 0;
  21319. };
  21320. /**
  21321. * Returns null by default. Implemented by child classes
  21322. * @returns null
  21323. */
  21324. AbstractMesh.prototype.getIndices = function () {
  21325. return null;
  21326. };
  21327. /**
  21328. * Returns the array of the requested vertex data kind. Implemented by child classes
  21329. * @param kind defines the vertex data kind to use
  21330. * @returns null
  21331. */
  21332. AbstractMesh.prototype.getVerticesData = function (kind) {
  21333. return null;
  21334. };
  21335. /**
  21336. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21337. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21338. * Note that a new underlying VertexBuffer object is created each call.
  21339. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21340. * @param kind defines vertex data kind:
  21341. * * BABYLON.VertexBuffer.PositionKind
  21342. * * BABYLON.VertexBuffer.UVKind
  21343. * * BABYLON.VertexBuffer.UV2Kind
  21344. * * BABYLON.VertexBuffer.UV3Kind
  21345. * * BABYLON.VertexBuffer.UV4Kind
  21346. * * BABYLON.VertexBuffer.UV5Kind
  21347. * * BABYLON.VertexBuffer.UV6Kind
  21348. * * BABYLON.VertexBuffer.ColorKind
  21349. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21350. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21351. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21352. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21353. * @param data defines the data source
  21354. * @param updatable defines if the data must be flagged as updatable (or static)
  21355. * @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
  21356. * @returns the current mesh
  21357. */
  21358. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21359. return this;
  21360. };
  21361. /**
  21362. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21363. * If the mesh has no geometry, it is simply returned as it is.
  21364. * @param kind defines vertex data kind:
  21365. * * BABYLON.VertexBuffer.PositionKind
  21366. * * BABYLON.VertexBuffer.UVKind
  21367. * * BABYLON.VertexBuffer.UV2Kind
  21368. * * BABYLON.VertexBuffer.UV3Kind
  21369. * * BABYLON.VertexBuffer.UV4Kind
  21370. * * BABYLON.VertexBuffer.UV5Kind
  21371. * * BABYLON.VertexBuffer.UV6Kind
  21372. * * BABYLON.VertexBuffer.ColorKind
  21373. * * BABYLON.VertexBuffer.MatricesIndicesKind
  21374. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21375. * * BABYLON.VertexBuffer.MatricesWeightsKind
  21376. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21377. * @param data defines the data source
  21378. * @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
  21379. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  21380. * @returns the current mesh
  21381. */
  21382. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21383. return this;
  21384. };
  21385. /**
  21386. * Sets the mesh indices,
  21387. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21388. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  21389. * @param totalVertices Defines the total number of vertices
  21390. * @returns the current mesh
  21391. */
  21392. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  21393. return this;
  21394. };
  21395. /**
  21396. * Gets a boolean indicating if specific vertex data is present
  21397. * @param kind defines the vertex data kind to use
  21398. * @returns true is data kind is present
  21399. */
  21400. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  21401. return false;
  21402. };
  21403. /**
  21404. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  21405. * @returns a BoundingInfo
  21406. */
  21407. AbstractMesh.prototype.getBoundingInfo = function () {
  21408. if (this._masterMesh) {
  21409. return this._masterMesh.getBoundingInfo();
  21410. }
  21411. if (!this._boundingInfo) {
  21412. // this._boundingInfo is being created here
  21413. this._updateBoundingInfo();
  21414. }
  21415. // cannot be null.
  21416. return this._boundingInfo;
  21417. };
  21418. /**
  21419. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  21420. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  21421. * @returns the current mesh
  21422. */
  21423. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  21424. if (includeDescendants === void 0) { includeDescendants = true; }
  21425. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  21426. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  21427. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  21428. if (maxDimension === 0) {
  21429. return this;
  21430. }
  21431. var scale = 1 / maxDimension;
  21432. this.scaling.scaleInPlace(scale);
  21433. return this;
  21434. };
  21435. /**
  21436. * Overwrite the current bounding info
  21437. * @param boundingInfo defines the new bounding info
  21438. * @returns the current mesh
  21439. */
  21440. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  21441. this._boundingInfo = boundingInfo;
  21442. return this;
  21443. };
  21444. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  21445. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  21446. get: function () {
  21447. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  21448. },
  21449. enumerable: true,
  21450. configurable: true
  21451. });
  21452. /** @hidden */
  21453. AbstractMesh.prototype._preActivate = function () {
  21454. };
  21455. /** @hidden */
  21456. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21457. };
  21458. /** @hidden */
  21459. AbstractMesh.prototype._activate = function (renderId) {
  21460. this._renderId = renderId;
  21461. };
  21462. /**
  21463. * Gets the current world matrix
  21464. * @returns a Matrix
  21465. */
  21466. AbstractMesh.prototype.getWorldMatrix = function () {
  21467. if (this._masterMesh) {
  21468. return this._masterMesh.getWorldMatrix();
  21469. }
  21470. return _super.prototype.getWorldMatrix.call(this);
  21471. };
  21472. /** @hidden */
  21473. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  21474. if (this._masterMesh) {
  21475. return this._masterMesh._getWorldMatrixDeterminant();
  21476. }
  21477. return _super.prototype._getWorldMatrixDeterminant.call(this);
  21478. };
  21479. // ================================== Point of View Movement =================================
  21480. /**
  21481. * Perform relative position change from the point of view of behind the front of the mesh.
  21482. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21483. * Supports definition of mesh facing forward or backward
  21484. * @param amountRight defines the distance on the right axis
  21485. * @param amountUp defines the distance on the up axis
  21486. * @param amountForward defines the distance on the forward axis
  21487. * @returns the current mesh
  21488. */
  21489. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  21490. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  21491. return this;
  21492. };
  21493. /**
  21494. * Calculate relative position change from the point of view of behind the front of the mesh.
  21495. * This is performed taking into account the meshes current rotation, so you do not have to care.
  21496. * Supports definition of mesh facing forward or backward
  21497. * @param amountRight defines the distance on the right axis
  21498. * @param amountUp defines the distance on the up axis
  21499. * @param amountForward defines the distance on the forward axis
  21500. * @returns the new displacement vector
  21501. */
  21502. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  21503. var rotMatrix = new BABYLON.Matrix();
  21504. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  21505. rotQuaternion.toRotationMatrix(rotMatrix);
  21506. var translationDelta = BABYLON.Vector3.Zero();
  21507. var defForwardMult = this.definedFacingForward ? -1 : 1;
  21508. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  21509. return translationDelta;
  21510. };
  21511. // ================================== Point of View Rotation =================================
  21512. /**
  21513. * Perform relative rotation change from the point of view of behind the front of the mesh.
  21514. * Supports definition of mesh facing forward or backward
  21515. * @param flipBack defines the flip
  21516. * @param twirlClockwise defines the twirl
  21517. * @param tiltRight defines the tilt
  21518. * @returns the current mesh
  21519. */
  21520. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21521. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  21522. return this;
  21523. };
  21524. /**
  21525. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  21526. * Supports definition of mesh facing forward or backward.
  21527. * @param flipBack defines the flip
  21528. * @param twirlClockwise defines the twirl
  21529. * @param tiltRight defines the tilt
  21530. * @returns the new rotation vector
  21531. */
  21532. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  21533. var defForwardMult = this.definedFacingForward ? 1 : -1;
  21534. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  21535. };
  21536. /**
  21537. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  21538. * @param includeDescendants Include bounding info from descendants as well (true by default)
  21539. * @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
  21540. * @returns the new bounding vectors
  21541. */
  21542. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  21543. if (includeDescendants === void 0) { includeDescendants = true; }
  21544. if (predicate === void 0) { predicate = null; }
  21545. // Ensures that all world matrix will be recomputed.
  21546. this.getScene().incrementRenderId();
  21547. this.computeWorldMatrix(true);
  21548. var min;
  21549. var max;
  21550. var boundingInfo = this.getBoundingInfo();
  21551. if (!this.subMeshes) {
  21552. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  21553. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  21554. }
  21555. else {
  21556. min = boundingInfo.boundingBox.minimumWorld;
  21557. max = boundingInfo.boundingBox.maximumWorld;
  21558. }
  21559. if (includeDescendants) {
  21560. var descendants = this.getDescendants(false);
  21561. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  21562. var descendant = descendants_1[_i];
  21563. var childMesh = descendant;
  21564. childMesh.computeWorldMatrix(true);
  21565. // Filters meshes based on custom predicate function.
  21566. if (predicate && !predicate(childMesh)) {
  21567. continue;
  21568. }
  21569. //make sure we have the needed params to get mix and max
  21570. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  21571. continue;
  21572. }
  21573. var childBoundingInfo = childMesh.getBoundingInfo();
  21574. var boundingBox = childBoundingInfo.boundingBox;
  21575. var minBox = boundingBox.minimumWorld;
  21576. var maxBox = boundingBox.maximumWorld;
  21577. BABYLON.Tools.CheckExtends(minBox, min, max);
  21578. BABYLON.Tools.CheckExtends(maxBox, min, max);
  21579. }
  21580. }
  21581. return {
  21582. min: min,
  21583. max: max
  21584. };
  21585. };
  21586. /** @hidden */
  21587. AbstractMesh.prototype._updateBoundingInfo = function () {
  21588. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  21589. this._boundingInfo.update(this.worldMatrixFromCache);
  21590. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21591. return this;
  21592. };
  21593. /** @hidden */
  21594. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  21595. if (!this.subMeshes) {
  21596. return this;
  21597. }
  21598. var count = this.subMeshes.length;
  21599. for (var subIndex = 0; subIndex < count; subIndex++) {
  21600. var subMesh = this.subMeshes[subIndex];
  21601. if (count > 1 || !subMesh.IsGlobal) {
  21602. subMesh.updateBoundingInfo(matrix);
  21603. }
  21604. }
  21605. return this;
  21606. };
  21607. /** @hidden */
  21608. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  21609. // Bounding info
  21610. this._updateBoundingInfo();
  21611. };
  21612. /**
  21613. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  21614. * A mesh is in the frustum if its bounding box intersects the frustum
  21615. * @param frustumPlanes defines the frustum to test
  21616. * @returns true if the mesh is in the frustum planes
  21617. */
  21618. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  21619. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes, this.cullingStrategy);
  21620. };
  21621. /**
  21622. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  21623. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  21624. * @param frustumPlanes defines the frustum to test
  21625. * @returns true if the mesh is completely in the frustum planes
  21626. */
  21627. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  21628. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  21629. };
  21630. /**
  21631. * True if the mesh intersects another mesh or a SolidParticle object
  21632. * @param mesh defines a target mesh or SolidParticle to test
  21633. * @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)
  21634. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  21635. * @returns true if there is an intersection
  21636. */
  21637. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  21638. if (precise === void 0) { precise = false; }
  21639. if (!this._boundingInfo || !mesh._boundingInfo) {
  21640. return false;
  21641. }
  21642. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  21643. return true;
  21644. }
  21645. if (includeDescendants) {
  21646. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  21647. var child = _a[_i];
  21648. if (child.intersectsMesh(mesh, precise, true)) {
  21649. return true;
  21650. }
  21651. }
  21652. }
  21653. return false;
  21654. };
  21655. /**
  21656. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  21657. * @param point defines the point to test
  21658. * @returns true if there is an intersection
  21659. */
  21660. AbstractMesh.prototype.intersectsPoint = function (point) {
  21661. if (!this._boundingInfo) {
  21662. return false;
  21663. }
  21664. return this._boundingInfo.intersectsPoint(point);
  21665. };
  21666. /**
  21667. * Gets the position of the current mesh in camera space
  21668. * @param camera defines the camera to use
  21669. * @returns a position
  21670. */
  21671. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  21672. if (camera === void 0) { camera = null; }
  21673. if (!camera) {
  21674. camera = this.getScene().activeCamera;
  21675. }
  21676. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  21677. };
  21678. /**
  21679. * Returns the distance from the mesh to the active camera
  21680. * @param camera defines the camera to use
  21681. * @returns the distance
  21682. */
  21683. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  21684. if (camera === void 0) { camera = null; }
  21685. if (!camera) {
  21686. camera = this.getScene().activeCamera;
  21687. }
  21688. return this.absolutePosition.subtract(camera.position).length();
  21689. };
  21690. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  21691. // Collisions
  21692. /**
  21693. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  21694. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21695. */
  21696. get: function () {
  21697. return this._checkCollisions;
  21698. },
  21699. set: function (collisionEnabled) {
  21700. this._checkCollisions = collisionEnabled;
  21701. if (this.getScene().workerCollisions) {
  21702. this.getScene().collisionCoordinator.onMeshUpdated(this);
  21703. }
  21704. },
  21705. enumerable: true,
  21706. configurable: true
  21707. });
  21708. Object.defineProperty(AbstractMesh.prototype, "collider", {
  21709. /**
  21710. * Gets Collider object used to compute collisions (not physics)
  21711. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21712. */
  21713. get: function () {
  21714. return this._collider;
  21715. },
  21716. enumerable: true,
  21717. configurable: true
  21718. });
  21719. /**
  21720. * Move the mesh using collision engine
  21721. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  21722. * @param displacement defines the requested displacement vector
  21723. * @returns the current mesh
  21724. */
  21725. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  21726. var globalPosition = this.getAbsolutePosition();
  21727. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  21728. if (!this._collider) {
  21729. this._collider = new BABYLON.Collider();
  21730. }
  21731. this._collider._radius = this.ellipsoid;
  21732. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  21733. return this;
  21734. };
  21735. // Collisions
  21736. /** @hidden */
  21737. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  21738. this._generatePointsArray();
  21739. if (!this._positions) {
  21740. return this;
  21741. }
  21742. // Transformation
  21743. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  21744. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  21745. subMesh._lastColliderWorldVertices = [];
  21746. subMesh._trianglePlanes = [];
  21747. var start = subMesh.verticesStart;
  21748. var end = (subMesh.verticesStart + subMesh.verticesCount);
  21749. for (var i = start; i < end; i++) {
  21750. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  21751. }
  21752. }
  21753. // Collide
  21754. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  21755. if (collider.collisionFound) {
  21756. collider.collidedMesh = this;
  21757. }
  21758. return this;
  21759. };
  21760. /** @hidden */
  21761. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  21762. var subMeshes = this._scene.getCollidingSubMeshCandidates(this, collider);
  21763. var len = subMeshes.length;
  21764. for (var index = 0; index < len; index++) {
  21765. var subMesh = subMeshes.data[index];
  21766. // Bounding test
  21767. if (len > 1 && !subMesh._checkCollision(collider))
  21768. continue;
  21769. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21770. }
  21771. return this;
  21772. };
  21773. /** @hidden */
  21774. AbstractMesh.prototype._checkCollision = function (collider) {
  21775. // Bounding box test
  21776. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21777. return this;
  21778. // Transformation matrix
  21779. var collisionsScalingMatrix = BABYLON.Tmp.Matrix[0];
  21780. var collisionsTransformMatrix = BABYLON.Tmp.Matrix[1];
  21781. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, collisionsScalingMatrix);
  21782. this.worldMatrixFromCache.multiplyToRef(collisionsScalingMatrix, collisionsTransformMatrix);
  21783. this._processCollisionsForSubMeshes(collider, collisionsTransformMatrix);
  21784. return this;
  21785. };
  21786. // Picking
  21787. /** @hidden */
  21788. AbstractMesh.prototype._generatePointsArray = function () {
  21789. return false;
  21790. };
  21791. /**
  21792. * Checks if the passed Ray intersects with the mesh
  21793. * @param ray defines the ray to use
  21794. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21795. * @returns the picking info
  21796. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21797. */
  21798. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21799. var pickingInfo = new BABYLON.PickingInfo();
  21800. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21801. return pickingInfo;
  21802. }
  21803. if (!this._generatePointsArray()) {
  21804. return pickingInfo;
  21805. }
  21806. var intersectInfo = null;
  21807. var subMeshes = this._scene.getIntersectingSubMeshCandidates(this, ray);
  21808. var len = subMeshes.length;
  21809. for (var index = 0; index < len; index++) {
  21810. var subMesh = subMeshes.data[index];
  21811. // Bounding test
  21812. if (len > 1 && !subMesh.canIntersects(ray))
  21813. continue;
  21814. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21815. if (currentIntersectInfo) {
  21816. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21817. intersectInfo = currentIntersectInfo;
  21818. intersectInfo.subMeshId = index;
  21819. if (fastCheck) {
  21820. break;
  21821. }
  21822. }
  21823. }
  21824. }
  21825. if (intersectInfo) {
  21826. // Get picked point
  21827. var world = this.getWorldMatrix();
  21828. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21829. var direction = ray.direction.clone();
  21830. direction = direction.scale(intersectInfo.distance);
  21831. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21832. var pickedPoint = worldOrigin.add(worldDirection);
  21833. // Return result
  21834. pickingInfo.hit = true;
  21835. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21836. pickingInfo.pickedPoint = pickedPoint;
  21837. pickingInfo.pickedMesh = this;
  21838. pickingInfo.bu = intersectInfo.bu || 0;
  21839. pickingInfo.bv = intersectInfo.bv || 0;
  21840. pickingInfo.faceId = intersectInfo.faceId;
  21841. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21842. return pickingInfo;
  21843. }
  21844. return pickingInfo;
  21845. };
  21846. /**
  21847. * Clones the current mesh
  21848. * @param name defines the mesh name
  21849. * @param newParent defines the new mesh parent
  21850. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21851. * @returns the new mesh
  21852. */
  21853. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21854. return null;
  21855. };
  21856. /**
  21857. * Disposes all the submeshes of the current meshnp
  21858. * @returns the current mesh
  21859. */
  21860. AbstractMesh.prototype.releaseSubMeshes = function () {
  21861. if (this.subMeshes) {
  21862. while (this.subMeshes.length) {
  21863. this.subMeshes[0].dispose();
  21864. }
  21865. }
  21866. else {
  21867. this.subMeshes = new Array();
  21868. }
  21869. return this;
  21870. };
  21871. /**
  21872. * Releases resources associated with this abstract mesh.
  21873. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21874. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21875. */
  21876. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21877. var _this = this;
  21878. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21879. var index;
  21880. // Smart Array Retainers.
  21881. this.getScene().freeActiveMeshes();
  21882. this.getScene().freeRenderingGroups();
  21883. // Action manager
  21884. if (this.actionManager !== undefined && this.actionManager !== null) {
  21885. this.actionManager.dispose();
  21886. this.actionManager = null;
  21887. }
  21888. // Skeleton
  21889. this._skeleton = null;
  21890. // Intersections in progress
  21891. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21892. var other = this._intersectionsInProgress[index];
  21893. var pos = other._intersectionsInProgress.indexOf(this);
  21894. other._intersectionsInProgress.splice(pos, 1);
  21895. }
  21896. this._intersectionsInProgress = [];
  21897. // Lights
  21898. var lights = this.getScene().lights;
  21899. lights.forEach(function (light) {
  21900. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21901. if (meshIndex !== -1) {
  21902. light.includedOnlyMeshes.splice(meshIndex, 1);
  21903. }
  21904. meshIndex = light.excludedMeshes.indexOf(_this);
  21905. if (meshIndex !== -1) {
  21906. light.excludedMeshes.splice(meshIndex, 1);
  21907. }
  21908. // Shadow generators
  21909. var generator = light.getShadowGenerator();
  21910. if (generator) {
  21911. var shadowMap = generator.getShadowMap();
  21912. if (shadowMap && shadowMap.renderList) {
  21913. meshIndex = shadowMap.renderList.indexOf(_this);
  21914. if (meshIndex !== -1) {
  21915. shadowMap.renderList.splice(meshIndex, 1);
  21916. }
  21917. }
  21918. }
  21919. });
  21920. // SubMeshes
  21921. if (this.getClassName() !== "InstancedMesh") {
  21922. this.releaseSubMeshes();
  21923. }
  21924. // Query
  21925. var engine = this.getScene().getEngine();
  21926. if (this._occlusionQuery) {
  21927. this.isOcclusionQueryInProgress = false;
  21928. engine.deleteQuery(this._occlusionQuery);
  21929. this._occlusionQuery = null;
  21930. }
  21931. // Engine
  21932. engine.wipeCaches();
  21933. // Remove from scene
  21934. this.getScene().removeMesh(this);
  21935. if (disposeMaterialAndTextures) {
  21936. if (this.material) {
  21937. this.material.dispose(false, true);
  21938. }
  21939. }
  21940. if (!doNotRecurse) {
  21941. // Particles
  21942. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21943. if (this.getScene().particleSystems[index].emitter === this) {
  21944. this.getScene().particleSystems[index].dispose();
  21945. index--;
  21946. }
  21947. }
  21948. }
  21949. // facet data
  21950. if (this._facetData.facetDataEnabled) {
  21951. this.disableFacetData();
  21952. }
  21953. this.onAfterWorldMatrixUpdateObservable.clear();
  21954. this.onCollideObservable.clear();
  21955. this.onCollisionPositionChangeObservable.clear();
  21956. this.onRebuildObservable.clear();
  21957. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21958. };
  21959. /**
  21960. * Adds the passed mesh as a child to the current mesh
  21961. * @param mesh defines the child mesh
  21962. * @returns the current mesh
  21963. */
  21964. AbstractMesh.prototype.addChild = function (mesh) {
  21965. mesh.setParent(this);
  21966. return this;
  21967. };
  21968. /**
  21969. * Removes the passed mesh from the current mesh children list
  21970. * @param mesh defines the child mesh
  21971. * @returns the current mesh
  21972. */
  21973. AbstractMesh.prototype.removeChild = function (mesh) {
  21974. mesh.setParent(null);
  21975. return this;
  21976. };
  21977. // Facet data
  21978. /** @hidden */
  21979. AbstractMesh.prototype._initFacetData = function () {
  21980. var data = this._facetData;
  21981. if (!data.facetNormals) {
  21982. data.facetNormals = new Array();
  21983. }
  21984. if (!data.facetPositions) {
  21985. data.facetPositions = new Array();
  21986. }
  21987. if (!data.facetPartitioning) {
  21988. data.facetPartitioning = new Array();
  21989. }
  21990. data.facetNb = (this.getIndices().length / 3) | 0;
  21991. data.partitioningSubdivisions = (data.partitioningSubdivisions) ? data.partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21992. data.partitioningBBoxRatio = (data.partitioningBBoxRatio) ? data.partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21993. for (var f = 0; f < data.facetNb; f++) {
  21994. data.facetNormals[f] = BABYLON.Vector3.Zero();
  21995. data.facetPositions[f] = BABYLON.Vector3.Zero();
  21996. }
  21997. data.facetDataEnabled = true;
  21998. return this;
  21999. };
  22000. /**
  22001. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  22002. * This method can be called within the render loop.
  22003. * 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
  22004. * @returns the current mesh
  22005. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22006. */
  22007. AbstractMesh.prototype.updateFacetData = function () {
  22008. var data = this._facetData;
  22009. if (!data.facetDataEnabled) {
  22010. this._initFacetData();
  22011. }
  22012. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22013. var indices = this.getIndices();
  22014. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22015. var bInfo = this.getBoundingInfo();
  22016. if (data.facetDepthSort && !data.facetDepthSortEnabled) {
  22017. // init arrays, matrix and sort function on first call
  22018. data.facetDepthSortEnabled = true;
  22019. if (indices instanceof Uint16Array) {
  22020. data.depthSortedIndices = new Uint16Array(indices);
  22021. }
  22022. else if (indices instanceof Uint32Array) {
  22023. data.depthSortedIndices = new Uint32Array(indices);
  22024. }
  22025. else {
  22026. var needs32bits = false;
  22027. for (var i = 0; i < indices.length; i++) {
  22028. if (indices[i] > 65535) {
  22029. needs32bits = true;
  22030. break;
  22031. }
  22032. }
  22033. if (needs32bits) {
  22034. data.depthSortedIndices = new Uint32Array(indices);
  22035. }
  22036. else {
  22037. data.depthSortedIndices = new Uint16Array(indices);
  22038. }
  22039. }
  22040. data.facetDepthSortFunction = function (f1, f2) {
  22041. return (f2.sqDistance - f1.sqDistance);
  22042. };
  22043. if (!data.facetDepthSortFrom) {
  22044. var camera = this.getScene().activeCamera;
  22045. data.facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  22046. }
  22047. data.depthSortedFacets = [];
  22048. for (var f = 0; f < data.facetNb; f++) {
  22049. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  22050. data.depthSortedFacets.push(depthSortedFacet);
  22051. }
  22052. data.invertedMatrix = BABYLON.Matrix.Identity();
  22053. data.facetDepthSortOrigin = BABYLON.Vector3.Zero();
  22054. }
  22055. data.bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  22056. data.bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  22057. data.bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  22058. var bbSizeMax = (data.bbSize.x > data.bbSize.y) ? data.bbSize.x : data.bbSize.y;
  22059. bbSizeMax = (bbSizeMax > data.bbSize.z) ? bbSizeMax : data.bbSize.z;
  22060. data.subDiv.max = data.partitioningSubdivisions;
  22061. data.subDiv.X = Math.floor(data.subDiv.max * data.bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  22062. data.subDiv.Y = Math.floor(data.subDiv.max * data.bbSize.y / bbSizeMax); // according to each bbox size per axis
  22063. data.subDiv.Z = Math.floor(data.subDiv.max * data.bbSize.z / bbSizeMax);
  22064. data.subDiv.X = data.subDiv.X < 1 ? 1 : data.subDiv.X; // at least one subdivision
  22065. data.subDiv.Y = data.subDiv.Y < 1 ? 1 : data.subDiv.Y;
  22066. data.subDiv.Z = data.subDiv.Z < 1 ? 1 : data.subDiv.Z;
  22067. // set the parameters for ComputeNormals()
  22068. data.facetParameters.facetNormals = this.getFacetLocalNormals();
  22069. data.facetParameters.facetPositions = this.getFacetLocalPositions();
  22070. data.facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  22071. data.facetParameters.bInfo = bInfo;
  22072. data.facetParameters.bbSize = data.bbSize;
  22073. data.facetParameters.subDiv = data.subDiv;
  22074. data.facetParameters.ratio = this.partitioningBBoxRatio;
  22075. data.facetParameters.depthSort = data.facetDepthSort;
  22076. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22077. this.computeWorldMatrix(true);
  22078. this._worldMatrix.invertToRef(data.invertedMatrix);
  22079. BABYLON.Vector3.TransformCoordinatesToRef(data.facetDepthSortFrom, data.invertedMatrix, data.facetDepthSortOrigin);
  22080. data.facetParameters.distanceTo = data.facetDepthSortOrigin;
  22081. }
  22082. data.facetParameters.depthSortedFacets = data.depthSortedFacets;
  22083. BABYLON.VertexData.ComputeNormals(positions, indices, normals, data.facetParameters);
  22084. if (data.facetDepthSort && data.facetDepthSortEnabled) {
  22085. data.depthSortedFacets.sort(data.facetDepthSortFunction);
  22086. var l = (data.depthSortedIndices.length / 3) | 0;
  22087. for (var f = 0; f < l; f++) {
  22088. var sind = data.depthSortedFacets[f].ind;
  22089. data.depthSortedIndices[f * 3] = indices[sind];
  22090. data.depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  22091. data.depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  22092. }
  22093. this.updateIndices(data.depthSortedIndices);
  22094. }
  22095. return this;
  22096. };
  22097. /**
  22098. * Returns the facetLocalNormals array.
  22099. * The normals are expressed in the mesh local spac
  22100. * @returns an array of Vector3
  22101. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22102. */
  22103. AbstractMesh.prototype.getFacetLocalNormals = function () {
  22104. if (!this._facetData.facetNormals) {
  22105. this.updateFacetData();
  22106. }
  22107. return this._facetData.facetNormals;
  22108. };
  22109. /**
  22110. * Returns the facetLocalPositions array.
  22111. * The facet positions are expressed in the mesh local space
  22112. * @returns an array of Vector3
  22113. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22114. */
  22115. AbstractMesh.prototype.getFacetLocalPositions = function () {
  22116. if (!this._facetData.facetPositions) {
  22117. this.updateFacetData();
  22118. }
  22119. return this._facetData.facetPositions;
  22120. };
  22121. /**
  22122. * Returns the facetLocalPartioning array
  22123. * @returns an array of array of numbers
  22124. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22125. */
  22126. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  22127. if (!this._facetData.facetPartitioning) {
  22128. this.updateFacetData();
  22129. }
  22130. return this._facetData.facetPartitioning;
  22131. };
  22132. /**
  22133. * Returns the i-th facet position in the world system.
  22134. * This method allocates a new Vector3 per call
  22135. * @param i defines the facet index
  22136. * @returns a new Vector3
  22137. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22138. */
  22139. AbstractMesh.prototype.getFacetPosition = function (i) {
  22140. var pos = BABYLON.Vector3.Zero();
  22141. this.getFacetPositionToRef(i, pos);
  22142. return pos;
  22143. };
  22144. /**
  22145. * Sets the reference Vector3 with the i-th facet position in the world system
  22146. * @param i defines the facet index
  22147. * @param ref defines the target vector
  22148. * @returns the current mesh
  22149. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22150. */
  22151. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  22152. var localPos = (this.getFacetLocalPositions())[i];
  22153. var world = this.getWorldMatrix();
  22154. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  22155. return this;
  22156. };
  22157. /**
  22158. * Returns the i-th facet normal in the world system.
  22159. * This method allocates a new Vector3 per call
  22160. * @param i defines the facet index
  22161. * @returns a new Vector3
  22162. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22163. */
  22164. AbstractMesh.prototype.getFacetNormal = function (i) {
  22165. var norm = BABYLON.Vector3.Zero();
  22166. this.getFacetNormalToRef(i, norm);
  22167. return norm;
  22168. };
  22169. /**
  22170. * Sets the reference Vector3 with the i-th facet normal in the world system
  22171. * @param i defines the facet index
  22172. * @param ref defines the target vector
  22173. * @returns the current mesh
  22174. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22175. */
  22176. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  22177. var localNorm = (this.getFacetLocalNormals())[i];
  22178. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  22179. return this;
  22180. };
  22181. /**
  22182. * 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)
  22183. * @param x defines x coordinate
  22184. * @param y defines y coordinate
  22185. * @param z defines z coordinate
  22186. * @returns the array of facet indexes
  22187. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22188. */
  22189. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  22190. var bInfo = this.getBoundingInfo();
  22191. var data = this._facetData;
  22192. var ox = Math.floor((x - bInfo.minimum.x * data.partitioningBBoxRatio) * data.subDiv.X * data.partitioningBBoxRatio / data.bbSize.x);
  22193. var oy = Math.floor((y - bInfo.minimum.y * data.partitioningBBoxRatio) * data.subDiv.Y * data.partitioningBBoxRatio / data.bbSize.y);
  22194. var oz = Math.floor((z - bInfo.minimum.z * data.partitioningBBoxRatio) * data.subDiv.Z * data.partitioningBBoxRatio / data.bbSize.z);
  22195. if (ox < 0 || ox > data.subDiv.max || oy < 0 || oy > data.subDiv.max || oz < 0 || oz > data.subDiv.max) {
  22196. return null;
  22197. }
  22198. return data.facetPartitioning[ox + data.subDiv.max * oy + data.subDiv.max * data.subDiv.max * oz];
  22199. };
  22200. /**
  22201. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  22202. * @param projected sets as the (x,y,z) world projection on the facet
  22203. * @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
  22204. * @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
  22205. * @param x defines x coordinate
  22206. * @param y defines y coordinate
  22207. * @param z defines z coordinate
  22208. * @returns the face index if found (or null instead)
  22209. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22210. */
  22211. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  22212. if (checkFace === void 0) { checkFace = false; }
  22213. if (facing === void 0) { facing = true; }
  22214. var world = this.getWorldMatrix();
  22215. var invMat = BABYLON.Tmp.Matrix[5];
  22216. world.invertToRef(invMat);
  22217. var invVect = BABYLON.Tmp.Vector3[8];
  22218. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  22219. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  22220. if (projected) {
  22221. // tranform the local computed projected vector to world coordinates
  22222. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  22223. }
  22224. return closest;
  22225. };
  22226. /**
  22227. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  22228. * @param projected sets as the (x,y,z) local projection on the facet
  22229. * @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
  22230. * @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
  22231. * @param x defines x coordinate
  22232. * @param y defines y coordinate
  22233. * @param z defines z coordinate
  22234. * @returns the face index if found (or null instead)
  22235. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22236. */
  22237. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  22238. if (checkFace === void 0) { checkFace = false; }
  22239. if (facing === void 0) { facing = true; }
  22240. var closest = null;
  22241. var tmpx = 0.0;
  22242. var tmpy = 0.0;
  22243. var tmpz = 0.0;
  22244. var d = 0.0; // tmp dot facet normal * facet position
  22245. var t0 = 0.0;
  22246. var projx = 0.0;
  22247. var projy = 0.0;
  22248. var projz = 0.0;
  22249. // Get all the facets in the same partitioning block than (x, y, z)
  22250. var facetPositions = this.getFacetLocalPositions();
  22251. var facetNormals = this.getFacetLocalNormals();
  22252. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  22253. if (!facetsInBlock) {
  22254. return null;
  22255. }
  22256. // Get the closest facet to (x, y, z)
  22257. var shortest = Number.MAX_VALUE; // init distance vars
  22258. var tmpDistance = shortest;
  22259. var fib; // current facet in the block
  22260. var norm; // current facet normal
  22261. var p0; // current facet barycenter position
  22262. // loop on all the facets in the current partitioning block
  22263. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  22264. fib = facetsInBlock[idx];
  22265. norm = facetNormals[fib];
  22266. p0 = facetPositions[fib];
  22267. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  22268. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  22269. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  22270. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  22271. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  22272. projx = x + norm.x * t0;
  22273. projy = y + norm.y * t0;
  22274. projz = z + norm.z * t0;
  22275. tmpx = projx - x;
  22276. tmpy = projy - y;
  22277. tmpz = projz - z;
  22278. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  22279. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  22280. shortest = tmpDistance;
  22281. closest = fib;
  22282. if (projected) {
  22283. projected.x = projx;
  22284. projected.y = projy;
  22285. projected.z = projz;
  22286. }
  22287. }
  22288. }
  22289. }
  22290. return closest;
  22291. };
  22292. /**
  22293. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  22294. * @returns the parameters
  22295. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22296. */
  22297. AbstractMesh.prototype.getFacetDataParameters = function () {
  22298. return this._facetData.facetParameters;
  22299. };
  22300. /**
  22301. * Disables the feature FacetData and frees the related memory
  22302. * @returns the current mesh
  22303. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  22304. */
  22305. AbstractMesh.prototype.disableFacetData = function () {
  22306. if (this._facetData.facetDataEnabled) {
  22307. this._facetData.facetDataEnabled = false;
  22308. this._facetData.facetPositions = new Array();
  22309. this._facetData.facetNormals = new Array();
  22310. this._facetData.facetPartitioning = new Array();
  22311. this._facetData.facetParameters = null;
  22312. this._facetData.depthSortedIndices = new Uint32Array(0);
  22313. }
  22314. return this;
  22315. };
  22316. /**
  22317. * Updates the AbstractMesh indices array
  22318. * @param indices defines the data source
  22319. * @returns the current mesh
  22320. */
  22321. AbstractMesh.prototype.updateIndices = function (indices) {
  22322. return this;
  22323. };
  22324. /**
  22325. * Creates new normals data for the mesh
  22326. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  22327. * @returns the current mesh
  22328. */
  22329. AbstractMesh.prototype.createNormals = function (updatable) {
  22330. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22331. var indices = this.getIndices();
  22332. var normals;
  22333. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22334. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22335. }
  22336. else {
  22337. normals = [];
  22338. }
  22339. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  22340. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  22341. return this;
  22342. };
  22343. /**
  22344. * Align the mesh with a normal
  22345. * @param normal defines the normal to use
  22346. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  22347. * @returns the current mesh
  22348. */
  22349. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  22350. if (!upDirection) {
  22351. upDirection = BABYLON.Axis.Y;
  22352. }
  22353. var axisX = BABYLON.Tmp.Vector3[0];
  22354. var axisZ = BABYLON.Tmp.Vector3[1];
  22355. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  22356. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  22357. if (this.rotationQuaternion) {
  22358. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  22359. }
  22360. else {
  22361. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  22362. }
  22363. return this;
  22364. };
  22365. /** @hidden */
  22366. AbstractMesh.prototype._checkOcclusionQuery = function () {
  22367. return false;
  22368. };
  22369. /** No occlusion */
  22370. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  22371. /** Occlusion set to optimisitic */
  22372. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  22373. /** Occlusion set to strict */
  22374. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  22375. /** Use an accurante occlusion algorithm */
  22376. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  22377. /** Use a conservative occlusion algorithm */
  22378. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  22379. /** Default culling strategy with bounding box and bounding sphere and then frustum culling */
  22380. AbstractMesh.CULLINGSTRATEGY_STANDARD = 0;
  22381. /** Culling strategy with bounding sphere only and then frustum culling */
  22382. AbstractMesh.CULLINGSTRATEGY_BOUNDINGSPHERE_ONLY = 1;
  22383. return AbstractMesh;
  22384. }(BABYLON.TransformNode));
  22385. BABYLON.AbstractMesh = AbstractMesh;
  22386. })(BABYLON || (BABYLON = {}));
  22387. //# sourceMappingURL=babylon.abstractMesh.js.map
  22388. var BABYLON;
  22389. (function (BABYLON) {
  22390. /**
  22391. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  22392. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  22393. * 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.
  22394. */
  22395. var Light = /** @class */ (function (_super) {
  22396. __extends(Light, _super);
  22397. /**
  22398. * Creates a Light object in the scene.
  22399. * Documentation : http://doc.babylonjs.com/tutorials/lights
  22400. * @param name The firendly name of the light
  22401. * @param scene The scene the light belongs too
  22402. */
  22403. function Light(name, scene) {
  22404. var _this = _super.call(this, name, scene) || this;
  22405. /**
  22406. * Diffuse gives the basic color to an object.
  22407. */
  22408. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  22409. /**
  22410. * Specular produces a highlight color on an object.
  22411. * Note: This is note affecting PBR materials.
  22412. */
  22413. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  22414. /**
  22415. * Defines the falloff type for this light. This lets overrriding how punctual light are
  22416. * falling off base on range or angle.
  22417. * This can be set to any values in Light.FALLOFF_x.
  22418. *
  22419. * Note: This is only usefull for PBR Materials at the moment. This could be extended if required to
  22420. * other types of materials.
  22421. */
  22422. _this.falloffType = Light.FALLOFF_DEFAULT;
  22423. /**
  22424. * Strength of the light.
  22425. * Note: By default it is define in the framework own unit.
  22426. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  22427. */
  22428. _this.intensity = 1.0;
  22429. _this._range = Number.MAX_VALUE;
  22430. _this._inverseSquaredRange = 0;
  22431. /**
  22432. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  22433. * of light.
  22434. */
  22435. _this._photometricScale = 1.0;
  22436. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  22437. _this._radius = 0.00001;
  22438. /**
  22439. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  22440. * exceeding the number allowed of the materials.
  22441. */
  22442. _this.renderPriority = 0;
  22443. _this._shadowEnabled = true;
  22444. _this._excludeWithLayerMask = 0;
  22445. _this._includeOnlyWithLayerMask = 0;
  22446. _this._lightmapMode = 0;
  22447. /**
  22448. * @hidden Internal use only.
  22449. */
  22450. _this._excludedMeshesIds = new Array();
  22451. /**
  22452. * @hidden Internal use only.
  22453. */
  22454. _this._includedOnlyMeshesIds = new Array();
  22455. _this.getScene().addLight(_this);
  22456. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  22457. _this._buildUniformLayout();
  22458. _this.includedOnlyMeshes = new Array();
  22459. _this.excludedMeshes = new Array();
  22460. _this._resyncMeshes();
  22461. return _this;
  22462. }
  22463. Object.defineProperty(Light.prototype, "range", {
  22464. /**
  22465. * Defines how far from the source the light is impacting in scene units.
  22466. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22467. */
  22468. get: function () {
  22469. return this._range;
  22470. },
  22471. /**
  22472. * Defines how far from the source the light is impacting in scene units.
  22473. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  22474. */
  22475. set: function (value) {
  22476. this._range = value;
  22477. this._inverseSquaredRange = 1.0 / (this.range * this.range);
  22478. },
  22479. enumerable: true,
  22480. configurable: true
  22481. });
  22482. Object.defineProperty(Light.prototype, "intensityMode", {
  22483. /**
  22484. * Gets the photometric scale used to interpret the intensity.
  22485. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22486. */
  22487. get: function () {
  22488. return this._intensityMode;
  22489. },
  22490. /**
  22491. * Sets the photometric scale used to interpret the intensity.
  22492. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  22493. */
  22494. set: function (value) {
  22495. this._intensityMode = value;
  22496. this._computePhotometricScale();
  22497. },
  22498. enumerable: true,
  22499. configurable: true
  22500. });
  22501. ;
  22502. ;
  22503. Object.defineProperty(Light.prototype, "radius", {
  22504. /**
  22505. * Gets the light radius used by PBR Materials to simulate soft area lights.
  22506. */
  22507. get: function () {
  22508. return this._radius;
  22509. },
  22510. /**
  22511. * sets the light radius used by PBR Materials to simulate soft area lights.
  22512. */
  22513. set: function (value) {
  22514. this._radius = value;
  22515. this._computePhotometricScale();
  22516. },
  22517. enumerable: true,
  22518. configurable: true
  22519. });
  22520. ;
  22521. ;
  22522. Object.defineProperty(Light.prototype, "shadowEnabled", {
  22523. /**
  22524. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22525. * the current shadow generator.
  22526. */
  22527. get: function () {
  22528. return this._shadowEnabled;
  22529. },
  22530. /**
  22531. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  22532. * the current shadow generator.
  22533. */
  22534. set: function (value) {
  22535. if (this._shadowEnabled === value) {
  22536. return;
  22537. }
  22538. this._shadowEnabled = value;
  22539. this._markMeshesAsLightDirty();
  22540. },
  22541. enumerable: true,
  22542. configurable: true
  22543. });
  22544. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  22545. /**
  22546. * Gets the only meshes impacted by this light.
  22547. */
  22548. get: function () {
  22549. return this._includedOnlyMeshes;
  22550. },
  22551. /**
  22552. * Sets the only meshes impacted by this light.
  22553. */
  22554. set: function (value) {
  22555. this._includedOnlyMeshes = value;
  22556. this._hookArrayForIncludedOnly(value);
  22557. },
  22558. enumerable: true,
  22559. configurable: true
  22560. });
  22561. Object.defineProperty(Light.prototype, "excludedMeshes", {
  22562. /**
  22563. * Gets the meshes not impacted by this light.
  22564. */
  22565. get: function () {
  22566. return this._excludedMeshes;
  22567. },
  22568. /**
  22569. * Sets the meshes not impacted by this light.
  22570. */
  22571. set: function (value) {
  22572. this._excludedMeshes = value;
  22573. this._hookArrayForExcluded(value);
  22574. },
  22575. enumerable: true,
  22576. configurable: true
  22577. });
  22578. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  22579. /**
  22580. * Gets the layer id use to find what meshes are not impacted by the light.
  22581. * Inactive if 0
  22582. */
  22583. get: function () {
  22584. return this._excludeWithLayerMask;
  22585. },
  22586. /**
  22587. * Sets the layer id use to find what meshes are not impacted by the light.
  22588. * Inactive if 0
  22589. */
  22590. set: function (value) {
  22591. this._excludeWithLayerMask = value;
  22592. this._resyncMeshes();
  22593. },
  22594. enumerable: true,
  22595. configurable: true
  22596. });
  22597. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  22598. /**
  22599. * Gets the layer id use to find what meshes are impacted by the light.
  22600. * Inactive if 0
  22601. */
  22602. get: function () {
  22603. return this._includeOnlyWithLayerMask;
  22604. },
  22605. /**
  22606. * Sets the layer id use to find what meshes are impacted by the light.
  22607. * Inactive if 0
  22608. */
  22609. set: function (value) {
  22610. this._includeOnlyWithLayerMask = value;
  22611. this._resyncMeshes();
  22612. },
  22613. enumerable: true,
  22614. configurable: true
  22615. });
  22616. Object.defineProperty(Light.prototype, "lightmapMode", {
  22617. /**
  22618. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22619. */
  22620. get: function () {
  22621. return this._lightmapMode;
  22622. },
  22623. /**
  22624. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22625. */
  22626. set: function (value) {
  22627. if (this._lightmapMode === value) {
  22628. return;
  22629. }
  22630. this._lightmapMode = value;
  22631. this._markMeshesAsLightDirty();
  22632. },
  22633. enumerable: true,
  22634. configurable: true
  22635. });
  22636. /**
  22637. * Returns the string "Light".
  22638. * @returns the class name
  22639. */
  22640. Light.prototype.getClassName = function () {
  22641. return "Light";
  22642. };
  22643. /**
  22644. * Converts the light information to a readable string for debug purpose.
  22645. * @param fullDetails Supports for multiple levels of logging within scene loading
  22646. * @returns the human readable light info
  22647. */
  22648. Light.prototype.toString = function (fullDetails) {
  22649. var ret = "Name: " + this.name;
  22650. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22651. if (this.animations) {
  22652. for (var i = 0; i < this.animations.length; i++) {
  22653. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22654. }
  22655. }
  22656. if (fullDetails) {
  22657. }
  22658. return ret;
  22659. };
  22660. /** @hidden */
  22661. Light.prototype._syncParentEnabledState = function () {
  22662. _super.prototype._syncParentEnabledState.call(this);
  22663. this._resyncMeshes();
  22664. };
  22665. /**
  22666. * Set the enabled state of this node.
  22667. * @param value - the new enabled state
  22668. */
  22669. Light.prototype.setEnabled = function (value) {
  22670. _super.prototype.setEnabled.call(this, value);
  22671. this._resyncMeshes();
  22672. };
  22673. /**
  22674. * Returns the Light associated shadow generator if any.
  22675. * @return the associated shadow generator.
  22676. */
  22677. Light.prototype.getShadowGenerator = function () {
  22678. return this._shadowGenerator;
  22679. };
  22680. /**
  22681. * Returns a Vector3, the absolute light position in the World.
  22682. * @returns the world space position of the light
  22683. */
  22684. Light.prototype.getAbsolutePosition = function () {
  22685. return BABYLON.Vector3.Zero();
  22686. };
  22687. /**
  22688. * Specifies if the light will affect the passed mesh.
  22689. * @param mesh The mesh to test against the light
  22690. * @return true the mesh is affected otherwise, false.
  22691. */
  22692. Light.prototype.canAffectMesh = function (mesh) {
  22693. if (!mesh) {
  22694. return true;
  22695. }
  22696. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22697. return false;
  22698. }
  22699. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22700. return false;
  22701. }
  22702. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22703. return false;
  22704. }
  22705. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22706. return false;
  22707. }
  22708. return true;
  22709. };
  22710. /**
  22711. * Sort function to order lights for rendering.
  22712. * @param a First Light object to compare to second.
  22713. * @param b Second Light object to compare first.
  22714. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22715. */
  22716. Light.CompareLightsPriority = function (a, b) {
  22717. //shadow-casting lights have priority over non-shadow-casting lights
  22718. //the renderPrioirty is a secondary sort criterion
  22719. if (a.shadowEnabled !== b.shadowEnabled) {
  22720. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22721. }
  22722. return b.renderPriority - a.renderPriority;
  22723. };
  22724. /**
  22725. * Releases resources associated with this node.
  22726. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22727. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22728. */
  22729. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22730. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22731. if (this._shadowGenerator) {
  22732. this._shadowGenerator.dispose();
  22733. this._shadowGenerator = null;
  22734. }
  22735. // Animations
  22736. this.getScene().stopAnimation(this);
  22737. // Remove from meshes
  22738. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22739. var mesh = _a[_i];
  22740. mesh._removeLightSource(this);
  22741. }
  22742. this._uniformBuffer.dispose();
  22743. // Remove from scene
  22744. this.getScene().removeLight(this);
  22745. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22746. };
  22747. /**
  22748. * Returns the light type ID (integer).
  22749. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22750. */
  22751. Light.prototype.getTypeID = function () {
  22752. return 0;
  22753. };
  22754. /**
  22755. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22756. * @returns the scaled intensity in intensity mode unit
  22757. */
  22758. Light.prototype.getScaledIntensity = function () {
  22759. return this._photometricScale * this.intensity;
  22760. };
  22761. /**
  22762. * Returns a new Light object, named "name", from the current one.
  22763. * @param name The name of the cloned light
  22764. * @returns the new created light
  22765. */
  22766. Light.prototype.clone = function (name) {
  22767. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22768. if (!constructor) {
  22769. return null;
  22770. }
  22771. return BABYLON.SerializationHelper.Clone(constructor, this);
  22772. };
  22773. /**
  22774. * Serializes the current light into a Serialization object.
  22775. * @returns the serialized object.
  22776. */
  22777. Light.prototype.serialize = function () {
  22778. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22779. // Type
  22780. serializationObject.type = this.getTypeID();
  22781. // Parent
  22782. if (this.parent) {
  22783. serializationObject.parentId = this.parent.id;
  22784. }
  22785. // Inclusion / exclusions
  22786. if (this.excludedMeshes.length > 0) {
  22787. serializationObject.excludedMeshesIds = [];
  22788. this.excludedMeshes.forEach(function (mesh) {
  22789. serializationObject.excludedMeshesIds.push(mesh.id);
  22790. });
  22791. }
  22792. if (this.includedOnlyMeshes.length > 0) {
  22793. serializationObject.includedOnlyMeshesIds = [];
  22794. this.includedOnlyMeshes.forEach(function (mesh) {
  22795. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22796. });
  22797. }
  22798. // Animations
  22799. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22800. serializationObject.ranges = this.serializeAnimationRanges();
  22801. return serializationObject;
  22802. };
  22803. /**
  22804. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22805. * This new light is named "name" and added to the passed scene.
  22806. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22807. * @param name The friendly name of the light
  22808. * @param scene The scene the new light will belong to
  22809. * @returns the constructor function
  22810. */
  22811. Light.GetConstructorFromName = function (type, name, scene) {
  22812. var constructorFunc = BABYLON.Node.Construct("Light_Type_" + type, name, scene);
  22813. if (constructorFunc) {
  22814. return constructorFunc;
  22815. }
  22816. // Default to no light for none present once.
  22817. return null;
  22818. };
  22819. /**
  22820. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22821. * @param parsedLight The JSON representation of the light
  22822. * @param scene The scene to create the parsed light in
  22823. * @returns the created light after parsing
  22824. */
  22825. Light.Parse = function (parsedLight, scene) {
  22826. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22827. if (!constructor) {
  22828. return null;
  22829. }
  22830. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22831. // Inclusion / exclusions
  22832. if (parsedLight.excludedMeshesIds) {
  22833. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22834. }
  22835. if (parsedLight.includedOnlyMeshesIds) {
  22836. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22837. }
  22838. // Parent
  22839. if (parsedLight.parentId) {
  22840. light._waitingParentId = parsedLight.parentId;
  22841. }
  22842. // Animations
  22843. if (parsedLight.animations) {
  22844. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22845. var parsedAnimation = parsedLight.animations[animationIndex];
  22846. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22847. }
  22848. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22849. }
  22850. if (parsedLight.autoAnimate) {
  22851. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22852. }
  22853. return light;
  22854. };
  22855. Light.prototype._hookArrayForExcluded = function (array) {
  22856. var _this = this;
  22857. var oldPush = array.push;
  22858. array.push = function () {
  22859. var items = [];
  22860. for (var _i = 0; _i < arguments.length; _i++) {
  22861. items[_i] = arguments[_i];
  22862. }
  22863. var result = oldPush.apply(array, items);
  22864. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22865. var item = items_1[_a];
  22866. item._resyncLighSource(_this);
  22867. }
  22868. return result;
  22869. };
  22870. var oldSplice = array.splice;
  22871. array.splice = function (index, deleteCount) {
  22872. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22873. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22874. var item = deleted_1[_i];
  22875. item._resyncLighSource(_this);
  22876. }
  22877. return deleted;
  22878. };
  22879. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22880. var item = array_1[_i];
  22881. item._resyncLighSource(this);
  22882. }
  22883. };
  22884. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22885. var _this = this;
  22886. var oldPush = array.push;
  22887. array.push = function () {
  22888. var items = [];
  22889. for (var _i = 0; _i < arguments.length; _i++) {
  22890. items[_i] = arguments[_i];
  22891. }
  22892. var result = oldPush.apply(array, items);
  22893. _this._resyncMeshes();
  22894. return result;
  22895. };
  22896. var oldSplice = array.splice;
  22897. array.splice = function (index, deleteCount) {
  22898. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22899. _this._resyncMeshes();
  22900. return deleted;
  22901. };
  22902. this._resyncMeshes();
  22903. };
  22904. Light.prototype._resyncMeshes = function () {
  22905. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22906. var mesh = _a[_i];
  22907. mesh._resyncLighSource(this);
  22908. }
  22909. };
  22910. /**
  22911. * Forces the meshes to update their light related information in their rendering used effects
  22912. * @hidden Internal Use Only
  22913. */
  22914. Light.prototype._markMeshesAsLightDirty = function () {
  22915. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22916. var mesh = _a[_i];
  22917. if (mesh._lightSources.indexOf(this) !== -1) {
  22918. mesh._markSubMeshesAsLightDirty();
  22919. }
  22920. }
  22921. };
  22922. /**
  22923. * Recomputes the cached photometric scale if needed.
  22924. */
  22925. Light.prototype._computePhotometricScale = function () {
  22926. this._photometricScale = this._getPhotometricScale();
  22927. this.getScene().resetCachedMaterial();
  22928. };
  22929. /**
  22930. * Returns the Photometric Scale according to the light type and intensity mode.
  22931. */
  22932. Light.prototype._getPhotometricScale = function () {
  22933. var photometricScale = 0.0;
  22934. var lightTypeID = this.getTypeID();
  22935. //get photometric mode
  22936. var photometricMode = this.intensityMode;
  22937. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22938. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22939. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22940. }
  22941. else {
  22942. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22943. }
  22944. }
  22945. //compute photometric scale
  22946. switch (lightTypeID) {
  22947. case Light.LIGHTTYPEID_POINTLIGHT:
  22948. case Light.LIGHTTYPEID_SPOTLIGHT:
  22949. switch (photometricMode) {
  22950. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22951. photometricScale = 1.0 / (4.0 * Math.PI);
  22952. break;
  22953. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22954. photometricScale = 1.0;
  22955. break;
  22956. case Light.INTENSITYMODE_LUMINANCE:
  22957. photometricScale = this.radius * this.radius;
  22958. break;
  22959. }
  22960. break;
  22961. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22962. switch (photometricMode) {
  22963. case Light.INTENSITYMODE_ILLUMINANCE:
  22964. photometricScale = 1.0;
  22965. break;
  22966. case Light.INTENSITYMODE_LUMINANCE:
  22967. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22968. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22969. var apexAngleRadians = this.radius;
  22970. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22971. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22972. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22973. photometricScale = solidAngle;
  22974. break;
  22975. }
  22976. break;
  22977. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22978. // No fall off in hemisperic light.
  22979. photometricScale = 1.0;
  22980. break;
  22981. }
  22982. return photometricScale;
  22983. };
  22984. /**
  22985. * Reorder the light in the scene according to their defined priority.
  22986. * @hidden Internal Use Only
  22987. */
  22988. Light.prototype._reorderLightsInScene = function () {
  22989. var scene = this.getScene();
  22990. if (this._renderPriority != 0) {
  22991. scene.requireLightSorting = true;
  22992. }
  22993. this.getScene().sortLightsByPriority();
  22994. };
  22995. /**
  22996. * Falloff Default: light is falling off following the material specification:
  22997. * standard material is using standard falloff whereas pbr material can request special falloff per materials.
  22998. */
  22999. Light.FALLOFF_DEFAULT = 0;
  23000. /**
  23001. * Falloff Physical: light is falling off following the inverse squared distance law.
  23002. */
  23003. Light.FALLOFF_PHYSICAL = 1;
  23004. /**
  23005. * Falloff gltf: light is falling off as described in the gltf moving to PBR document
  23006. * to enhance interoperability with other engines.
  23007. */
  23008. Light.FALLOFF_GLTF = 2;
  23009. /**
  23010. * Falloff Standard: light is falling off like in the standard material
  23011. * to enhance interoperability with other materials.
  23012. */
  23013. Light.FALLOFF_STANDARD = 3;
  23014. //lightmapMode Consts
  23015. /**
  23016. * If every light affecting the material is in this lightmapMode,
  23017. * material.lightmapTexture adds or multiplies
  23018. * (depends on material.useLightmapAsShadowmap)
  23019. * after every other light calculations.
  23020. */
  23021. Light.LIGHTMAP_DEFAULT = 0;
  23022. /**
  23023. * material.lightmapTexture as only diffuse lighting from this light
  23024. * adds only specular lighting from this light
  23025. * adds dynamic shadows
  23026. */
  23027. Light.LIGHTMAP_SPECULAR = 1;
  23028. /**
  23029. * material.lightmapTexture as only lighting
  23030. * no light calculation from this light
  23031. * only adds dynamic shadows from this light
  23032. */
  23033. Light.LIGHTMAP_SHADOWSONLY = 2;
  23034. // Intensity Mode Consts
  23035. /**
  23036. * Each light type uses the default quantity according to its type:
  23037. * point/spot lights use luminous intensity
  23038. * directional lights use illuminance
  23039. */
  23040. Light.INTENSITYMODE_AUTOMATIC = 0;
  23041. /**
  23042. * lumen (lm)
  23043. */
  23044. Light.INTENSITYMODE_LUMINOUSPOWER = 1;
  23045. /**
  23046. * candela (lm/sr)
  23047. */
  23048. Light.INTENSITYMODE_LUMINOUSINTENSITY = 2;
  23049. /**
  23050. * lux (lm/m^2)
  23051. */
  23052. Light.INTENSITYMODE_ILLUMINANCE = 3;
  23053. /**
  23054. * nit (cd/m^2)
  23055. */
  23056. Light.INTENSITYMODE_LUMINANCE = 4;
  23057. // Light types ids const.
  23058. /**
  23059. * Light type const id of the point light.
  23060. */
  23061. Light.LIGHTTYPEID_POINTLIGHT = 0;
  23062. /**
  23063. * Light type const id of the directional light.
  23064. */
  23065. Light.LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  23066. /**
  23067. * Light type const id of the spot light.
  23068. */
  23069. Light.LIGHTTYPEID_SPOTLIGHT = 2;
  23070. /**
  23071. * Light type const id of the hemispheric light.
  23072. */
  23073. Light.LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  23074. __decorate([
  23075. BABYLON.serializeAsColor3()
  23076. ], Light.prototype, "diffuse", void 0);
  23077. __decorate([
  23078. BABYLON.serializeAsColor3()
  23079. ], Light.prototype, "specular", void 0);
  23080. __decorate([
  23081. BABYLON.serialize()
  23082. ], Light.prototype, "falloffType", void 0);
  23083. __decorate([
  23084. BABYLON.serialize()
  23085. ], Light.prototype, "intensity", void 0);
  23086. __decorate([
  23087. BABYLON.serialize()
  23088. ], Light.prototype, "range", null);
  23089. __decorate([
  23090. BABYLON.serialize()
  23091. ], Light.prototype, "intensityMode", null);
  23092. __decorate([
  23093. BABYLON.serialize()
  23094. ], Light.prototype, "radius", null);
  23095. __decorate([
  23096. BABYLON.serialize()
  23097. ], Light.prototype, "_renderPriority", void 0);
  23098. __decorate([
  23099. BABYLON.expandToProperty("_reorderLightsInScene")
  23100. ], Light.prototype, "renderPriority", void 0);
  23101. __decorate([
  23102. BABYLON.serialize("shadowEnabled")
  23103. ], Light.prototype, "_shadowEnabled", void 0);
  23104. __decorate([
  23105. BABYLON.serialize("excludeWithLayerMask")
  23106. ], Light.prototype, "_excludeWithLayerMask", void 0);
  23107. __decorate([
  23108. BABYLON.serialize("includeOnlyWithLayerMask")
  23109. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  23110. __decorate([
  23111. BABYLON.serialize("lightmapMode")
  23112. ], Light.prototype, "_lightmapMode", void 0);
  23113. return Light;
  23114. }(BABYLON.Node));
  23115. BABYLON.Light = Light;
  23116. })(BABYLON || (BABYLON = {}));
  23117. //# sourceMappingURL=babylon.light.js.map
  23118. var BABYLON;
  23119. (function (BABYLON) {
  23120. /**
  23121. * This is the base class of all the camera used in the application.
  23122. * @see http://doc.babylonjs.com/features/cameras
  23123. */
  23124. var Camera = /** @class */ (function (_super) {
  23125. __extends(Camera, _super);
  23126. /**
  23127. * Instantiates a new camera object.
  23128. * This should not be used directly but through the inherited cameras: ArcRotate, Free...
  23129. * @see http://doc.babylonjs.com/features/cameras
  23130. * @param name Defines the name of the camera in the scene
  23131. * @param position Defines the position of the camera
  23132. * @param scene Defines the scene the camera belongs too
  23133. * @param setActiveOnSceneIfNoneActive Defines if the camera should be set as active after creation if no other camera have been defined in the scene
  23134. */
  23135. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  23136. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  23137. var _this = _super.call(this, name, scene) || this;
  23138. /**
  23139. * The vector the camera should consider as up.
  23140. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  23141. */
  23142. _this.upVector = BABYLON.Vector3.Up();
  23143. /**
  23144. * Define the current limit on the left side for an orthographic camera
  23145. * In scene unit
  23146. */
  23147. _this.orthoLeft = null;
  23148. /**
  23149. * Define the current limit on the right side for an orthographic camera
  23150. * In scene unit
  23151. */
  23152. _this.orthoRight = null;
  23153. /**
  23154. * Define the current limit on the bottom side for an orthographic camera
  23155. * In scene unit
  23156. */
  23157. _this.orthoBottom = null;
  23158. /**
  23159. * Define the current limit on the top side for an orthographic camera
  23160. * In scene unit
  23161. */
  23162. _this.orthoTop = null;
  23163. /**
  23164. * Field Of View is set in Radians. (default is 0.8)
  23165. */
  23166. _this.fov = 0.8;
  23167. /**
  23168. * Define the minimum distance the camera can see from.
  23169. * This is important to note that the depth buffer are not infinite and the closer it starts
  23170. * the more your scene might encounter depth fighting issue.
  23171. */
  23172. _this.minZ = 1;
  23173. /**
  23174. * Define the maximum distance the camera can see to.
  23175. * This is important to note that the depth buffer are not infinite and the further it end
  23176. * the more your scene might encounter depth fighting issue.
  23177. */
  23178. _this.maxZ = 10000.0;
  23179. /**
  23180. * Define the default inertia of the camera.
  23181. * This helps giving a smooth feeling to the camera movement.
  23182. */
  23183. _this.inertia = 0.9;
  23184. /**
  23185. * Define the mode of the camera (Camera.PERSPECTIVE_CAMERA or Camera.PERSPECTIVE_ORTHOGRAPHIC)
  23186. */
  23187. _this.mode = Camera.PERSPECTIVE_CAMERA;
  23188. /**
  23189. * Define wether the camera is intermediate.
  23190. * This is usefull to not present the output directly to the screen in case of rig without post process for instance
  23191. */
  23192. _this.isIntermediate = false;
  23193. /**
  23194. * Define the viewport of the camera.
  23195. * This correspond to the portion of the screen the camera will render to in normalized 0 to 1 unit.
  23196. */
  23197. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  23198. /**
  23199. * Restricts the camera to viewing objects with the same layerMask.
  23200. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  23201. */
  23202. _this.layerMask = 0x0FFFFFFF;
  23203. /**
  23204. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  23205. */
  23206. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  23207. /**
  23208. * Rig mode of the camera.
  23209. * This is usefull to create the camera with two "eyes" instead of one to create VR or stereoscopic scenes.
  23210. * This is normally controlled byt the camera themselves as internal use.
  23211. */
  23212. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  23213. /**
  23214. * Defines the list of custom render target the camera should render to.
  23215. * This is pretty helpfull if you wish to make a camera render to a texture you could reuse somewhere
  23216. * else in the scene.
  23217. */
  23218. _this.customRenderTargets = new Array();
  23219. /**
  23220. * Observable triggered when the camera view matrix has changed.
  23221. */
  23222. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  23223. /**
  23224. * Observable triggered when the camera Projection matrix has changed.
  23225. */
  23226. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  23227. /**
  23228. * Observable triggered when the inputs have been processed.
  23229. */
  23230. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  23231. /**
  23232. * Observable triggered when reset has been called and applied to the camera.
  23233. */
  23234. _this.onRestoreStateObservable = new BABYLON.Observable();
  23235. /** @hidden */
  23236. _this._rigCameras = new Array();
  23237. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  23238. /** @hidden */
  23239. _this._skipRendering = false;
  23240. /** @hidden */
  23241. _this._projectionMatrix = new BABYLON.Matrix();
  23242. /** @hidden */
  23243. _this._postProcesses = new Array();
  23244. /** @hidden */
  23245. _this._activeMeshes = new BABYLON.SmartArray(256);
  23246. _this._globalPosition = BABYLON.Vector3.Zero();
  23247. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  23248. _this._doNotComputeProjectionMatrix = false;
  23249. _this._transformMatrix = BABYLON.Matrix.Zero();
  23250. _this._refreshFrustumPlanes = true;
  23251. _this.getScene().addCamera(_this);
  23252. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  23253. _this.getScene().activeCamera = _this;
  23254. }
  23255. _this.position = position;
  23256. return _this;
  23257. }
  23258. /**
  23259. * Store current camera state (fov, position, etc..)
  23260. * @returns the camera
  23261. */
  23262. Camera.prototype.storeState = function () {
  23263. this._stateStored = true;
  23264. this._storedFov = this.fov;
  23265. return this;
  23266. };
  23267. /**
  23268. * Restores the camera state values if it has been stored. You must call storeState() first
  23269. */
  23270. Camera.prototype._restoreStateValues = function () {
  23271. if (!this._stateStored) {
  23272. return false;
  23273. }
  23274. this.fov = this._storedFov;
  23275. return true;
  23276. };
  23277. /**
  23278. * Restored camera state. You must call storeState() first.
  23279. * @returns true if restored and false otherwise
  23280. */
  23281. Camera.prototype.restoreState = function () {
  23282. if (this._restoreStateValues()) {
  23283. this.onRestoreStateObservable.notifyObservers(this);
  23284. return true;
  23285. }
  23286. return false;
  23287. };
  23288. /**
  23289. * Gets the class name of the camera.
  23290. * @returns the class name
  23291. */
  23292. Camera.prototype.getClassName = function () {
  23293. return "Camera";
  23294. };
  23295. /**
  23296. * Gets a string representation of the camera usefull for debug purpose.
  23297. * @param fullDetails Defines that a more verboe level of logging is required
  23298. * @returns the string representation
  23299. */
  23300. Camera.prototype.toString = function (fullDetails) {
  23301. var ret = "Name: " + this.name;
  23302. ret += ", type: " + this.getClassName();
  23303. if (this.animations) {
  23304. for (var i = 0; i < this.animations.length; i++) {
  23305. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  23306. }
  23307. }
  23308. if (fullDetails) {
  23309. }
  23310. return ret;
  23311. };
  23312. Object.defineProperty(Camera.prototype, "globalPosition", {
  23313. /**
  23314. * Gets the current world space position of the camera.
  23315. */
  23316. get: function () {
  23317. return this._globalPosition;
  23318. },
  23319. enumerable: true,
  23320. configurable: true
  23321. });
  23322. /**
  23323. * Gets the list of active meshes this frame (meshes no culled or excluded by lod s in the frame)
  23324. * @returns the active meshe list
  23325. */
  23326. Camera.prototype.getActiveMeshes = function () {
  23327. return this._activeMeshes;
  23328. };
  23329. /**
  23330. * Check wether a mesh is part of the current active mesh list of the camera
  23331. * @param mesh Defines the mesh to check
  23332. * @returns true if active, false otherwise
  23333. */
  23334. Camera.prototype.isActiveMesh = function (mesh) {
  23335. return (this._activeMeshes.indexOf(mesh) !== -1);
  23336. };
  23337. /**
  23338. * Is this camera ready to be used/rendered
  23339. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  23340. * @return true if the camera is ready
  23341. */
  23342. Camera.prototype.isReady = function (completeCheck) {
  23343. if (completeCheck === void 0) { completeCheck = false; }
  23344. if (completeCheck) {
  23345. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  23346. var pp = _a[_i];
  23347. if (pp && !pp.isReady()) {
  23348. return false;
  23349. }
  23350. }
  23351. }
  23352. return _super.prototype.isReady.call(this, completeCheck);
  23353. };
  23354. /** @hidden */
  23355. Camera.prototype._initCache = function () {
  23356. _super.prototype._initCache.call(this);
  23357. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23358. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  23359. this._cache.mode = undefined;
  23360. this._cache.minZ = undefined;
  23361. this._cache.maxZ = undefined;
  23362. this._cache.fov = undefined;
  23363. this._cache.fovMode = undefined;
  23364. this._cache.aspectRatio = undefined;
  23365. this._cache.orthoLeft = undefined;
  23366. this._cache.orthoRight = undefined;
  23367. this._cache.orthoBottom = undefined;
  23368. this._cache.orthoTop = undefined;
  23369. this._cache.renderWidth = undefined;
  23370. this._cache.renderHeight = undefined;
  23371. };
  23372. /** @hidden */
  23373. Camera.prototype._updateCache = function (ignoreParentClass) {
  23374. if (!ignoreParentClass) {
  23375. _super.prototype._updateCache.call(this);
  23376. }
  23377. this._cache.position.copyFrom(this.position);
  23378. this._cache.upVector.copyFrom(this.upVector);
  23379. };
  23380. /** @hidden */
  23381. Camera.prototype._isSynchronized = function () {
  23382. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  23383. };
  23384. /** @hidden */
  23385. Camera.prototype._isSynchronizedViewMatrix = function () {
  23386. if (!_super.prototype._isSynchronized.call(this))
  23387. return false;
  23388. return this._cache.position.equals(this.position)
  23389. && this._cache.upVector.equals(this.upVector)
  23390. && this.isSynchronizedWithParent();
  23391. };
  23392. /** @hidden */
  23393. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  23394. var check = this._cache.mode === this.mode
  23395. && this._cache.minZ === this.minZ
  23396. && this._cache.maxZ === this.maxZ;
  23397. if (!check) {
  23398. return false;
  23399. }
  23400. var engine = this.getEngine();
  23401. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23402. check = this._cache.fov === this.fov
  23403. && this._cache.fovMode === this.fovMode
  23404. && this._cache.aspectRatio === engine.getAspectRatio(this);
  23405. }
  23406. else {
  23407. check = this._cache.orthoLeft === this.orthoLeft
  23408. && this._cache.orthoRight === this.orthoRight
  23409. && this._cache.orthoBottom === this.orthoBottom
  23410. && this._cache.orthoTop === this.orthoTop
  23411. && this._cache.renderWidth === engine.getRenderWidth()
  23412. && this._cache.renderHeight === engine.getRenderHeight();
  23413. }
  23414. return check;
  23415. };
  23416. /**
  23417. * Attach the input controls to a specific dom element to get the input from.
  23418. * @param element Defines the element the controls should be listened from
  23419. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  23420. */
  23421. Camera.prototype.attachControl = function (element, noPreventDefault) {
  23422. };
  23423. /**
  23424. * Detach the current controls from the specified dom element.
  23425. * @param element Defines the element to stop listening the inputs from
  23426. */
  23427. Camera.prototype.detachControl = function (element) {
  23428. };
  23429. /**
  23430. * Update the camera state according to the different inputs gathered during the frame.
  23431. */
  23432. Camera.prototype.update = function () {
  23433. this._checkInputs();
  23434. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23435. this._updateRigCameras();
  23436. }
  23437. };
  23438. /** @hidden */
  23439. Camera.prototype._checkInputs = function () {
  23440. this.onAfterCheckInputsObservable.notifyObservers(this);
  23441. };
  23442. Object.defineProperty(Camera.prototype, "rigCameras", {
  23443. /** @hidden */
  23444. get: function () {
  23445. return this._rigCameras;
  23446. },
  23447. enumerable: true,
  23448. configurable: true
  23449. });
  23450. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  23451. /**
  23452. * Gets the post process used by the rig cameras
  23453. */
  23454. get: function () {
  23455. return this._rigPostProcess;
  23456. },
  23457. enumerable: true,
  23458. configurable: true
  23459. });
  23460. /**
  23461. * Internal, gets the first post proces.
  23462. * @returns the first post process to be run on this camera.
  23463. */
  23464. Camera.prototype._getFirstPostProcess = function () {
  23465. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  23466. if (this._postProcesses[ppIndex] !== null) {
  23467. return this._postProcesses[ppIndex];
  23468. }
  23469. }
  23470. return null;
  23471. };
  23472. Camera.prototype._cascadePostProcessesToRigCams = function () {
  23473. // invalidate framebuffer
  23474. var firstPostProcess = this._getFirstPostProcess();
  23475. if (firstPostProcess) {
  23476. firstPostProcess.markTextureDirty();
  23477. }
  23478. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  23479. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  23480. var cam = this._rigCameras[i];
  23481. var rigPostProcess = cam._rigPostProcess;
  23482. // for VR rig, there does not have to be a post process
  23483. if (rigPostProcess) {
  23484. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  23485. if (isPass) {
  23486. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  23487. cam.isIntermediate = this._postProcesses.length === 0;
  23488. }
  23489. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  23490. rigPostProcess.markTextureDirty();
  23491. }
  23492. else {
  23493. cam._postProcesses = this._postProcesses.slice(0);
  23494. }
  23495. }
  23496. };
  23497. /**
  23498. * Attach a post process to the camera.
  23499. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23500. * @param postProcess The post process to attach to the camera
  23501. * @param insertAt The position of the post process in case several of them are in use in the scene
  23502. * @returns the position the post process has been inserted at
  23503. */
  23504. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  23505. if (insertAt === void 0) { insertAt = null; }
  23506. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  23507. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  23508. return 0;
  23509. }
  23510. if (insertAt == null || insertAt < 0) {
  23511. this._postProcesses.push(postProcess);
  23512. }
  23513. else if (this._postProcesses[insertAt] === null) {
  23514. this._postProcesses[insertAt] = postProcess;
  23515. }
  23516. else {
  23517. this._postProcesses.splice(insertAt, 0, postProcess);
  23518. }
  23519. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23520. return this._postProcesses.indexOf(postProcess);
  23521. };
  23522. /**
  23523. * Detach a post process to the camera.
  23524. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocesses#attach-postprocess
  23525. * @param postProcess The post process to detach from the camera
  23526. */
  23527. Camera.prototype.detachPostProcess = function (postProcess) {
  23528. var idx = this._postProcesses.indexOf(postProcess);
  23529. if (idx !== -1) {
  23530. this._postProcesses[idx] = null;
  23531. }
  23532. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  23533. };
  23534. /**
  23535. * Gets the current world matrix of the camera
  23536. */
  23537. Camera.prototype.getWorldMatrix = function () {
  23538. if (this._isSynchronizedViewMatrix()) {
  23539. return this._worldMatrix;
  23540. }
  23541. // Getting the the view matrix will also compute the world matrix.
  23542. this.getViewMatrix();
  23543. return this._worldMatrix;
  23544. };
  23545. /** @hidden */
  23546. Camera.prototype._getViewMatrix = function () {
  23547. return BABYLON.Matrix.Identity();
  23548. };
  23549. /**
  23550. * Gets the current view matrix of the camera.
  23551. * @param force forces the camera to recompute the matrix without looking at the cached state
  23552. * @returns the view matrix
  23553. */
  23554. Camera.prototype.getViewMatrix = function (force) {
  23555. if (!force && this._isSynchronizedViewMatrix()) {
  23556. return this._computedViewMatrix;
  23557. }
  23558. this.updateCache();
  23559. this._computedViewMatrix = this._getViewMatrix();
  23560. this._currentRenderId = this.getScene().getRenderId();
  23561. this._childRenderId = this._currentRenderId;
  23562. this._refreshFrustumPlanes = true;
  23563. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  23564. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  23565. }
  23566. this.onViewMatrixChangedObservable.notifyObservers(this);
  23567. this._computedViewMatrix.invertToRef(this._worldMatrix);
  23568. return this._computedViewMatrix;
  23569. };
  23570. /**
  23571. * Freeze the projection matrix.
  23572. * It will prevent the cache check of the camera projection compute and can speed up perf
  23573. * if no parameter of the camera are meant to change
  23574. * @param projection Defines manually a projection if necessary
  23575. */
  23576. Camera.prototype.freezeProjectionMatrix = function (projection) {
  23577. this._doNotComputeProjectionMatrix = true;
  23578. if (projection !== undefined) {
  23579. this._projectionMatrix = projection;
  23580. }
  23581. };
  23582. ;
  23583. /**
  23584. * Unfreeze the projection matrix if it has previously been freezed by freezeProjectionMatrix.
  23585. */
  23586. Camera.prototype.unfreezeProjectionMatrix = function () {
  23587. this._doNotComputeProjectionMatrix = false;
  23588. };
  23589. ;
  23590. /**
  23591. * Gets the current projection matrix of the camera.
  23592. * @param force forces the camera to recompute the matrix without looking at the cached state
  23593. * @returns the projection matrix
  23594. */
  23595. Camera.prototype.getProjectionMatrix = function (force) {
  23596. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  23597. return this._projectionMatrix;
  23598. }
  23599. // Cache
  23600. this._cache.mode = this.mode;
  23601. this._cache.minZ = this.minZ;
  23602. this._cache.maxZ = this.maxZ;
  23603. // Matrix
  23604. this._refreshFrustumPlanes = true;
  23605. var engine = this.getEngine();
  23606. var scene = this.getScene();
  23607. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  23608. this._cache.fov = this.fov;
  23609. this._cache.fovMode = this.fovMode;
  23610. this._cache.aspectRatio = engine.getAspectRatio(this);
  23611. if (this.minZ <= 0) {
  23612. this.minZ = 0.1;
  23613. }
  23614. if (scene.useRightHandedSystem) {
  23615. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23616. }
  23617. else {
  23618. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  23619. }
  23620. }
  23621. else {
  23622. var halfWidth = engine.getRenderWidth() / 2.0;
  23623. var halfHeight = engine.getRenderHeight() / 2.0;
  23624. if (scene.useRightHandedSystem) {
  23625. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23626. }
  23627. else {
  23628. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  23629. }
  23630. this._cache.orthoLeft = this.orthoLeft;
  23631. this._cache.orthoRight = this.orthoRight;
  23632. this._cache.orthoBottom = this.orthoBottom;
  23633. this._cache.orthoTop = this.orthoTop;
  23634. this._cache.renderWidth = engine.getRenderWidth();
  23635. this._cache.renderHeight = engine.getRenderHeight();
  23636. }
  23637. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  23638. return this._projectionMatrix;
  23639. };
  23640. /**
  23641. * Gets the transformation matrix (ie. the multiplication of view by projection matrices)
  23642. * @returns a Matrix
  23643. */
  23644. Camera.prototype.getTransformationMatrix = function () {
  23645. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  23646. return this._transformMatrix;
  23647. };
  23648. Camera.prototype._updateFrustumPlanes = function () {
  23649. if (!this._refreshFrustumPlanes) {
  23650. return;
  23651. }
  23652. this.getTransformationMatrix();
  23653. if (!this._frustumPlanes) {
  23654. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  23655. }
  23656. else {
  23657. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  23658. }
  23659. this._refreshFrustumPlanes = false;
  23660. };
  23661. /**
  23662. * Checks if a cullable object (mesh...) is in the camera frustum
  23663. * This checks the bounding box center. See isCompletelyInFrustum for a full bounding check
  23664. * @param target The object to check
  23665. * @returns true if the object is in frustum otherwise false
  23666. */
  23667. Camera.prototype.isInFrustum = function (target) {
  23668. this._updateFrustumPlanes();
  23669. return target.isInFrustum(this._frustumPlanes);
  23670. };
  23671. /**
  23672. * Checks if a cullable object (mesh...) is in the camera frustum
  23673. * Unlike isInFrustum this cheks the full bounding box
  23674. * @param target The object to check
  23675. * @returns true if the object is in frustum otherwise false
  23676. */
  23677. Camera.prototype.isCompletelyInFrustum = function (target) {
  23678. this._updateFrustumPlanes();
  23679. return target.isCompletelyInFrustum(this._frustumPlanes);
  23680. };
  23681. /**
  23682. * Gets a ray in the forward direction from the camera.
  23683. * @param length Defines the length of the ray to create
  23684. * @param transform Defines the transform to apply to the ray, by default the world matrx is used to create a workd space ray
  23685. * @param origin Defines the start point of the ray which defaults to the camera position
  23686. * @returns the forward ray
  23687. */
  23688. Camera.prototype.getForwardRay = function (length, transform, origin) {
  23689. if (length === void 0) { length = 100; }
  23690. if (!transform) {
  23691. transform = this.getWorldMatrix();
  23692. }
  23693. if (!origin) {
  23694. origin = this.position;
  23695. }
  23696. var forward = this._scene.useRightHandedSystem ? new BABYLON.Vector3(0, 0, -1) : new BABYLON.Vector3(0, 0, 1);
  23697. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  23698. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  23699. return new BABYLON.Ray(origin, direction, length);
  23700. };
  23701. /**
  23702. * Releases resources associated with this node.
  23703. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  23704. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  23705. */
  23706. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  23707. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  23708. // Observables
  23709. this.onViewMatrixChangedObservable.clear();
  23710. this.onProjectionMatrixChangedObservable.clear();
  23711. this.onAfterCheckInputsObservable.clear();
  23712. this.onRestoreStateObservable.clear();
  23713. // Inputs
  23714. if (this.inputs) {
  23715. this.inputs.clear();
  23716. }
  23717. // Animations
  23718. this.getScene().stopAnimation(this);
  23719. // Remove from scene
  23720. this.getScene().removeCamera(this);
  23721. while (this._rigCameras.length > 0) {
  23722. var camera = this._rigCameras.pop();
  23723. if (camera) {
  23724. camera.dispose();
  23725. }
  23726. }
  23727. // Postprocesses
  23728. if (this._rigPostProcess) {
  23729. this._rigPostProcess.dispose(this);
  23730. this._rigPostProcess = null;
  23731. this._postProcesses = [];
  23732. }
  23733. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23734. this._rigPostProcess = null;
  23735. this._postProcesses = [];
  23736. }
  23737. else {
  23738. var i = this._postProcesses.length;
  23739. while (--i >= 0) {
  23740. var postProcess = this._postProcesses[i];
  23741. if (postProcess) {
  23742. postProcess.dispose(this);
  23743. }
  23744. }
  23745. }
  23746. // Render targets
  23747. var i = this.customRenderTargets.length;
  23748. while (--i >= 0) {
  23749. this.customRenderTargets[i].dispose();
  23750. }
  23751. this.customRenderTargets = [];
  23752. // Active Meshes
  23753. this._activeMeshes.dispose();
  23754. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23755. };
  23756. Object.defineProperty(Camera.prototype, "leftCamera", {
  23757. /**
  23758. * Gets the left camera of a rig setup in case of Rigged Camera
  23759. */
  23760. get: function () {
  23761. if (this._rigCameras.length < 1) {
  23762. return null;
  23763. }
  23764. return this._rigCameras[0];
  23765. },
  23766. enumerable: true,
  23767. configurable: true
  23768. });
  23769. Object.defineProperty(Camera.prototype, "rightCamera", {
  23770. /**
  23771. * Gets the right camera of a rig setup in case of Rigged Camera
  23772. */
  23773. get: function () {
  23774. if (this._rigCameras.length < 2) {
  23775. return null;
  23776. }
  23777. return this._rigCameras[1];
  23778. },
  23779. enumerable: true,
  23780. configurable: true
  23781. });
  23782. /**
  23783. * Gets the left camera target of a rig setup in case of Rigged Camera
  23784. * @returns the target position
  23785. */
  23786. Camera.prototype.getLeftTarget = function () {
  23787. if (this._rigCameras.length < 1) {
  23788. return null;
  23789. }
  23790. return this._rigCameras[0].getTarget();
  23791. };
  23792. /**
  23793. * Gets the right camera target of a rig setup in case of Rigged Camera
  23794. * @returns the target position
  23795. */
  23796. Camera.prototype.getRightTarget = function () {
  23797. if (this._rigCameras.length < 2) {
  23798. return null;
  23799. }
  23800. return this._rigCameras[1].getTarget();
  23801. };
  23802. /**
  23803. * @hidden
  23804. */
  23805. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23806. if (this.cameraRigMode === mode) {
  23807. return;
  23808. }
  23809. while (this._rigCameras.length > 0) {
  23810. var camera = this._rigCameras.pop();
  23811. if (camera) {
  23812. camera.dispose();
  23813. }
  23814. }
  23815. this.cameraRigMode = mode;
  23816. this._cameraRigParams = {};
  23817. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23818. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23819. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23820. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23821. // create the rig cameras, unless none
  23822. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23823. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23824. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23825. if (leftCamera && rightCamera) {
  23826. this._rigCameras.push(leftCamera);
  23827. this._rigCameras.push(rightCamera);
  23828. }
  23829. }
  23830. switch (this.cameraRigMode) {
  23831. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23832. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23833. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23834. break;
  23835. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23836. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23837. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23838. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23839. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23840. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23841. break;
  23842. case Camera.RIG_MODE_VR:
  23843. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23844. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23845. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23846. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23847. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23848. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23849. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23850. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23851. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23852. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23853. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23854. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23855. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23856. if (metrics.compensateDistortion) {
  23857. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23858. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23859. }
  23860. break;
  23861. case Camera.RIG_MODE_WEBVR:
  23862. if (rigParams.vrDisplay) {
  23863. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23864. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23865. //Left eye
  23866. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23867. this._rigCameras[0].setCameraRigParameter("left", true);
  23868. //leaving this for future reference
  23869. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23870. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23871. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23872. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23873. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23874. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23875. this._rigCameras[0].parent = this;
  23876. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23877. //Right eye
  23878. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23879. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23880. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23881. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23882. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23883. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23884. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23885. this._rigCameras[1].parent = this;
  23886. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23887. if (Camera.UseAlternateWebVRRendering) {
  23888. this._rigCameras[1]._skipRendering = true;
  23889. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23890. }
  23891. }
  23892. break;
  23893. }
  23894. this._cascadePostProcessesToRigCams();
  23895. this.update();
  23896. };
  23897. Camera.prototype._getVRProjectionMatrix = function () {
  23898. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23899. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23900. return this._projectionMatrix;
  23901. };
  23902. Camera.prototype._updateCameraRotationMatrix = function () {
  23903. //Here for WebVR
  23904. };
  23905. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23906. //Here for WebVR
  23907. };
  23908. /**
  23909. * This function MUST be overwritten by the different WebVR cameras available.
  23910. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23911. */
  23912. Camera.prototype._getWebVRProjectionMatrix = function () {
  23913. return BABYLON.Matrix.Identity();
  23914. };
  23915. /**
  23916. * This function MUST be overwritten by the different WebVR cameras available.
  23917. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23918. */
  23919. Camera.prototype._getWebVRViewMatrix = function () {
  23920. return BABYLON.Matrix.Identity();
  23921. };
  23922. /** @hidden */
  23923. Camera.prototype.setCameraRigParameter = function (name, value) {
  23924. if (!this._cameraRigParams) {
  23925. this._cameraRigParams = {};
  23926. }
  23927. this._cameraRigParams[name] = value;
  23928. //provisionnally:
  23929. if (name === "interaxialDistance") {
  23930. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23931. }
  23932. };
  23933. /**
  23934. * needs to be overridden by children so sub has required properties to be copied
  23935. * @hidden
  23936. */
  23937. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23938. return null;
  23939. };
  23940. /**
  23941. * May need to be overridden by children
  23942. * @hidden
  23943. */
  23944. Camera.prototype._updateRigCameras = function () {
  23945. for (var i = 0; i < this._rigCameras.length; i++) {
  23946. this._rigCameras[i].minZ = this.minZ;
  23947. this._rigCameras[i].maxZ = this.maxZ;
  23948. this._rigCameras[i].fov = this.fov;
  23949. }
  23950. // only update viewport when ANAGLYPH
  23951. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23952. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23953. }
  23954. };
  23955. /** @hidden */
  23956. Camera.prototype._setupInputs = function () {
  23957. };
  23958. /**
  23959. * Serialiaze the camera setup to a json represention
  23960. * @returns the JSON representation
  23961. */
  23962. Camera.prototype.serialize = function () {
  23963. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23964. // Type
  23965. serializationObject.type = this.getClassName();
  23966. // Parent
  23967. if (this.parent) {
  23968. serializationObject.parentId = this.parent.id;
  23969. }
  23970. if (this.inputs) {
  23971. this.inputs.serialize(serializationObject);
  23972. }
  23973. // Animations
  23974. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23975. serializationObject.ranges = this.serializeAnimationRanges();
  23976. return serializationObject;
  23977. };
  23978. /**
  23979. * Clones the current camera.
  23980. * @param name The cloned camera name
  23981. * @returns the cloned camera
  23982. */
  23983. Camera.prototype.clone = function (name) {
  23984. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23985. };
  23986. /**
  23987. * Gets the direction of the camera relative to a given local axis.
  23988. * @param localAxis Defines the reference axis to provide a relative direction.
  23989. * @return the direction
  23990. */
  23991. Camera.prototype.getDirection = function (localAxis) {
  23992. var result = BABYLON.Vector3.Zero();
  23993. this.getDirectionToRef(localAxis, result);
  23994. return result;
  23995. };
  23996. /**
  23997. * Gets the direction of the camera relative to a given local axis into a passed vector.
  23998. * @param localAxis Defines the reference axis to provide a relative direction.
  23999. * @param result Defines the vector to store the result in
  24000. */
  24001. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  24002. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  24003. };
  24004. /**
  24005. * Gets a camera constructor for a given camera type
  24006. * @param type The type of the camera to construct (should be equal to one of the camera class name)
  24007. * @param name The name of the camera the result will be able to instantiate
  24008. * @param scene The scene the result will construct the camera in
  24009. * @param interaxial_distance In case of stereoscopic setup, the distance between both eyes
  24010. * @param isStereoscopicSideBySide In case of stereoscopic setup, should the sereo be side b side
  24011. * @returns a factory method to construc the camera
  24012. */
  24013. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  24014. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  24015. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  24016. var constructorFunc = BABYLON.Node.Construct(type, name, scene, {
  24017. interaxial_distance: interaxial_distance,
  24018. isStereoscopicSideBySide: isStereoscopicSideBySide
  24019. });
  24020. if (constructorFunc) {
  24021. return constructorFunc;
  24022. }
  24023. // Default to universal camera
  24024. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  24025. };
  24026. /**
  24027. * Compute the world matrix of the camera.
  24028. * @returns the camera workd matrix
  24029. */
  24030. Camera.prototype.computeWorldMatrix = function () {
  24031. return this.getWorldMatrix();
  24032. };
  24033. /**
  24034. * Parse a JSON and creates the camera from the parsed information
  24035. * @param parsedCamera The JSON to parse
  24036. * @param scene The scene to instantiate the camera in
  24037. * @returns the newly constructed camera
  24038. */
  24039. Camera.Parse = function (parsedCamera, scene) {
  24040. var type = parsedCamera.type;
  24041. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  24042. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  24043. // Parent
  24044. if (parsedCamera.parentId) {
  24045. camera._waitingParentId = parsedCamera.parentId;
  24046. }
  24047. //If camera has an input manager, let it parse inputs settings
  24048. if (camera.inputs) {
  24049. camera.inputs.parse(parsedCamera);
  24050. camera._setupInputs();
  24051. }
  24052. if (camera.setPosition) { // need to force position
  24053. camera.position.copyFromFloats(0, 0, 0);
  24054. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  24055. }
  24056. // Target
  24057. if (parsedCamera.target) {
  24058. if (camera.setTarget) {
  24059. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  24060. }
  24061. }
  24062. // Apply 3d rig, when found
  24063. if (parsedCamera.cameraRigMode) {
  24064. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  24065. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  24066. }
  24067. // Animations
  24068. if (parsedCamera.animations) {
  24069. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  24070. var parsedAnimation = parsedCamera.animations[animationIndex];
  24071. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  24072. }
  24073. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  24074. }
  24075. if (parsedCamera.autoAnimate) {
  24076. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  24077. }
  24078. return camera;
  24079. };
  24080. /**
  24081. * This is the default projection mode used by the cameras.
  24082. * It helps recreating a feeling of perspective and better appreciate depth.
  24083. * This is the best way to simulate real life cameras.
  24084. */
  24085. Camera.PERSPECTIVE_CAMERA = 0;
  24086. /**
  24087. * This helps creating camera with an orthographic mode.
  24088. * 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.
  24089. */
  24090. Camera.ORTHOGRAPHIC_CAMERA = 1;
  24091. /**
  24092. * This is the default FOV mode for perspective cameras.
  24093. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  24094. */
  24095. Camera.FOVMODE_VERTICAL_FIXED = 0;
  24096. /**
  24097. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  24098. */
  24099. Camera.FOVMODE_HORIZONTAL_FIXED = 1;
  24100. /**
  24101. * This specifies ther is no need for a camera rig.
  24102. * Basically only one eye is rendered corresponding to the camera.
  24103. */
  24104. Camera.RIG_MODE_NONE = 0;
  24105. /**
  24106. * Simulates a camera Rig with one blue eye and one red eye.
  24107. * This can be use with 3d blue and red glasses.
  24108. */
  24109. Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  24110. /**
  24111. * Defines that both eyes of the camera will be rendered side by side with a parallel target.
  24112. */
  24113. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  24114. /**
  24115. * Defines that both eyes of the camera will be rendered side by side with a none parallel target.
  24116. */
  24117. Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  24118. /**
  24119. * Defines that both eyes of the camera will be rendered over under each other.
  24120. */
  24121. Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  24122. /**
  24123. * Defines that both eyes of the camera should be renderered in a VR mode (carbox).
  24124. */
  24125. Camera.RIG_MODE_VR = 20;
  24126. /**
  24127. * Defines that both eyes of the camera should be renderered in a VR mode (webVR).
  24128. */
  24129. Camera.RIG_MODE_WEBVR = 21;
  24130. /**
  24131. * Defines if by default attaching controls should prevent the default javascript event to continue.
  24132. */
  24133. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  24134. /**
  24135. * @hidden
  24136. * Might be removed once multiview will be a thing
  24137. */
  24138. Camera.UseAlternateWebVRRendering = false;
  24139. __decorate([
  24140. BABYLON.serializeAsVector3()
  24141. ], Camera.prototype, "position", void 0);
  24142. __decorate([
  24143. BABYLON.serializeAsVector3()
  24144. ], Camera.prototype, "upVector", void 0);
  24145. __decorate([
  24146. BABYLON.serialize()
  24147. ], Camera.prototype, "orthoLeft", void 0);
  24148. __decorate([
  24149. BABYLON.serialize()
  24150. ], Camera.prototype, "orthoRight", void 0);
  24151. __decorate([
  24152. BABYLON.serialize()
  24153. ], Camera.prototype, "orthoBottom", void 0);
  24154. __decorate([
  24155. BABYLON.serialize()
  24156. ], Camera.prototype, "orthoTop", void 0);
  24157. __decorate([
  24158. BABYLON.serialize()
  24159. ], Camera.prototype, "fov", void 0);
  24160. __decorate([
  24161. BABYLON.serialize()
  24162. ], Camera.prototype, "minZ", void 0);
  24163. __decorate([
  24164. BABYLON.serialize()
  24165. ], Camera.prototype, "maxZ", void 0);
  24166. __decorate([
  24167. BABYLON.serialize()
  24168. ], Camera.prototype, "inertia", void 0);
  24169. __decorate([
  24170. BABYLON.serialize()
  24171. ], Camera.prototype, "mode", void 0);
  24172. __decorate([
  24173. BABYLON.serialize()
  24174. ], Camera.prototype, "layerMask", void 0);
  24175. __decorate([
  24176. BABYLON.serialize()
  24177. ], Camera.prototype, "fovMode", void 0);
  24178. __decorate([
  24179. BABYLON.serialize()
  24180. ], Camera.prototype, "cameraRigMode", void 0);
  24181. __decorate([
  24182. BABYLON.serialize()
  24183. ], Camera.prototype, "interaxialDistance", void 0);
  24184. __decorate([
  24185. BABYLON.serialize()
  24186. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  24187. return Camera;
  24188. }(BABYLON.Node));
  24189. BABYLON.Camera = Camera;
  24190. })(BABYLON || (BABYLON = {}));
  24191. //# sourceMappingURL=babylon.camera.js.map
  24192. var BABYLON;
  24193. (function (BABYLON) {
  24194. /**
  24195. * This is the manager responsible of all the rendering for meshes sprites and particles.
  24196. * It is enable to manage the different groups as well as the different necessary sort functions.
  24197. * This should not be used directly aside of the few static configurations
  24198. */
  24199. var RenderingManager = /** @class */ (function () {
  24200. /**
  24201. * Instantiates a new rendering group for a particular scene
  24202. * @param scene Defines the scene the groups belongs to
  24203. */
  24204. function RenderingManager(scene) {
  24205. /**
  24206. * @hidden
  24207. */
  24208. this._useSceneAutoClearSetup = false;
  24209. this._renderingGroups = new Array();
  24210. this._autoClearDepthStencil = {};
  24211. this._customOpaqueSortCompareFn = {};
  24212. this._customAlphaTestSortCompareFn = {};
  24213. this._customTransparentSortCompareFn = {};
  24214. this._renderingGroupInfo = new BABYLON.RenderingGroupInfo();
  24215. this._scene = scene;
  24216. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  24217. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  24218. }
  24219. }
  24220. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  24221. if (depth === void 0) { depth = true; }
  24222. if (stencil === void 0) { stencil = true; }
  24223. if (this._depthStencilBufferAlreadyCleaned) {
  24224. return;
  24225. }
  24226. this._scene.getEngine().clear(null, false, depth, stencil);
  24227. this._depthStencilBufferAlreadyCleaned = true;
  24228. };
  24229. /**
  24230. * Renders the entire managed groups. This is used by the scene or the different rennder targets.
  24231. * @hidden
  24232. */
  24233. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  24234. // Update the observable context (not null as it only goes away on dispose)
  24235. var info = this._renderingGroupInfo;
  24236. info.scene = this._scene;
  24237. info.camera = this._scene.activeCamera;
  24238. // Dispatch sprites
  24239. if (this._scene.spriteManagers && renderSprites) {
  24240. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  24241. var manager = this._scene.spriteManagers[index];
  24242. this.dispatchSprites(manager);
  24243. }
  24244. }
  24245. // Render
  24246. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24247. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  24248. var renderingGroup = this._renderingGroups[index];
  24249. if (!renderingGroup)
  24250. continue;
  24251. var renderingGroupMask = Math.pow(2, index);
  24252. info.renderingGroupId = index;
  24253. // Before Observable
  24254. this._scene.onBeforeRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24255. // Clear depth/stencil if needed
  24256. if (RenderingManager.AUTOCLEAR) {
  24257. var autoClear = this._useSceneAutoClearSetup ?
  24258. this._scene.getAutoClearDepthStencilSetup(index) :
  24259. this._autoClearDepthStencil[index];
  24260. if (autoClear && autoClear.autoClear) {
  24261. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  24262. }
  24263. }
  24264. // Render
  24265. for (var _i = 0, _a = this._scene._beforeRenderingGroupDrawStage; _i < _a.length; _i++) {
  24266. var step = _a[_i];
  24267. step.action(index);
  24268. }
  24269. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  24270. for (var _b = 0, _c = this._scene._afterRenderingGroupDrawStage; _b < _c.length; _b++) {
  24271. var step = _c[_b];
  24272. step.action(index);
  24273. }
  24274. // After Observable
  24275. this._scene.onAfterRenderingGroupObservable.notifyObservers(info, renderingGroupMask);
  24276. }
  24277. };
  24278. /**
  24279. * Resets the different information of the group to prepare a new frame
  24280. * @hidden
  24281. */
  24282. RenderingManager.prototype.reset = function () {
  24283. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24284. var renderingGroup = this._renderingGroups[index];
  24285. if (renderingGroup) {
  24286. renderingGroup.prepare();
  24287. }
  24288. }
  24289. };
  24290. /**
  24291. * Dispose and release the group and its associated resources.
  24292. * @hidden
  24293. */
  24294. RenderingManager.prototype.dispose = function () {
  24295. this.freeRenderingGroups();
  24296. this._renderingGroups.length = 0;
  24297. this._renderingGroupInfo = null;
  24298. };
  24299. /**
  24300. * Clear the info related to rendering groups preventing retention points during dispose.
  24301. */
  24302. RenderingManager.prototype.freeRenderingGroups = function () {
  24303. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  24304. var renderingGroup = this._renderingGroups[index];
  24305. if (renderingGroup) {
  24306. renderingGroup.dispose();
  24307. }
  24308. }
  24309. };
  24310. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  24311. if (this._renderingGroups[renderingGroupId] === undefined) {
  24312. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  24313. }
  24314. };
  24315. /**
  24316. * Add a sprite manager to the rendering manager in order to render it this frame.
  24317. * @param spriteManager Define the sprite manager to render
  24318. */
  24319. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  24320. var renderingGroupId = spriteManager.renderingGroupId || 0;
  24321. this._prepareRenderingGroup(renderingGroupId);
  24322. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  24323. };
  24324. /**
  24325. * Add a particle system to the rendering manager in order to render it this frame.
  24326. * @param particleSystem Define the particle system to render
  24327. */
  24328. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  24329. var renderingGroupId = particleSystem.renderingGroupId || 0;
  24330. this._prepareRenderingGroup(renderingGroupId);
  24331. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  24332. };
  24333. /**
  24334. * Add a submesh to the manager in order to render it this frame
  24335. * @param subMesh The submesh to dispatch
  24336. * @param mesh Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24337. * @param material Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24338. */
  24339. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  24340. if (mesh === undefined) {
  24341. mesh = subMesh.getMesh();
  24342. }
  24343. var renderingGroupId = mesh.renderingGroupId || 0;
  24344. this._prepareRenderingGroup(renderingGroupId);
  24345. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  24346. };
  24347. /**
  24348. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24349. * This allowed control for front to back rendering or reversly depending of the special needs.
  24350. *
  24351. * @param renderingGroupId The rendering group id corresponding to its index
  24352. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24353. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24354. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24355. */
  24356. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24357. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24358. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24359. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24360. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  24361. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  24362. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  24363. if (this._renderingGroups[renderingGroupId]) {
  24364. var group = this._renderingGroups[renderingGroupId];
  24365. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  24366. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  24367. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  24368. }
  24369. };
  24370. /**
  24371. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24372. *
  24373. * @param renderingGroupId The rendering group id corresponding to its index
  24374. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24375. * @param depth Automatically clears depth between groups if true and autoClear is true.
  24376. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  24377. */
  24378. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  24379. if (depth === void 0) { depth = true; }
  24380. if (stencil === void 0) { stencil = true; }
  24381. this._autoClearDepthStencil[renderingGroupId] = {
  24382. autoClear: autoClearDepthStencil,
  24383. depth: depth,
  24384. stencil: stencil
  24385. };
  24386. };
  24387. /**
  24388. * Gets the current auto clear configuration for one rendering group of the rendering
  24389. * manager.
  24390. * @param index the rendering group index to get the information for
  24391. * @returns The auto clear setup for the requested rendering group
  24392. */
  24393. RenderingManager.prototype.getAutoClearDepthStencilSetup = function (index) {
  24394. return this._autoClearDepthStencil[index];
  24395. };
  24396. /**
  24397. * The max id used for rendering groups (not included)
  24398. */
  24399. RenderingManager.MAX_RENDERINGGROUPS = 4;
  24400. /**
  24401. * The min id used for rendering groups (included)
  24402. */
  24403. RenderingManager.MIN_RENDERINGGROUPS = 0;
  24404. /**
  24405. * Used to globally prevent autoclearing scenes.
  24406. */
  24407. RenderingManager.AUTOCLEAR = true;
  24408. return RenderingManager;
  24409. }());
  24410. BABYLON.RenderingManager = RenderingManager;
  24411. })(BABYLON || (BABYLON = {}));
  24412. //# sourceMappingURL=babylon.renderingManager.js.map
  24413. var BABYLON;
  24414. (function (BABYLON) {
  24415. /**
  24416. * This represents the object necessary to create a rendering group.
  24417. * This is exclusively used and created by the rendering manager.
  24418. * To modify the behavior, you use the available helpers in your scene or meshes.
  24419. * @hidden
  24420. */
  24421. var RenderingGroup = /** @class */ (function () {
  24422. /**
  24423. * Creates a new rendering group.
  24424. * @param index The rendering group index
  24425. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  24426. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  24427. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  24428. */
  24429. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24430. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24431. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24432. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24433. this.index = index;
  24434. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  24435. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  24436. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  24437. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  24438. this._particleSystems = new BABYLON.SmartArray(256);
  24439. this._spriteManagers = new BABYLON.SmartArray(256);
  24440. this._edgesRenderers = new BABYLON.SmartArray(16);
  24441. this._scene = scene;
  24442. this.opaqueSortCompareFn = opaqueSortCompareFn;
  24443. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  24444. this.transparentSortCompareFn = transparentSortCompareFn;
  24445. }
  24446. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  24447. /**
  24448. * Set the opaque sort comparison function.
  24449. * If null the sub meshes will be render in the order they were created
  24450. */
  24451. set: function (value) {
  24452. this._opaqueSortCompareFn = value;
  24453. if (value) {
  24454. this._renderOpaque = this.renderOpaqueSorted;
  24455. }
  24456. else {
  24457. this._renderOpaque = RenderingGroup.renderUnsorted;
  24458. }
  24459. },
  24460. enumerable: true,
  24461. configurable: true
  24462. });
  24463. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  24464. /**
  24465. * Set the alpha test sort comparison function.
  24466. * If null the sub meshes will be render in the order they were created
  24467. */
  24468. set: function (value) {
  24469. this._alphaTestSortCompareFn = value;
  24470. if (value) {
  24471. this._renderAlphaTest = this.renderAlphaTestSorted;
  24472. }
  24473. else {
  24474. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  24475. }
  24476. },
  24477. enumerable: true,
  24478. configurable: true
  24479. });
  24480. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  24481. /**
  24482. * Set the transparent sort comparison function.
  24483. * If null the sub meshes will be render in the order they were created
  24484. */
  24485. set: function (value) {
  24486. if (value) {
  24487. this._transparentSortCompareFn = value;
  24488. }
  24489. else {
  24490. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  24491. }
  24492. this._renderTransparent = this.renderTransparentSorted;
  24493. },
  24494. enumerable: true,
  24495. configurable: true
  24496. });
  24497. /**
  24498. * Render all the sub meshes contained in the group.
  24499. * @param customRenderFunction Used to override the default render behaviour of the group.
  24500. * @returns true if rendered some submeshes.
  24501. */
  24502. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  24503. if (customRenderFunction) {
  24504. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  24505. return;
  24506. }
  24507. var engine = this._scene.getEngine();
  24508. // Depth only
  24509. if (this._depthOnlySubMeshes.length !== 0) {
  24510. engine.setColorWrite(false);
  24511. this._renderAlphaTest(this._depthOnlySubMeshes);
  24512. engine.setColorWrite(true);
  24513. }
  24514. // Opaque
  24515. if (this._opaqueSubMeshes.length !== 0) {
  24516. this._renderOpaque(this._opaqueSubMeshes);
  24517. }
  24518. // Alpha test
  24519. if (this._alphaTestSubMeshes.length !== 0) {
  24520. this._renderAlphaTest(this._alphaTestSubMeshes);
  24521. }
  24522. var stencilState = engine.getStencilBuffer();
  24523. engine.setStencilBuffer(false);
  24524. // Sprites
  24525. if (renderSprites) {
  24526. this._renderSprites();
  24527. }
  24528. // Particles
  24529. if (renderParticles) {
  24530. this._renderParticles(activeMeshes);
  24531. }
  24532. if (this.onBeforeTransparentRendering) {
  24533. this.onBeforeTransparentRendering();
  24534. }
  24535. // Transparent
  24536. if (this._transparentSubMeshes.length !== 0) {
  24537. this._renderTransparent(this._transparentSubMeshes);
  24538. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24539. }
  24540. // Set back stencil to false in case it changes before the edge renderer.
  24541. engine.setStencilBuffer(false);
  24542. // Edges
  24543. if (this._edgesRenderers.length) {
  24544. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  24545. this._edgesRenderers.data[edgesRendererIndex].render();
  24546. }
  24547. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24548. }
  24549. // Restore Stencil state.
  24550. engine.setStencilBuffer(stencilState);
  24551. };
  24552. /**
  24553. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  24554. * @param subMeshes The submeshes to render
  24555. */
  24556. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  24557. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  24558. };
  24559. /**
  24560. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  24561. * @param subMeshes The submeshes to render
  24562. */
  24563. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  24564. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  24565. };
  24566. /**
  24567. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  24568. * @param subMeshes The submeshes to render
  24569. */
  24570. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  24571. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  24572. };
  24573. /**
  24574. * Renders the submeshes in a specified order.
  24575. * @param subMeshes The submeshes to sort before render
  24576. * @param sortCompareFn The comparison function use to sort
  24577. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  24578. * @param transparent Specifies to activate blending if true
  24579. */
  24580. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  24581. var subIndex = 0;
  24582. var subMesh;
  24583. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  24584. for (; subIndex < subMeshes.length; subIndex++) {
  24585. subMesh = subMeshes.data[subIndex];
  24586. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  24587. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  24588. }
  24589. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  24590. if (sortCompareFn) {
  24591. sortedArray.sort(sortCompareFn);
  24592. }
  24593. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  24594. subMesh = sortedArray[subIndex];
  24595. if (transparent) {
  24596. var material = subMesh.getMaterial();
  24597. if (material && material.needDepthPrePass) {
  24598. var engine = material.getScene().getEngine();
  24599. engine.setColorWrite(false);
  24600. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  24601. subMesh.render(false);
  24602. engine.setColorWrite(true);
  24603. }
  24604. }
  24605. subMesh.render(transparent);
  24606. }
  24607. };
  24608. /**
  24609. * Renders the submeshes in the order they were dispatched (no sort applied).
  24610. * @param subMeshes The submeshes to render
  24611. */
  24612. RenderingGroup.renderUnsorted = function (subMeshes) {
  24613. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  24614. var submesh = subMeshes.data[subIndex];
  24615. submesh.render(false);
  24616. }
  24617. };
  24618. /**
  24619. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24620. * are rendered back to front if in the same alpha index.
  24621. *
  24622. * @param a The first submesh
  24623. * @param b The second submesh
  24624. * @returns The result of the comparison
  24625. */
  24626. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  24627. // Alpha index first
  24628. if (a._alphaIndex > b._alphaIndex) {
  24629. return 1;
  24630. }
  24631. if (a._alphaIndex < b._alphaIndex) {
  24632. return -1;
  24633. }
  24634. // Then distance to camera
  24635. return RenderingGroup.backToFrontSortCompare(a, b);
  24636. };
  24637. /**
  24638. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24639. * are rendered back to front.
  24640. *
  24641. * @param a The first submesh
  24642. * @param b The second submesh
  24643. * @returns The result of the comparison
  24644. */
  24645. RenderingGroup.backToFrontSortCompare = function (a, b) {
  24646. // Then distance to camera
  24647. if (a._distanceToCamera < b._distanceToCamera) {
  24648. return 1;
  24649. }
  24650. if (a._distanceToCamera > b._distanceToCamera) {
  24651. return -1;
  24652. }
  24653. return 0;
  24654. };
  24655. /**
  24656. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  24657. * are rendered front to back (prevent overdraw).
  24658. *
  24659. * @param a The first submesh
  24660. * @param b The second submesh
  24661. * @returns The result of the comparison
  24662. */
  24663. RenderingGroup.frontToBackSortCompare = function (a, b) {
  24664. // Then distance to camera
  24665. if (a._distanceToCamera < b._distanceToCamera) {
  24666. return -1;
  24667. }
  24668. if (a._distanceToCamera > b._distanceToCamera) {
  24669. return 1;
  24670. }
  24671. return 0;
  24672. };
  24673. /**
  24674. * Resets the different lists of submeshes to prepare a new frame.
  24675. */
  24676. RenderingGroup.prototype.prepare = function () {
  24677. this._opaqueSubMeshes.reset();
  24678. this._transparentSubMeshes.reset();
  24679. this._alphaTestSubMeshes.reset();
  24680. this._depthOnlySubMeshes.reset();
  24681. this._particleSystems.reset();
  24682. this._spriteManagers.reset();
  24683. this._edgesRenderers.reset();
  24684. };
  24685. RenderingGroup.prototype.dispose = function () {
  24686. this._opaqueSubMeshes.dispose();
  24687. this._transparentSubMeshes.dispose();
  24688. this._alphaTestSubMeshes.dispose();
  24689. this._depthOnlySubMeshes.dispose();
  24690. this._particleSystems.dispose();
  24691. this._spriteManagers.dispose();
  24692. this._edgesRenderers.dispose();
  24693. };
  24694. /**
  24695. * Inserts the submesh in its correct queue depending on its material.
  24696. * @param subMesh The submesh to dispatch
  24697. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  24698. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  24699. */
  24700. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  24701. // Get mesh and materials if not provided
  24702. if (mesh === undefined) {
  24703. mesh = subMesh.getMesh();
  24704. }
  24705. if (material === undefined) {
  24706. material = subMesh.getMaterial();
  24707. }
  24708. if (material === null || material === undefined) {
  24709. return;
  24710. }
  24711. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  24712. this._transparentSubMeshes.push(subMesh);
  24713. }
  24714. else if (material.needAlphaTesting()) { // Alpha test
  24715. if (material.needDepthPrePass) {
  24716. this._depthOnlySubMeshes.push(subMesh);
  24717. }
  24718. this._alphaTestSubMeshes.push(subMesh);
  24719. }
  24720. else {
  24721. if (material.needDepthPrePass) {
  24722. this._depthOnlySubMeshes.push(subMesh);
  24723. }
  24724. this._opaqueSubMeshes.push(subMesh); // Opaque
  24725. }
  24726. if (mesh._edgesRenderer && mesh._edgesRenderer.isEnabled) {
  24727. this._edgesRenderers.push(mesh._edgesRenderer);
  24728. }
  24729. };
  24730. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  24731. this._spriteManagers.push(spriteManager);
  24732. };
  24733. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  24734. this._particleSystems.push(particleSystem);
  24735. };
  24736. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  24737. if (this._particleSystems.length === 0) {
  24738. return;
  24739. }
  24740. // Particles
  24741. var activeCamera = this._scene.activeCamera;
  24742. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  24743. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  24744. var particleSystem = this._particleSystems.data[particleIndex];
  24745. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  24746. continue;
  24747. }
  24748. var emitter = particleSystem.emitter;
  24749. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  24750. this._scene._activeParticles.addCount(particleSystem.render(), false);
  24751. }
  24752. }
  24753. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  24754. };
  24755. RenderingGroup.prototype._renderSprites = function () {
  24756. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  24757. return;
  24758. }
  24759. // Sprites
  24760. var activeCamera = this._scene.activeCamera;
  24761. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  24762. for (var id = 0; id < this._spriteManagers.length; id++) {
  24763. var spriteManager = this._spriteManagers.data[id];
  24764. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  24765. spriteManager.render();
  24766. }
  24767. }
  24768. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  24769. };
  24770. return RenderingGroup;
  24771. }());
  24772. BABYLON.RenderingGroup = RenderingGroup;
  24773. })(BABYLON || (BABYLON = {}));
  24774. //# sourceMappingURL=babylon.renderingGroup.js.map
  24775. var BABYLON;
  24776. (function (BABYLON) {
  24777. /**
  24778. * Groups all the scene component constants in one place to ease maintenance.
  24779. * @hidden
  24780. */
  24781. var SceneComponentConstants = /** @class */ (function () {
  24782. function SceneComponentConstants() {
  24783. }
  24784. SceneComponentConstants.NAME_EFFECTLAYER = "EffectLayer";
  24785. SceneComponentConstants.NAME_LAYER = "Layer";
  24786. SceneComponentConstants.NAME_LENSFLARESYSTEM = "LensFlareSystem";
  24787. SceneComponentConstants.NAME_BOUNDINGBOXRENDERER = "BoundingBoxRenderer";
  24788. SceneComponentConstants.NAME_PARTICLESYSTEM = "ParticleSystem";
  24789. SceneComponentConstants.NAME_GAMEPAD = "Gamepad";
  24790. SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE = "SimplificationQueue";
  24791. SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER = "GeometryBufferRenderer";
  24792. SceneComponentConstants.NAME_DEPTHRENDERER = "DepthRenderer";
  24793. SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER = "PostProcessRenderPipelineManager";
  24794. SceneComponentConstants.NAME_SPRITE = "Sprite";
  24795. SceneComponentConstants.NAME_OUTLINERENDERER = "Outline";
  24796. SceneComponentConstants.NAME_PROCEDURALTEXTURE = "ProceduralTexture";
  24797. SceneComponentConstants.NAME_SHADOWGENERATOR = "ShadowGenerator";
  24798. SceneComponentConstants.NAME_OCTREE = "Octree";
  24799. SceneComponentConstants.NAME_PHYSICSENGINE = "PhysicsEngine";
  24800. SceneComponentConstants.NAME_AUDIO = "Audio";
  24801. SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER = 0;
  24802. SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24803. SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER = 0;
  24804. SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER = 0;
  24805. SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER = 1;
  24806. SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER = 0;
  24807. SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER = 1;
  24808. SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE = 0;
  24809. SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE = 0;
  24810. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW = 0;
  24811. SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER = 1;
  24812. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE = 0;
  24813. SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD = 1;
  24814. SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE = 0;
  24815. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER = 0;
  24816. SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM = 1;
  24817. SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW = 2;
  24818. SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER = 3;
  24819. SceneComponentConstants.STEP_AFTERRENDER_AUDIO = 0;
  24820. SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR = 0;
  24821. SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER = 1;
  24822. SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER = 2;
  24823. SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER = 3;
  24824. SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER = 0;
  24825. SceneComponentConstants.STEP_POINTERMOVE_SPRITE = 0;
  24826. SceneComponentConstants.STEP_POINTERDOWN_SPRITE = 0;
  24827. SceneComponentConstants.STEP_POINTERUP_SPRITE = 0;
  24828. return SceneComponentConstants;
  24829. }());
  24830. BABYLON.SceneComponentConstants = SceneComponentConstants;
  24831. /**
  24832. * Repressentation of a stage in the scene (Basically a list of ordered steps)
  24833. * @hidden
  24834. */
  24835. var Stage = /** @class */ (function (_super) {
  24836. __extends(Stage, _super);
  24837. /**
  24838. * Hide ctor from the rest of the world.
  24839. * @param items The items to add.
  24840. */
  24841. function Stage(items) {
  24842. return _super.apply(this, items) || this;
  24843. }
  24844. /**
  24845. * Creates a new Stage.
  24846. * @returns A new instance of a Stage
  24847. */
  24848. Stage.Create = function () {
  24849. return Object.create(Stage.prototype);
  24850. };
  24851. /**
  24852. * Registers a step in an ordered way in the targeted stage.
  24853. * @param index Defines the position to register the step in
  24854. * @param component Defines the component attached to the step
  24855. * @param action Defines the action to launch during the step
  24856. */
  24857. Stage.prototype.registerStep = function (index, component, action) {
  24858. var i = 0;
  24859. var maxIndex = Number.MAX_VALUE;
  24860. for (; i < this.length; i++) {
  24861. var step = this[i];
  24862. maxIndex = step.index;
  24863. if (index < maxIndex) {
  24864. break;
  24865. }
  24866. }
  24867. this.splice(i, 0, { index: index, component: component, action: action.bind(component) });
  24868. };
  24869. /**
  24870. * Clears all the steps from the stage.
  24871. */
  24872. Stage.prototype.clear = function () {
  24873. this.length = 0;
  24874. };
  24875. return Stage;
  24876. }(Array));
  24877. BABYLON.Stage = Stage;
  24878. })(BABYLON || (BABYLON = {}));
  24879. //# sourceMappingURL=babylon.sceneComponent.js.map
  24880. var BABYLON;
  24881. (function (BABYLON) {
  24882. /**
  24883. * Base class of the scene acting as a container for the different elements composing a scene.
  24884. * This class is dynamically extended by the different components of the scene increasing
  24885. * flexibility and reducing coupling
  24886. */
  24887. var AbstractScene = /** @class */ (function () {
  24888. function AbstractScene() {
  24889. /**
  24890. * Gets the list of root nodes (ie. nodes with no parent)
  24891. */
  24892. this.rootNodes = new Array();
  24893. /** All of the cameras added to this scene
  24894. * @see http://doc.babylonjs.com/babylon101/cameras
  24895. */
  24896. this.cameras = new Array();
  24897. /**
  24898. * All of the lights added to this scene
  24899. * @see http://doc.babylonjs.com/babylon101/lights
  24900. */
  24901. this.lights = new Array();
  24902. /**
  24903. * All of the (abstract) meshes added to this scene
  24904. */
  24905. this.meshes = new Array();
  24906. /**
  24907. * The list of skeletons added to the scene
  24908. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24909. */
  24910. this.skeletons = new Array();
  24911. /**
  24912. * All of the particle systems added to this scene
  24913. * @see http://doc.babylonjs.com/babylon101/particles
  24914. */
  24915. this.particleSystems = new Array();
  24916. /**
  24917. * Gets a list of Animations associated with the scene
  24918. */
  24919. this.animations = [];
  24920. /**
  24921. * All of the animation groups added to this scene
  24922. * @see http://doc.babylonjs.com/how_to/group
  24923. */
  24924. this.animationGroups = new Array();
  24925. /**
  24926. * All of the multi-materials added to this scene
  24927. * @see http://doc.babylonjs.com/how_to/multi_materials
  24928. */
  24929. this.multiMaterials = new Array();
  24930. /**
  24931. * All of the materials added to this scene
  24932. * @see http://doc.babylonjs.com/babylon101/materials
  24933. */
  24934. this.materials = new Array();
  24935. /**
  24936. * The list of morph target managers added to the scene
  24937. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24938. */
  24939. this.morphTargetManagers = new Array();
  24940. /**
  24941. * The list of geometries used in the scene.
  24942. */
  24943. this.geometries = new Array();
  24944. /**
  24945. * All of the tranform nodes added to this scene
  24946. * @see http://doc.babylonjs.com/how_to/transformnode
  24947. */
  24948. this.transformNodes = new Array();
  24949. /**
  24950. * ActionManagers available on the scene.
  24951. */
  24952. this.actionManagers = new Array();
  24953. /**
  24954. * Textures to keep.
  24955. */
  24956. this.textures = new Array();
  24957. }
  24958. /**
  24959. * Adds a parser in the list of available ones
  24960. * @param name Defines the name of the parser
  24961. * @param parser Defines the parser to add
  24962. */
  24963. AbstractScene.AddParser = function (name, parser) {
  24964. this._BabylonFileParsers[name] = parser;
  24965. };
  24966. /**
  24967. * Gets a general parser from the list of avaialble ones
  24968. * @param name Defines the name of the parser
  24969. * @returns the requested parser or null
  24970. */
  24971. AbstractScene.GetParser = function (name) {
  24972. if (this._BabylonFileParsers[name]) {
  24973. return this._BabylonFileParsers[name];
  24974. }
  24975. return null;
  24976. };
  24977. /**
  24978. * Adds n individual parser in the list of available ones
  24979. * @param name Defines the name of the parser
  24980. * @param parser Defines the parser to add
  24981. */
  24982. AbstractScene.AddIndividualParser = function (name, parser) {
  24983. this._IndividualBabylonFileParsers[name] = parser;
  24984. };
  24985. /**
  24986. * Gets an individual parser from the list of avaialble ones
  24987. * @param name Defines the name of the parser
  24988. * @returns the requested parser or null
  24989. */
  24990. AbstractScene.GetIndividualParser = function (name) {
  24991. if (this._IndividualBabylonFileParsers[name]) {
  24992. return this._IndividualBabylonFileParsers[name];
  24993. }
  24994. return null;
  24995. };
  24996. /**
  24997. * Parser json data and populate both a scene and its associated container object
  24998. * @param jsonData Defines the data to parse
  24999. * @param scene Defines the scene to parse the data for
  25000. * @param container Defines the container attached to the parsing sequence
  25001. * @param rootUrl Defines the root url of the data
  25002. */
  25003. AbstractScene.Parse = function (jsonData, scene, container, rootUrl) {
  25004. for (var parserName in this._BabylonFileParsers) {
  25005. if (this._BabylonFileParsers.hasOwnProperty(parserName)) {
  25006. this._BabylonFileParsers[parserName](jsonData, scene, container, rootUrl);
  25007. }
  25008. }
  25009. };
  25010. /**
  25011. * Stores the list of available parsers in the application.
  25012. */
  25013. AbstractScene._BabylonFileParsers = {};
  25014. /**
  25015. * Stores the list of available individual parsers in the application.
  25016. */
  25017. AbstractScene._IndividualBabylonFileParsers = {};
  25018. return AbstractScene;
  25019. }());
  25020. BABYLON.AbstractScene = AbstractScene;
  25021. })(BABYLON || (BABYLON = {}));
  25022. //# sourceMappingURL=babylon.abstractScene.js.map
  25023. var BABYLON;
  25024. (function (BABYLON) {
  25025. /** @hidden */
  25026. var ClickInfo = /** @class */ (function () {
  25027. function ClickInfo() {
  25028. this._singleClick = false;
  25029. this._doubleClick = false;
  25030. this._hasSwiped = false;
  25031. this._ignore = false;
  25032. }
  25033. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  25034. get: function () {
  25035. return this._singleClick;
  25036. },
  25037. set: function (b) {
  25038. this._singleClick = b;
  25039. },
  25040. enumerable: true,
  25041. configurable: true
  25042. });
  25043. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  25044. get: function () {
  25045. return this._doubleClick;
  25046. },
  25047. set: function (b) {
  25048. this._doubleClick = b;
  25049. },
  25050. enumerable: true,
  25051. configurable: true
  25052. });
  25053. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  25054. get: function () {
  25055. return this._hasSwiped;
  25056. },
  25057. set: function (b) {
  25058. this._hasSwiped = b;
  25059. },
  25060. enumerable: true,
  25061. configurable: true
  25062. });
  25063. Object.defineProperty(ClickInfo.prototype, "ignore", {
  25064. get: function () {
  25065. return this._ignore;
  25066. },
  25067. set: function (b) {
  25068. this._ignore = b;
  25069. },
  25070. enumerable: true,
  25071. configurable: true
  25072. });
  25073. return ClickInfo;
  25074. }());
  25075. /**
  25076. * This class is used by the onRenderingGroupObservable
  25077. */
  25078. var RenderingGroupInfo = /** @class */ (function () {
  25079. function RenderingGroupInfo() {
  25080. }
  25081. return RenderingGroupInfo;
  25082. }());
  25083. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  25084. /**
  25085. * Represents a scene to be rendered by the engine.
  25086. * @see http://doc.babylonjs.com/features/scene
  25087. */
  25088. var Scene = /** @class */ (function (_super) {
  25089. __extends(Scene, _super);
  25090. /**
  25091. * Creates a new Scene
  25092. * @param engine defines the engine to use to render this scene
  25093. */
  25094. function Scene(engine) {
  25095. var _this = _super.call(this) || this;
  25096. // Members
  25097. /**
  25098. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  25099. */
  25100. _this.autoClear = true;
  25101. /**
  25102. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  25103. */
  25104. _this.autoClearDepthAndStencil = true;
  25105. /**
  25106. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  25107. */
  25108. _this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  25109. /**
  25110. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  25111. */
  25112. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  25113. _this._forceWireframe = false;
  25114. _this._forcePointsCloud = false;
  25115. /**
  25116. * Gets or sets a boolean indicating if animations are enabled
  25117. */
  25118. _this.animationsEnabled = true;
  25119. _this._animationPropertiesOverride = null;
  25120. /**
  25121. * Gets or sets a boolean indicating if a constant deltatime has to be used
  25122. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  25123. */
  25124. _this.useConstantAnimationDeltaTime = false;
  25125. /**
  25126. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  25127. * Please note that it requires to run a ray cast through the scene on every frame
  25128. */
  25129. _this.constantlyUpdateMeshUnderPointer = false;
  25130. /**
  25131. * Defines the HTML cursor to use when hovering over interactive elements
  25132. */
  25133. _this.hoverCursor = "pointer";
  25134. /**
  25135. * Defines the HTML default cursor to use (empty by default)
  25136. */
  25137. _this.defaultCursor = "";
  25138. /**
  25139. * This is used to call preventDefault() on pointer down
  25140. * in order to block unwanted artifacts like system double clicks
  25141. */
  25142. _this.preventDefaultOnPointerDown = true;
  25143. // Metadata
  25144. /**
  25145. * Gets or sets user defined metadata
  25146. */
  25147. _this.metadata = null;
  25148. /**
  25149. * Use this array to add regular expressions used to disable offline support for specific urls
  25150. */
  25151. _this.disableOfflineSupportExceptionRules = new Array();
  25152. /**
  25153. * An event triggered when the scene is disposed.
  25154. */
  25155. _this.onDisposeObservable = new BABYLON.Observable();
  25156. _this._onDisposeObserver = null;
  25157. /**
  25158. * An event triggered before rendering the scene (right after animations and physics)
  25159. */
  25160. _this.onBeforeRenderObservable = new BABYLON.Observable();
  25161. _this._onBeforeRenderObserver = null;
  25162. /**
  25163. * An event triggered after rendering the scene
  25164. */
  25165. _this.onAfterRenderObservable = new BABYLON.Observable();
  25166. _this._onAfterRenderObserver = null;
  25167. /**
  25168. * An event triggered before animating the scene
  25169. */
  25170. _this.onBeforeAnimationsObservable = new BABYLON.Observable();
  25171. /**
  25172. * An event triggered after animations processing
  25173. */
  25174. _this.onAfterAnimationsObservable = new BABYLON.Observable();
  25175. /**
  25176. * An event triggered before draw calls are ready to be sent
  25177. */
  25178. _this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  25179. /**
  25180. * An event triggered after draw calls have been sent
  25181. */
  25182. _this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  25183. /**
  25184. * An event triggered when the scene is ready
  25185. */
  25186. _this.onReadyObservable = new BABYLON.Observable();
  25187. /**
  25188. * An event triggered before rendering a camera
  25189. */
  25190. _this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  25191. _this._onBeforeCameraRenderObserver = null;
  25192. /**
  25193. * An event triggered after rendering a camera
  25194. */
  25195. _this.onAfterCameraRenderObservable = new BABYLON.Observable();
  25196. _this._onAfterCameraRenderObserver = null;
  25197. /**
  25198. * An event triggered when active meshes evaluation is about to start
  25199. */
  25200. _this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25201. /**
  25202. * An event triggered when active meshes evaluation is done
  25203. */
  25204. _this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  25205. /**
  25206. * An event triggered when particles rendering is about to start
  25207. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25208. */
  25209. _this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  25210. /**
  25211. * An event triggered when particles rendering is done
  25212. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  25213. */
  25214. _this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  25215. /**
  25216. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  25217. */
  25218. _this.onDataLoadedObservable = new BABYLON.Observable();
  25219. /**
  25220. * An event triggered when a camera is created
  25221. */
  25222. _this.onNewCameraAddedObservable = new BABYLON.Observable();
  25223. /**
  25224. * An event triggered when a camera is removed
  25225. */
  25226. _this.onCameraRemovedObservable = new BABYLON.Observable();
  25227. /**
  25228. * An event triggered when a light is created
  25229. */
  25230. _this.onNewLightAddedObservable = new BABYLON.Observable();
  25231. /**
  25232. * An event triggered when a light is removed
  25233. */
  25234. _this.onLightRemovedObservable = new BABYLON.Observable();
  25235. /**
  25236. * An event triggered when a geometry is created
  25237. */
  25238. _this.onNewGeometryAddedObservable = new BABYLON.Observable();
  25239. /**
  25240. * An event triggered when a geometry is removed
  25241. */
  25242. _this.onGeometryRemovedObservable = new BABYLON.Observable();
  25243. /**
  25244. * An event triggered when a transform node is created
  25245. */
  25246. _this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  25247. /**
  25248. * An event triggered when a transform node is removed
  25249. */
  25250. _this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  25251. /**
  25252. * An event triggered when a mesh is created
  25253. */
  25254. _this.onNewMeshAddedObservable = new BABYLON.Observable();
  25255. /**
  25256. * An event triggered when a mesh is removed
  25257. */
  25258. _this.onMeshRemovedObservable = new BABYLON.Observable();
  25259. /**
  25260. * An event triggered when a material is created
  25261. */
  25262. _this.onNewMaterialAddedObservable = new BABYLON.Observable();
  25263. /**
  25264. * An event triggered when a material is removed
  25265. */
  25266. _this.onMaterialRemovedObservable = new BABYLON.Observable();
  25267. /**
  25268. * An event triggered when a texture is created
  25269. */
  25270. _this.onNewTextureAddedObservable = new BABYLON.Observable();
  25271. /**
  25272. * An event triggered when a texture is removed
  25273. */
  25274. _this.onTextureRemovedObservable = new BABYLON.Observable();
  25275. /**
  25276. * An event triggered when render targets are about to be rendered
  25277. * Can happen multiple times per frame.
  25278. */
  25279. _this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  25280. /**
  25281. * An event triggered when render targets were rendered.
  25282. * Can happen multiple times per frame.
  25283. */
  25284. _this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  25285. /**
  25286. * An event triggered before calculating deterministic simulation step
  25287. */
  25288. _this.onBeforeStepObservable = new BABYLON.Observable();
  25289. /**
  25290. * An event triggered after calculating deterministic simulation step
  25291. */
  25292. _this.onAfterStepObservable = new BABYLON.Observable();
  25293. /**
  25294. * This Observable will be triggered before rendering each renderingGroup of each rendered camera.
  25295. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25296. * 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)
  25297. */
  25298. _this.onBeforeRenderingGroupObservable = new BABYLON.Observable();
  25299. /**
  25300. * This Observable will be triggered after rendering each renderingGroup of each rendered camera.
  25301. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  25302. * 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)
  25303. */
  25304. _this.onAfterRenderingGroupObservable = new BABYLON.Observable();
  25305. /**
  25306. * This Observable will when a mesh has been imported into the scene.
  25307. */
  25308. _this.onMeshImportedObservable = new BABYLON.Observable();
  25309. // Animations
  25310. _this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  25311. /**
  25312. * 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).
  25313. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  25314. */
  25315. _this.onPrePointerObservable = new BABYLON.Observable();
  25316. /**
  25317. * Observable event triggered each time an input event is received from the rendering canvas
  25318. */
  25319. _this.onPointerObservable = new BABYLON.Observable();
  25320. _this._meshPickProceed = false;
  25321. _this._currentPickResult = null;
  25322. _this._previousPickResult = null;
  25323. _this._totalPointersPressed = 0;
  25324. _this._doubleClickOccured = false;
  25325. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  25326. _this.cameraToUseForPointers = null;
  25327. _this._pointerX = 0;
  25328. _this._pointerY = 0;
  25329. _this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  25330. _this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  25331. _this._startingPointerTime = 0;
  25332. _this._previousStartingPointerTime = 0;
  25333. _this._pointerCaptures = {};
  25334. // Deterministic lockstep
  25335. _this._timeAccumulator = 0;
  25336. _this._currentStepId = 0;
  25337. _this._currentInternalStep = 0;
  25338. // Keyboard
  25339. /**
  25340. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  25341. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  25342. */
  25343. _this.onPreKeyboardObservable = new BABYLON.Observable();
  25344. /**
  25345. * Observable event triggered each time an keyboard event is received from the hosting window
  25346. */
  25347. _this.onKeyboardObservable = new BABYLON.Observable();
  25348. // Coordinates system
  25349. _this._useRightHandedSystem = false;
  25350. // Fog
  25351. _this._fogEnabled = true;
  25352. _this._fogMode = Scene.FOGMODE_NONE;
  25353. /**
  25354. * Gets or sets the fog color to use
  25355. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25356. * (Default is Color3(0.2, 0.2, 0.3))
  25357. */
  25358. _this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  25359. /**
  25360. * Gets or sets the fog density to use
  25361. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25362. * (Default is 0.1)
  25363. */
  25364. _this.fogDensity = 0.1;
  25365. /**
  25366. * Gets or sets the fog start distance to use
  25367. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25368. * (Default is 0)
  25369. */
  25370. _this.fogStart = 0;
  25371. /**
  25372. * Gets or sets the fog end distance to use
  25373. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25374. * (Default is 1000)
  25375. */
  25376. _this.fogEnd = 1000.0;
  25377. // Lights
  25378. _this._shadowsEnabled = true;
  25379. _this._lightsEnabled = true;
  25380. /** All of the active cameras added to this scene. */
  25381. _this.activeCameras = new Array();
  25382. // Textures
  25383. _this._texturesEnabled = true;
  25384. // Particles
  25385. /**
  25386. * Gets or sets a boolean indicating if particles are enabled on this scene
  25387. */
  25388. _this.particlesEnabled = true;
  25389. // Sprites
  25390. /**
  25391. * Gets or sets a boolean indicating if sprites are enabled on this scene
  25392. */
  25393. _this.spritesEnabled = true;
  25394. // Skeletons
  25395. _this._skeletonsEnabled = true;
  25396. // Lens flares
  25397. /**
  25398. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  25399. */
  25400. _this.lensFlaresEnabled = true;
  25401. // Collisions
  25402. /**
  25403. * Gets or sets a boolean indicating if collisions are enabled on this scene
  25404. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25405. */
  25406. _this.collisionsEnabled = true;
  25407. /**
  25408. * Defines the gravity applied to this scene (used only for collisions)
  25409. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  25410. */
  25411. _this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  25412. // Postprocesses
  25413. /**
  25414. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  25415. */
  25416. _this.postProcessesEnabled = true;
  25417. /**
  25418. * The list of postprocesses added to the scene
  25419. */
  25420. _this.postProcesses = new Array();
  25421. // Customs render targets
  25422. /**
  25423. * Gets or sets a boolean indicating if render targets are enabled on this scene
  25424. */
  25425. _this.renderTargetsEnabled = true;
  25426. /**
  25427. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  25428. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  25429. */
  25430. _this.dumpNextRenderTargets = false;
  25431. /**
  25432. * The list of user defined render targets added to the scene
  25433. */
  25434. _this.customRenderTargets = new Array();
  25435. /**
  25436. * Gets the list of meshes imported to the scene through SceneLoader
  25437. */
  25438. _this.importedMeshesFiles = new Array();
  25439. // Probes
  25440. /**
  25441. * Gets or sets a boolean indicating if probes are enabled on this scene
  25442. */
  25443. _this.probesEnabled = true;
  25444. _this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  25445. // Procedural textures
  25446. /**
  25447. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  25448. */
  25449. _this.proceduralTexturesEnabled = true;
  25450. // Performance counters
  25451. _this._totalVertices = new BABYLON.PerfCounter();
  25452. /** @hidden */
  25453. _this._activeIndices = new BABYLON.PerfCounter();
  25454. /** @hidden */
  25455. _this._activeParticles = new BABYLON.PerfCounter();
  25456. /** @hidden */
  25457. _this._activeBones = new BABYLON.PerfCounter();
  25458. _this._animationTime = 0;
  25459. /**
  25460. * Gets or sets a general scale for animation speed
  25461. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  25462. */
  25463. _this.animationTimeScale = 1;
  25464. _this._renderId = 0;
  25465. _this._frameId = 0;
  25466. _this._executeWhenReadyTimeoutId = -1;
  25467. _this._intermediateRendering = false;
  25468. _this._viewUpdateFlag = -1;
  25469. _this._projectionUpdateFlag = -1;
  25470. _this._alternateViewUpdateFlag = -1;
  25471. _this._alternateProjectionUpdateFlag = -1;
  25472. /** @hidden */
  25473. _this._toBeDisposed = new Array(256);
  25474. _this._activeRequests = new Array();
  25475. _this._pendingData = new Array();
  25476. _this._isDisposed = false;
  25477. /**
  25478. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  25479. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  25480. */
  25481. _this.dispatchAllSubMeshesOfActiveMeshes = false;
  25482. _this._activeMeshes = new BABYLON.SmartArray(256);
  25483. _this._processedMaterials = new BABYLON.SmartArray(256);
  25484. _this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  25485. /** @hidden */
  25486. _this._activeParticleSystems = new BABYLON.SmartArray(256);
  25487. _this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  25488. _this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  25489. /** @hidden */
  25490. _this._activeAnimatables = new Array();
  25491. _this._transformMatrix = BABYLON.Matrix.Zero();
  25492. _this._useAlternateCameraConfiguration = false;
  25493. _this._alternateRendering = false;
  25494. /**
  25495. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  25496. * This is useful if there are more lights that the maximum simulteanous authorized
  25497. */
  25498. _this.requireLightSorting = false;
  25499. /**
  25500. * @hidden
  25501. * Backing store of defined scene components.
  25502. */
  25503. _this._components = [];
  25504. /**
  25505. * @hidden
  25506. * Backing store of defined scene components.
  25507. */
  25508. _this._serializableComponents = [];
  25509. /**
  25510. * List of components to register on the next registration step.
  25511. */
  25512. _this._transientComponents = [];
  25513. /**
  25514. * @hidden
  25515. * Defines the actions happening before camera updates.
  25516. */
  25517. _this._beforeCameraUpdateStage = BABYLON.Stage.Create();
  25518. /**
  25519. * @hidden
  25520. * Defines the actions happening before clear the canvas.
  25521. */
  25522. _this._beforeClearStage = BABYLON.Stage.Create();
  25523. /**
  25524. * @hidden
  25525. * Defines the actions when collecting render targets for the frame.
  25526. */
  25527. _this._gatherRenderTargetsStage = BABYLON.Stage.Create();
  25528. /**
  25529. * @hidden
  25530. * Defines the actions happening for one camera in the frame.
  25531. */
  25532. _this._gatherActiveCameraRenderTargetsStage = BABYLON.Stage.Create();
  25533. /**
  25534. * @hidden
  25535. * Defines the actions happening during the per mesh ready checks.
  25536. */
  25537. _this._isReadyForMeshStage = BABYLON.Stage.Create();
  25538. /**
  25539. * @hidden
  25540. * Defines the actions happening before evaluate active mesh checks.
  25541. */
  25542. _this._beforeEvaluateActiveMeshStage = BABYLON.Stage.Create();
  25543. /**
  25544. * @hidden
  25545. * Defines the actions happening during the evaluate sub mesh checks.
  25546. */
  25547. _this._evaluateSubMeshStage = BABYLON.Stage.Create();
  25548. /**
  25549. * @hidden
  25550. * Defines the actions happening during the active mesh stage.
  25551. */
  25552. _this._activeMeshStage = BABYLON.Stage.Create();
  25553. /**
  25554. * @hidden
  25555. * Defines the actions happening during the per camera render target step.
  25556. */
  25557. _this._cameraDrawRenderTargetStage = BABYLON.Stage.Create();
  25558. /**
  25559. * @hidden
  25560. * Defines the actions happening just before the active camera is drawing.
  25561. */
  25562. _this._beforeCameraDrawStage = BABYLON.Stage.Create();
  25563. /**
  25564. * @hidden
  25565. * Defines the actions happening just before a rendering group is drawing.
  25566. */
  25567. _this._beforeRenderingGroupDrawStage = BABYLON.Stage.Create();
  25568. /**
  25569. * @hidden
  25570. * Defines the actions happening just before a mesh is drawing.
  25571. */
  25572. _this._beforeRenderingMeshStage = BABYLON.Stage.Create();
  25573. /**
  25574. * @hidden
  25575. * Defines the actions happening just after a mesh has been drawn.
  25576. */
  25577. _this._afterRenderingMeshStage = BABYLON.Stage.Create();
  25578. /**
  25579. * @hidden
  25580. * Defines the actions happening just after a rendering group has been drawn.
  25581. */
  25582. _this._afterRenderingGroupDrawStage = BABYLON.Stage.Create();
  25583. /**
  25584. * @hidden
  25585. * Defines the actions happening just after the active camera has been drawn.
  25586. */
  25587. _this._afterCameraDrawStage = BABYLON.Stage.Create();
  25588. /**
  25589. * @hidden
  25590. * Defines the actions happening just after rendering all cameras and computing intersections.
  25591. */
  25592. _this._afterRenderStage = BABYLON.Stage.Create();
  25593. /**
  25594. * @hidden
  25595. * Defines the actions happening when a pointer move event happens.
  25596. */
  25597. _this._pointerMoveStage = BABYLON.Stage.Create();
  25598. /**
  25599. * @hidden
  25600. * Defines the actions happening when a pointer down event happens.
  25601. */
  25602. _this._pointerDownStage = BABYLON.Stage.Create();
  25603. /**
  25604. * @hidden
  25605. * Defines the actions happening when a pointer up event happens.
  25606. */
  25607. _this._pointerUpStage = BABYLON.Stage.Create();
  25608. _this._defaultMeshCandidates = {
  25609. data: [],
  25610. length: 0
  25611. };
  25612. _this._defaultSubMeshCandidates = {
  25613. data: [],
  25614. length: 0
  25615. };
  25616. _this._activeMeshesFrozen = false;
  25617. /** @hidden */
  25618. _this._allowPostProcessClearColor = true;
  25619. /**
  25620. * User updatable function that will return a deterministic frame time when engine is in deterministic lock step mode
  25621. */
  25622. _this.getDeterministicFrameTime = function () {
  25623. return 1000.0 / 60.0; // frame time in ms
  25624. };
  25625. _this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  25626. _this._blockMaterialDirtyMechanism = false;
  25627. _this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  25628. _this._engine.scenes.push(_this);
  25629. _this._uid = null;
  25630. _this._renderingManager = new BABYLON.RenderingManager(_this);
  25631. if (BABYLON.PostProcessManager) {
  25632. _this.postProcessManager = new BABYLON.PostProcessManager(_this);
  25633. }
  25634. if (BABYLON.Tools.IsWindowObjectExist()) {
  25635. _this.attachControl();
  25636. }
  25637. //collision coordinator initialization. For now legacy per default.
  25638. _this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  25639. // Uniform Buffer
  25640. _this._createUbo();
  25641. // Default Image processing definition
  25642. if (BABYLON.ImageProcessingConfiguration) {
  25643. _this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  25644. }
  25645. _this.setDefaultCandidateProviders();
  25646. return _this;
  25647. }
  25648. Object.defineProperty(Scene.prototype, "environmentTexture", {
  25649. /**
  25650. * Texture used in all pbr material as the reflection texture.
  25651. * As in the majority of the scene they are the same (exception for multi room and so on),
  25652. * this is easier to reference from here than from all the materials.
  25653. */
  25654. get: function () {
  25655. return this._environmentTexture;
  25656. },
  25657. /**
  25658. * Texture used in all pbr material as the reflection texture.
  25659. * As in the majority of the scene they are the same (exception for multi room and so on),
  25660. * this is easier to set here than in all the materials.
  25661. */
  25662. set: function (value) {
  25663. if (this._environmentTexture === value) {
  25664. return;
  25665. }
  25666. this._environmentTexture = value;
  25667. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25668. },
  25669. enumerable: true,
  25670. configurable: true
  25671. });
  25672. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  25673. /**
  25674. * Default image processing configuration used either in the rendering
  25675. * Forward main pass or through the imageProcessingPostProcess if present.
  25676. * As in the majority of the scene they are the same (exception for multi camera),
  25677. * this is easier to reference from here than from all the materials and post process.
  25678. *
  25679. * No setter as we it is a shared configuration, you can set the values instead.
  25680. */
  25681. get: function () {
  25682. return this._imageProcessingConfiguration;
  25683. },
  25684. enumerable: true,
  25685. configurable: true
  25686. });
  25687. Object.defineProperty(Scene.prototype, "forceWireframe", {
  25688. get: function () {
  25689. return this._forceWireframe;
  25690. },
  25691. /**
  25692. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  25693. */
  25694. set: function (value) {
  25695. if (this._forceWireframe === value) {
  25696. return;
  25697. }
  25698. this._forceWireframe = value;
  25699. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25700. },
  25701. enumerable: true,
  25702. configurable: true
  25703. });
  25704. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  25705. get: function () {
  25706. return this._forcePointsCloud;
  25707. },
  25708. /**
  25709. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  25710. */
  25711. set: function (value) {
  25712. if (this._forcePointsCloud === value) {
  25713. return;
  25714. }
  25715. this._forcePointsCloud = value;
  25716. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25717. },
  25718. enumerable: true,
  25719. configurable: true
  25720. });
  25721. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  25722. /**
  25723. * Gets or sets the animation properties override
  25724. */
  25725. get: function () {
  25726. return this._animationPropertiesOverride;
  25727. },
  25728. set: function (value) {
  25729. this._animationPropertiesOverride = value;
  25730. },
  25731. enumerable: true,
  25732. configurable: true
  25733. });
  25734. Object.defineProperty(Scene.prototype, "onDispose", {
  25735. /** Sets a function to be executed when this scene is disposed. */
  25736. set: function (callback) {
  25737. if (this._onDisposeObserver) {
  25738. this.onDisposeObservable.remove(this._onDisposeObserver);
  25739. }
  25740. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25741. },
  25742. enumerable: true,
  25743. configurable: true
  25744. });
  25745. Object.defineProperty(Scene.prototype, "beforeRender", {
  25746. /** Sets a function to be executed before rendering this scene */
  25747. set: function (callback) {
  25748. if (this._onBeforeRenderObserver) {
  25749. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  25750. }
  25751. if (callback) {
  25752. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  25753. }
  25754. },
  25755. enumerable: true,
  25756. configurable: true
  25757. });
  25758. Object.defineProperty(Scene.prototype, "afterRender", {
  25759. /** Sets a function to be executed after rendering this scene */
  25760. set: function (callback) {
  25761. if (this._onAfterRenderObserver) {
  25762. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  25763. }
  25764. if (callback) {
  25765. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  25766. }
  25767. },
  25768. enumerable: true,
  25769. configurable: true
  25770. });
  25771. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  25772. /** Sets a function to be executed before rendering a camera*/
  25773. set: function (callback) {
  25774. if (this._onBeforeCameraRenderObserver) {
  25775. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  25776. }
  25777. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  25778. },
  25779. enumerable: true,
  25780. configurable: true
  25781. });
  25782. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  25783. /** Sets a function to be executed after rendering a camera*/
  25784. set: function (callback) {
  25785. if (this._onAfterCameraRenderObserver) {
  25786. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  25787. }
  25788. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  25789. },
  25790. enumerable: true,
  25791. configurable: true
  25792. });
  25793. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  25794. /**
  25795. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  25796. */
  25797. get: function () {
  25798. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  25799. },
  25800. enumerable: true,
  25801. configurable: true
  25802. });
  25803. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  25804. get: function () {
  25805. return this._useRightHandedSystem;
  25806. },
  25807. /**
  25808. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  25809. */
  25810. set: function (value) {
  25811. if (this._useRightHandedSystem === value) {
  25812. return;
  25813. }
  25814. this._useRightHandedSystem = value;
  25815. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25816. },
  25817. enumerable: true,
  25818. configurable: true
  25819. });
  25820. /**
  25821. * Sets the step Id used by deterministic lock step
  25822. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25823. * @param newStepId defines the step Id
  25824. */
  25825. Scene.prototype.setStepId = function (newStepId) {
  25826. this._currentStepId = newStepId;
  25827. };
  25828. ;
  25829. /**
  25830. * Gets the step Id used by deterministic lock step
  25831. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25832. * @returns the step Id
  25833. */
  25834. Scene.prototype.getStepId = function () {
  25835. return this._currentStepId;
  25836. };
  25837. ;
  25838. /**
  25839. * Gets the internal step used by deterministic lock step
  25840. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  25841. * @returns the internal step
  25842. */
  25843. Scene.prototype.getInternalStep = function () {
  25844. return this._currentInternalStep;
  25845. };
  25846. ;
  25847. Object.defineProperty(Scene.prototype, "fogEnabled", {
  25848. get: function () {
  25849. return this._fogEnabled;
  25850. },
  25851. /**
  25852. * Gets or sets a boolean indicating if fog is enabled on this scene
  25853. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25854. * (Default is true)
  25855. */
  25856. set: function (value) {
  25857. if (this._fogEnabled === value) {
  25858. return;
  25859. }
  25860. this._fogEnabled = value;
  25861. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25862. },
  25863. enumerable: true,
  25864. configurable: true
  25865. });
  25866. Object.defineProperty(Scene.prototype, "fogMode", {
  25867. get: function () {
  25868. return this._fogMode;
  25869. },
  25870. /**
  25871. * Gets or sets the fog mode to use
  25872. * @see http://doc.babylonjs.com/babylon101/environment#fog
  25873. * | mode | value |
  25874. * | --- | --- |
  25875. * | FOGMODE_NONE | 0 |
  25876. * | FOGMODE_EXP | 1 |
  25877. * | FOGMODE_EXP2 | 2 |
  25878. * | FOGMODE_LINEAR | 3 |
  25879. */
  25880. set: function (value) {
  25881. if (this._fogMode === value) {
  25882. return;
  25883. }
  25884. this._fogMode = value;
  25885. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  25886. },
  25887. enumerable: true,
  25888. configurable: true
  25889. });
  25890. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  25891. get: function () {
  25892. return this._shadowsEnabled;
  25893. },
  25894. /**
  25895. * Gets or sets a boolean indicating if shadows are enabled on this scene
  25896. */
  25897. set: function (value) {
  25898. if (this._shadowsEnabled === value) {
  25899. return;
  25900. }
  25901. this._shadowsEnabled = value;
  25902. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25903. },
  25904. enumerable: true,
  25905. configurable: true
  25906. });
  25907. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  25908. get: function () {
  25909. return this._lightsEnabled;
  25910. },
  25911. /**
  25912. * Gets or sets a boolean indicating if lights are enabled on this scene
  25913. */
  25914. set: function (value) {
  25915. if (this._lightsEnabled === value) {
  25916. return;
  25917. }
  25918. this._lightsEnabled = value;
  25919. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  25920. },
  25921. enumerable: true,
  25922. configurable: true
  25923. });
  25924. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  25925. /** The default material used on meshes when no material is affected */
  25926. get: function () {
  25927. if (!this._defaultMaterial) {
  25928. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  25929. }
  25930. return this._defaultMaterial;
  25931. },
  25932. /** The default material used on meshes when no material is affected */
  25933. set: function (value) {
  25934. this._defaultMaterial = value;
  25935. },
  25936. enumerable: true,
  25937. configurable: true
  25938. });
  25939. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  25940. get: function () {
  25941. return this._texturesEnabled;
  25942. },
  25943. /**
  25944. * Gets or sets a boolean indicating if textures are enabled on this scene
  25945. */
  25946. set: function (value) {
  25947. if (this._texturesEnabled === value) {
  25948. return;
  25949. }
  25950. this._texturesEnabled = value;
  25951. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  25952. },
  25953. enumerable: true,
  25954. configurable: true
  25955. });
  25956. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  25957. get: function () {
  25958. return this._skeletonsEnabled;
  25959. },
  25960. /**
  25961. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  25962. */
  25963. set: function (value) {
  25964. if (this._skeletonsEnabled === value) {
  25965. return;
  25966. }
  25967. this._skeletonsEnabled = value;
  25968. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  25969. },
  25970. enumerable: true,
  25971. configurable: true
  25972. });
  25973. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  25974. /** @hidden */
  25975. get: function () {
  25976. return this._alternateRendering;
  25977. },
  25978. enumerable: true,
  25979. configurable: true
  25980. });
  25981. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  25982. /**
  25983. * Gets the list of frustum planes (built from the active camera)
  25984. */
  25985. get: function () {
  25986. return this._frustumPlanes;
  25987. },
  25988. enumerable: true,
  25989. configurable: true
  25990. });
  25991. /**
  25992. * Registers the transient components if needed.
  25993. */
  25994. Scene.prototype._registerTransientComponents = function () {
  25995. // Register components that have been associated lately to the scene.
  25996. if (this._transientComponents.length > 0) {
  25997. for (var _i = 0, _a = this._transientComponents; _i < _a.length; _i++) {
  25998. var component = _a[_i];
  25999. component.register();
  26000. }
  26001. this._transientComponents = [];
  26002. }
  26003. };
  26004. /**
  26005. * @hidden
  26006. * Add a component to the scene.
  26007. * Note that the ccomponent could be registered on th next frame if this is called after
  26008. * the register component stage.
  26009. * @param component Defines the component to add to the scene
  26010. */
  26011. Scene.prototype._addComponent = function (component) {
  26012. this._components.push(component);
  26013. this._transientComponents.push(component);
  26014. var serializableComponent = component;
  26015. if (serializableComponent.addFromContainer) {
  26016. this._serializableComponents.push(serializableComponent);
  26017. }
  26018. };
  26019. /**
  26020. * @hidden
  26021. * Gets a component from the scene.
  26022. * @param name defines the name of the component to retrieve
  26023. * @returns the component or null if not present
  26024. */
  26025. Scene.prototype._getComponent = function (name) {
  26026. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  26027. var component = _a[_i];
  26028. if (component.name === name) {
  26029. return component;
  26030. }
  26031. }
  26032. return null;
  26033. };
  26034. /**
  26035. * @hidden
  26036. */
  26037. Scene.prototype._getDefaultMeshCandidates = function () {
  26038. this._defaultMeshCandidates.data = this.meshes;
  26039. this._defaultMeshCandidates.length = this.meshes.length;
  26040. return this._defaultMeshCandidates;
  26041. };
  26042. /**
  26043. * @hidden
  26044. */
  26045. Scene.prototype._getDefaultSubMeshCandidates = function (mesh) {
  26046. this._defaultSubMeshCandidates.data = mesh.subMeshes;
  26047. this._defaultSubMeshCandidates.length = mesh.subMeshes.length;
  26048. return this._defaultSubMeshCandidates;
  26049. };
  26050. /**
  26051. * Sets the default candidate providers for the scene.
  26052. * This sets the getActiveMeshCandidates, getActiveSubMeshCandidates, getIntersectingSubMeshCandidates
  26053. * and getCollidingSubMeshCandidates to their default function
  26054. */
  26055. Scene.prototype.setDefaultCandidateProviders = function () {
  26056. this.getActiveMeshCandidates = this._getDefaultMeshCandidates.bind(this);
  26057. this.getActiveSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26058. this.getIntersectingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26059. this.getCollidingSubMeshCandidates = this._getDefaultSubMeshCandidates.bind(this);
  26060. };
  26061. Object.defineProperty(Scene.prototype, "workerCollisions", {
  26062. /**
  26063. * Gets a boolean indicating if collisions are processed on a web worker
  26064. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  26065. */
  26066. get: function () {
  26067. return this._workerCollisions;
  26068. },
  26069. set: function (enabled) {
  26070. if (!BABYLON.CollisionCoordinatorLegacy) {
  26071. return;
  26072. }
  26073. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  26074. this._workerCollisions = enabled;
  26075. if (this.collisionCoordinator) {
  26076. this.collisionCoordinator.destroy();
  26077. }
  26078. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  26079. this.collisionCoordinator.init(this);
  26080. },
  26081. enumerable: true,
  26082. configurable: true
  26083. });
  26084. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  26085. /**
  26086. * Gets the mesh that is currently under the pointer
  26087. */
  26088. get: function () {
  26089. return this._pointerOverMesh;
  26090. },
  26091. enumerable: true,
  26092. configurable: true
  26093. });
  26094. Object.defineProperty(Scene.prototype, "pointerX", {
  26095. /**
  26096. * Gets the current on-screen X position of the pointer
  26097. */
  26098. get: function () {
  26099. return this._pointerX;
  26100. },
  26101. enumerable: true,
  26102. configurable: true
  26103. });
  26104. Object.defineProperty(Scene.prototype, "pointerY", {
  26105. /**
  26106. * Gets the current on-screen Y position of the pointer
  26107. */
  26108. get: function () {
  26109. return this._pointerY;
  26110. },
  26111. enumerable: true,
  26112. configurable: true
  26113. });
  26114. /**
  26115. * Gets the cached material (ie. the latest rendered one)
  26116. * @returns the cached material
  26117. */
  26118. Scene.prototype.getCachedMaterial = function () {
  26119. return this._cachedMaterial;
  26120. };
  26121. /**
  26122. * Gets the cached effect (ie. the latest rendered one)
  26123. * @returns the cached effect
  26124. */
  26125. Scene.prototype.getCachedEffect = function () {
  26126. return this._cachedEffect;
  26127. };
  26128. /**
  26129. * Gets the cached visibility state (ie. the latest rendered one)
  26130. * @returns the cached visibility state
  26131. */
  26132. Scene.prototype.getCachedVisibility = function () {
  26133. return this._cachedVisibility;
  26134. };
  26135. /**
  26136. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  26137. * @param material defines the current material
  26138. * @param effect defines the current effect
  26139. * @param visibility defines the current visibility state
  26140. * @returns true if one parameter is not cached
  26141. */
  26142. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  26143. if (visibility === void 0) { visibility = 1; }
  26144. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  26145. };
  26146. /**
  26147. * Gets the engine associated with the scene
  26148. * @returns an Engine
  26149. */
  26150. Scene.prototype.getEngine = function () {
  26151. return this._engine;
  26152. };
  26153. /**
  26154. * Gets the total number of vertices rendered per frame
  26155. * @returns the total number of vertices rendered per frame
  26156. */
  26157. Scene.prototype.getTotalVertices = function () {
  26158. return this._totalVertices.current;
  26159. };
  26160. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  26161. /**
  26162. * Gets the performance counter for total vertices
  26163. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26164. */
  26165. get: function () {
  26166. return this._totalVertices;
  26167. },
  26168. enumerable: true,
  26169. configurable: true
  26170. });
  26171. /**
  26172. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  26173. * @returns the total number of active indices rendered per frame
  26174. */
  26175. Scene.prototype.getActiveIndices = function () {
  26176. return this._activeIndices.current;
  26177. };
  26178. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  26179. /**
  26180. * Gets the performance counter for active indices
  26181. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26182. */
  26183. get: function () {
  26184. return this._activeIndices;
  26185. },
  26186. enumerable: true,
  26187. configurable: true
  26188. });
  26189. /**
  26190. * Gets the total number of active particles rendered per frame
  26191. * @returns the total number of active particles rendered per frame
  26192. */
  26193. Scene.prototype.getActiveParticles = function () {
  26194. return this._activeParticles.current;
  26195. };
  26196. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  26197. /**
  26198. * Gets the performance counter for active particles
  26199. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26200. */
  26201. get: function () {
  26202. return this._activeParticles;
  26203. },
  26204. enumerable: true,
  26205. configurable: true
  26206. });
  26207. /**
  26208. * Gets the total number of active bones rendered per frame
  26209. * @returns the total number of active bones rendered per frame
  26210. */
  26211. Scene.prototype.getActiveBones = function () {
  26212. return this._activeBones.current;
  26213. };
  26214. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  26215. /**
  26216. * Gets the performance counter for active bones
  26217. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  26218. */
  26219. get: function () {
  26220. return this._activeBones;
  26221. },
  26222. enumerable: true,
  26223. configurable: true
  26224. });
  26225. /** @hidden */
  26226. Scene.prototype.getInterFramePerfCounter = function () {
  26227. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26228. return 0;
  26229. };
  26230. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  26231. /** @hidden */
  26232. get: function () {
  26233. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26234. return null;
  26235. },
  26236. enumerable: true,
  26237. configurable: true
  26238. });
  26239. /** @hidden */
  26240. Scene.prototype.getLastFrameDuration = function () {
  26241. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  26242. return 0;
  26243. };
  26244. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  26245. /** @hidden */
  26246. get: function () {
  26247. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  26248. return null;
  26249. },
  26250. enumerable: true,
  26251. configurable: true
  26252. });
  26253. /** @hidden */
  26254. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  26255. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  26256. return 0;
  26257. };
  26258. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  26259. /** @hidden */
  26260. get: function () {
  26261. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26262. return null;
  26263. },
  26264. enumerable: true,
  26265. configurable: true
  26266. });
  26267. /**
  26268. * Gets the array of active meshes
  26269. * @returns an array of AbstractMesh
  26270. */
  26271. Scene.prototype.getActiveMeshes = function () {
  26272. return this._activeMeshes;
  26273. };
  26274. /** @hidden */
  26275. Scene.prototype.getRenderTargetsDuration = function () {
  26276. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  26277. return 0;
  26278. };
  26279. /** @hidden */
  26280. Scene.prototype.getRenderDuration = function () {
  26281. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  26282. return 0;
  26283. };
  26284. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  26285. /** @hidden */
  26286. get: function () {
  26287. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26288. return null;
  26289. },
  26290. enumerable: true,
  26291. configurable: true
  26292. });
  26293. /** @hidden */
  26294. Scene.prototype.getParticlesDuration = function () {
  26295. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  26296. return 0;
  26297. };
  26298. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  26299. /** @hidden */
  26300. get: function () {
  26301. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  26302. return null;
  26303. },
  26304. enumerable: true,
  26305. configurable: true
  26306. });
  26307. /** @hidden */
  26308. Scene.prototype.getSpritesDuration = function () {
  26309. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  26310. return 0;
  26311. };
  26312. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  26313. /** @hidden */
  26314. get: function () {
  26315. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  26316. return null;
  26317. },
  26318. enumerable: true,
  26319. configurable: true
  26320. });
  26321. /**
  26322. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  26323. * @returns a number
  26324. */
  26325. Scene.prototype.getAnimationRatio = function () {
  26326. return this._animationRatio !== undefined ? this._animationRatio : 1;
  26327. };
  26328. /**
  26329. * Gets an unique Id for the current render phase
  26330. * @returns a number
  26331. */
  26332. Scene.prototype.getRenderId = function () {
  26333. return this._renderId;
  26334. };
  26335. /**
  26336. * Gets an unique Id for the current frame
  26337. * @returns a number
  26338. */
  26339. Scene.prototype.getFrameId = function () {
  26340. return this._frameId;
  26341. };
  26342. /** Call this function if you want to manually increment the render Id*/
  26343. Scene.prototype.incrementRenderId = function () {
  26344. this._renderId++;
  26345. };
  26346. Scene.prototype._updatePointerPosition = function (evt) {
  26347. var canvasRect = this._engine.getRenderingCanvasClientRect();
  26348. if (!canvasRect) {
  26349. return;
  26350. }
  26351. this._pointerX = evt.clientX - canvasRect.left;
  26352. this._pointerY = evt.clientY - canvasRect.top;
  26353. this._unTranslatedPointerX = this._pointerX;
  26354. this._unTranslatedPointerY = this._pointerY;
  26355. };
  26356. Scene.prototype._createUbo = function () {
  26357. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26358. this._sceneUbo.addUniform("viewProjection", 16);
  26359. this._sceneUbo.addUniform("view", 16);
  26360. };
  26361. Scene.prototype._createAlternateUbo = function () {
  26362. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  26363. this._alternateSceneUbo.addUniform("viewProjection", 16);
  26364. this._alternateSceneUbo.addUniform("view", 16);
  26365. };
  26366. // Pointers handling
  26367. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  26368. if (pointerInfo.pickInfo) {
  26369. if (!pointerInfo.pickInfo.ray) {
  26370. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  26371. }
  26372. }
  26373. };
  26374. /**
  26375. * Use this method to simulate a pointer move on a mesh
  26376. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26377. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26378. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26379. * @returns the current scene
  26380. */
  26381. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  26382. var evt = new PointerEvent("pointermove", pointerEventInit);
  26383. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  26384. return this;
  26385. }
  26386. return this._processPointerMove(pickResult, evt);
  26387. };
  26388. Scene.prototype._processPointerMove = function (pickResult, evt) {
  26389. var canvas = this._engine.getRenderingCanvas();
  26390. if (!canvas) {
  26391. return this;
  26392. }
  26393. // Restore pointer
  26394. canvas.style.cursor = this.defaultCursor;
  26395. var isMeshPicked = (pickResult && pickResult.hit && pickResult.pickedMesh) ? true : false;
  26396. if (isMeshPicked) {
  26397. this.setPointerOverMesh(pickResult.pickedMesh);
  26398. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  26399. if (this._pointerOverMesh.actionManager.hoverCursor) {
  26400. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  26401. }
  26402. else {
  26403. canvas.style.cursor = this.hoverCursor;
  26404. }
  26405. }
  26406. }
  26407. else {
  26408. this.setPointerOverMesh(null);
  26409. }
  26410. for (var _i = 0, _a = this._pointerMoveStage; _i < _a.length; _i++) {
  26411. var step = _a[_i];
  26412. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, isMeshPicked, canvas);
  26413. }
  26414. if (pickResult) {
  26415. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  26416. if (this.onPointerMove) {
  26417. this.onPointerMove(evt, pickResult, type);
  26418. }
  26419. if (this.onPointerObservable.hasObservers()) {
  26420. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26421. this._setRayOnPointerInfo(pi);
  26422. this.onPointerObservable.notifyObservers(pi, type);
  26423. }
  26424. }
  26425. return this;
  26426. };
  26427. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  26428. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  26429. if (pickResult) {
  26430. pi.ray = pickResult.ray;
  26431. }
  26432. this.onPrePointerObservable.notifyObservers(pi, type);
  26433. if (pi.skipOnPointerObservable) {
  26434. return true;
  26435. }
  26436. else {
  26437. return false;
  26438. }
  26439. };
  26440. /**
  26441. * Use this method to simulate a pointer down on a mesh
  26442. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26443. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26444. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26445. * @returns the current scene
  26446. */
  26447. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  26448. var evt = new PointerEvent("pointerdown", pointerEventInit);
  26449. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26450. return this;
  26451. }
  26452. return this._processPointerDown(pickResult, evt);
  26453. };
  26454. Scene.prototype._processPointerDown = function (pickResult, evt) {
  26455. var _this = this;
  26456. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  26457. this._pickedDownMesh = pickResult.pickedMesh;
  26458. var actionManager = pickResult.pickedMesh.actionManager;
  26459. if (actionManager) {
  26460. if (actionManager.hasPickTriggers) {
  26461. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26462. switch (evt.button) {
  26463. case 0:
  26464. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26465. break;
  26466. case 1:
  26467. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26468. break;
  26469. case 2:
  26470. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26471. break;
  26472. }
  26473. }
  26474. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  26475. window.setTimeout(function () {
  26476. 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);
  26477. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  26478. if (_this._totalPointersPressed !== 0 &&
  26479. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  26480. !_this._isPointerSwiping()) {
  26481. _this._startingPointerTime = 0;
  26482. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26483. }
  26484. }
  26485. }, Scene.LongPressDelay);
  26486. }
  26487. }
  26488. }
  26489. else {
  26490. for (var _i = 0, _a = this._pointerDownStage; _i < _a.length; _i++) {
  26491. var step = _a[_i];
  26492. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26493. }
  26494. }
  26495. if (pickResult) {
  26496. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  26497. if (this.onPointerDown) {
  26498. this.onPointerDown(evt, pickResult, type);
  26499. }
  26500. if (this.onPointerObservable.hasObservers()) {
  26501. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26502. this._setRayOnPointerInfo(pi);
  26503. this.onPointerObservable.notifyObservers(pi, type);
  26504. }
  26505. }
  26506. return this;
  26507. };
  26508. /**
  26509. * Use this method to simulate a pointer up on a mesh
  26510. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  26511. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  26512. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  26513. * @returns the current scene
  26514. */
  26515. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  26516. var evt = new PointerEvent("pointerup", pointerEventInit);
  26517. var clickInfo = new ClickInfo();
  26518. clickInfo.singleClick = true;
  26519. clickInfo.ignore = true;
  26520. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26521. return this;
  26522. }
  26523. return this._processPointerUp(pickResult, evt, clickInfo);
  26524. };
  26525. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  26526. if (pickResult && pickResult && pickResult.pickedMesh) {
  26527. this._pickedUpMesh = pickResult.pickedMesh;
  26528. if (this._pickedDownMesh === this._pickedUpMesh) {
  26529. if (this.onPointerPick) {
  26530. this.onPointerPick(evt, pickResult);
  26531. }
  26532. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  26533. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  26534. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  26535. this._setRayOnPointerInfo(pi);
  26536. this.onPointerObservable.notifyObservers(pi, type_1);
  26537. }
  26538. }
  26539. if (pickResult.pickedMesh.actionManager) {
  26540. if (clickInfo.ignore) {
  26541. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26542. }
  26543. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  26544. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26545. }
  26546. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26547. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  26548. }
  26549. }
  26550. }
  26551. else {
  26552. if (!clickInfo.ignore) {
  26553. for (var _i = 0, _a = this._pointerUpStage; _i < _a.length; _i++) {
  26554. var step = _a[_i];
  26555. pickResult = step.action(this._unTranslatedPointerX, this._unTranslatedPointerY, pickResult, evt);
  26556. }
  26557. }
  26558. }
  26559. if (this._pickedDownMesh &&
  26560. this._pickedDownMesh.actionManager &&
  26561. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  26562. this._pickedDownMesh !== this._pickedUpMesh) {
  26563. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  26564. }
  26565. var type = BABYLON.PointerEventTypes.POINTERUP;
  26566. if (this.onPointerObservable.hasObservers()) {
  26567. if (!clickInfo.ignore) {
  26568. if (!clickInfo.hasSwiped) {
  26569. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26570. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  26571. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  26572. this._setRayOnPointerInfo(pi);
  26573. this.onPointerObservable.notifyObservers(pi, type_2);
  26574. }
  26575. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26576. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  26577. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  26578. this._setRayOnPointerInfo(pi);
  26579. this.onPointerObservable.notifyObservers(pi, type_3);
  26580. }
  26581. }
  26582. }
  26583. else {
  26584. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  26585. this._setRayOnPointerInfo(pi);
  26586. this.onPointerObservable.notifyObservers(pi, type);
  26587. }
  26588. }
  26589. if (this.onPointerUp) {
  26590. this.onPointerUp(evt, pickResult, type);
  26591. }
  26592. return this;
  26593. };
  26594. /**
  26595. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  26596. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  26597. * @returns true if the pointer was captured
  26598. */
  26599. Scene.prototype.isPointerCaptured = function (pointerId) {
  26600. if (pointerId === void 0) { pointerId = 0; }
  26601. return this._pointerCaptures[pointerId];
  26602. };
  26603. /** @hidden */
  26604. Scene.prototype._isPointerSwiping = function () {
  26605. return Math.abs(this._startingPointerPosition.x - this._pointerX) > Scene.DragMovementThreshold ||
  26606. Math.abs(this._startingPointerPosition.y - this._pointerY) > Scene.DragMovementThreshold;
  26607. };
  26608. /**
  26609. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  26610. * @param attachUp defines if you want to attach events to pointerup
  26611. * @param attachDown defines if you want to attach events to pointerdown
  26612. * @param attachMove defines if you want to attach events to pointermove
  26613. */
  26614. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  26615. var _this = this;
  26616. if (attachUp === void 0) { attachUp = true; }
  26617. if (attachDown === void 0) { attachDown = true; }
  26618. if (attachMove === void 0) { attachMove = true; }
  26619. this._initActionManager = function (act, clickInfo) {
  26620. if (!_this._meshPickProceed) {
  26621. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26622. _this._currentPickResult = pickResult;
  26623. if (pickResult) {
  26624. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  26625. }
  26626. _this._meshPickProceed = true;
  26627. }
  26628. return act;
  26629. };
  26630. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  26631. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  26632. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  26633. btn !== _this._previousButtonPressed) {
  26634. _this._doubleClickOccured = false;
  26635. clickInfo.singleClick = true;
  26636. clickInfo.ignore = false;
  26637. cb(clickInfo, _this._currentPickResult);
  26638. }
  26639. };
  26640. this._initClickEvent = function (obs1, obs2, evt, cb) {
  26641. var clickInfo = new ClickInfo();
  26642. _this._currentPickResult = null;
  26643. var act = null;
  26644. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  26645. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  26646. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26647. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  26648. act = _this._initActionManager(act, clickInfo);
  26649. if (act)
  26650. checkPicking = act.hasPickTriggers;
  26651. }
  26652. if (checkPicking) {
  26653. var btn = evt.button;
  26654. clickInfo.hasSwiped = _this._isPointerSwiping();
  26655. if (!clickInfo.hasSwiped) {
  26656. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  26657. if (!checkSingleClickImmediately) {
  26658. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  26659. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26660. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26661. act = _this._initActionManager(act, clickInfo);
  26662. if (act)
  26663. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26664. }
  26665. }
  26666. if (checkSingleClickImmediately) {
  26667. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  26668. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  26669. btn !== _this._previousButtonPressed) {
  26670. clickInfo.singleClick = true;
  26671. cb(clickInfo, _this._currentPickResult);
  26672. }
  26673. }
  26674. // at least one double click is required to be check and exclusive double click is enabled
  26675. else {
  26676. // wait that no double click has been raised during the double click delay
  26677. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26678. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  26679. }
  26680. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  26681. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  26682. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  26683. act = _this._initActionManager(act, clickInfo);
  26684. if (act)
  26685. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  26686. }
  26687. if (checkDoubleClick) {
  26688. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  26689. if (btn === _this._previousButtonPressed &&
  26690. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  26691. !_this._doubleClickOccured) {
  26692. // pointer has not moved for 2 clicks, it's a double click
  26693. if (!clickInfo.hasSwiped &&
  26694. !_this._isPointerSwiping()) {
  26695. _this._previousStartingPointerTime = 0;
  26696. _this._doubleClickOccured = true;
  26697. clickInfo.doubleClick = true;
  26698. clickInfo.ignore = false;
  26699. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  26700. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26701. }
  26702. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26703. cb(clickInfo, _this._currentPickResult);
  26704. }
  26705. // if the two successive clicks are too far, it's just two simple clicks
  26706. else {
  26707. _this._doubleClickOccured = false;
  26708. _this._previousStartingPointerTime = _this._startingPointerTime;
  26709. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26710. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26711. _this._previousButtonPressed = btn;
  26712. if (Scene.ExclusiveDoubleClickMode) {
  26713. if (_this._previousDelayedSimpleClickTimeout) {
  26714. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  26715. }
  26716. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  26717. cb(clickInfo, _this._previousPickResult);
  26718. }
  26719. else {
  26720. cb(clickInfo, _this._currentPickResult);
  26721. }
  26722. }
  26723. }
  26724. // just the first click of the double has been raised
  26725. else {
  26726. _this._doubleClickOccured = false;
  26727. _this._previousStartingPointerTime = _this._startingPointerTime;
  26728. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  26729. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  26730. _this._previousButtonPressed = btn;
  26731. }
  26732. }
  26733. }
  26734. }
  26735. clickInfo.ignore = true;
  26736. cb(clickInfo, _this._currentPickResult);
  26737. };
  26738. this._onPointerMove = function (evt) {
  26739. _this._updatePointerPosition(evt);
  26740. // PreObservable support
  26741. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  26742. return;
  26743. }
  26744. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26745. return;
  26746. }
  26747. if (!_this.pointerMovePredicate) {
  26748. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  26749. }
  26750. // Meshes
  26751. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  26752. _this._processPointerMove(pickResult, evt);
  26753. };
  26754. this._onPointerDown = function (evt) {
  26755. _this._totalPointersPressed++;
  26756. _this._pickedDownMesh = null;
  26757. _this._meshPickProceed = false;
  26758. _this._updatePointerPosition(evt);
  26759. if (_this.preventDefaultOnPointerDown && canvas) {
  26760. evt.preventDefault();
  26761. canvas.focus();
  26762. }
  26763. // PreObservable support
  26764. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  26765. return;
  26766. }
  26767. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26768. return;
  26769. }
  26770. _this._pointerCaptures[evt.pointerId] = true;
  26771. _this._startingPointerPosition.x = _this._pointerX;
  26772. _this._startingPointerPosition.y = _this._pointerY;
  26773. _this._startingPointerTime = Date.now();
  26774. if (!_this.pointerDownPredicate) {
  26775. _this.pointerDownPredicate = function (mesh) {
  26776. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26777. };
  26778. }
  26779. // Meshes
  26780. _this._pickedDownMesh = null;
  26781. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  26782. _this._processPointerDown(pickResult, evt);
  26783. };
  26784. this._onPointerUp = function (evt) {
  26785. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  26786. return; // So we need to test it the pointer down was pressed before.
  26787. }
  26788. _this._totalPointersPressed--;
  26789. _this._pickedUpMesh = null;
  26790. _this._meshPickProceed = false;
  26791. _this._updatePointerPosition(evt);
  26792. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  26793. // PreObservable support
  26794. if (_this.onPrePointerObservable.hasObservers()) {
  26795. if (!clickInfo.ignore) {
  26796. if (!clickInfo.hasSwiped) {
  26797. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  26798. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  26799. return;
  26800. }
  26801. }
  26802. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26803. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  26804. return;
  26805. }
  26806. }
  26807. }
  26808. }
  26809. else {
  26810. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  26811. return;
  26812. }
  26813. }
  26814. }
  26815. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  26816. return;
  26817. }
  26818. _this._pointerCaptures[evt.pointerId] = false;
  26819. if (!_this.pointerUpPredicate) {
  26820. _this.pointerUpPredicate = function (mesh) {
  26821. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  26822. };
  26823. }
  26824. // Meshes
  26825. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  26826. _this._initActionManager(null, clickInfo);
  26827. }
  26828. if (!pickResult) {
  26829. pickResult = _this._currentPickResult;
  26830. }
  26831. _this._processPointerUp(pickResult, evt, clickInfo);
  26832. _this._previousPickResult = _this._currentPickResult;
  26833. });
  26834. };
  26835. this._onKeyDown = function (evt) {
  26836. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  26837. if (_this.onPreKeyboardObservable.hasObservers()) {
  26838. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26839. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26840. if (pi.skipOnPointerObservable) {
  26841. return;
  26842. }
  26843. }
  26844. if (_this.onKeyboardObservable.hasObservers()) {
  26845. var pi = new BABYLON.KeyboardInfo(type, evt);
  26846. _this.onKeyboardObservable.notifyObservers(pi, type);
  26847. }
  26848. if (_this.actionManager) {
  26849. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26850. }
  26851. };
  26852. this._onKeyUp = function (evt) {
  26853. var type = BABYLON.KeyboardEventTypes.KEYUP;
  26854. if (_this.onPreKeyboardObservable.hasObservers()) {
  26855. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  26856. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  26857. if (pi.skipOnPointerObservable) {
  26858. return;
  26859. }
  26860. }
  26861. if (_this.onKeyboardObservable.hasObservers()) {
  26862. var pi = new BABYLON.KeyboardInfo(type, evt);
  26863. _this.onKeyboardObservable.notifyObservers(pi, type);
  26864. }
  26865. if (_this.actionManager) {
  26866. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  26867. }
  26868. };
  26869. var engine = this.getEngine();
  26870. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  26871. if (!canvas) {
  26872. return;
  26873. }
  26874. canvas.addEventListener("keydown", _this._onKeyDown, false);
  26875. canvas.addEventListener("keyup", _this._onKeyUp, false);
  26876. });
  26877. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  26878. if (!canvas) {
  26879. return;
  26880. }
  26881. canvas.removeEventListener("keydown", _this._onKeyDown);
  26882. canvas.removeEventListener("keyup", _this._onKeyUp);
  26883. });
  26884. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26885. var canvas = this._engine.getRenderingCanvas();
  26886. if (!canvas) {
  26887. return;
  26888. }
  26889. if (attachMove) {
  26890. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  26891. // Wheel
  26892. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  26893. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  26894. }
  26895. if (attachDown) {
  26896. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  26897. }
  26898. if (attachUp) {
  26899. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  26900. }
  26901. canvas.tabIndex = 1;
  26902. };
  26903. /** Detaches all event handlers*/
  26904. Scene.prototype.detachControl = function () {
  26905. var engine = this.getEngine();
  26906. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  26907. var canvas = engine.getRenderingCanvas();
  26908. if (!canvas) {
  26909. return;
  26910. }
  26911. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  26912. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  26913. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  26914. if (this._onCanvasBlurObserver) {
  26915. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  26916. }
  26917. if (this._onCanvasFocusObserver) {
  26918. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  26919. }
  26920. // Wheel
  26921. canvas.removeEventListener('mousewheel', this._onPointerMove);
  26922. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  26923. // Keyboard
  26924. canvas.removeEventListener("keydown", this._onKeyDown);
  26925. canvas.removeEventListener("keyup", this._onKeyUp);
  26926. // Observables
  26927. this.onKeyboardObservable.clear();
  26928. this.onPreKeyboardObservable.clear();
  26929. this.onPointerObservable.clear();
  26930. this.onPrePointerObservable.clear();
  26931. };
  26932. /**
  26933. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  26934. * Delay loaded resources are not taking in account
  26935. * @return true if all required resources are ready
  26936. */
  26937. Scene.prototype.isReady = function () {
  26938. if (this._isDisposed) {
  26939. return false;
  26940. }
  26941. if (this._pendingData.length > 0) {
  26942. return false;
  26943. }
  26944. var index;
  26945. var engine = this.getEngine();
  26946. // Geometries
  26947. for (index = 0; index < this.geometries.length; index++) {
  26948. var geometry = this.geometries[index];
  26949. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  26950. return false;
  26951. }
  26952. }
  26953. // Meshes
  26954. for (index = 0; index < this.meshes.length; index++) {
  26955. var mesh = this.meshes[index];
  26956. if (!mesh.isEnabled()) {
  26957. continue;
  26958. }
  26959. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26960. continue;
  26961. }
  26962. if (!mesh.isReady(true)) {
  26963. return false;
  26964. }
  26965. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  26966. // Is Ready For Mesh
  26967. for (var _i = 0, _a = this._isReadyForMeshStage; _i < _a.length; _i++) {
  26968. var step = _a[_i];
  26969. if (!step.action(mesh, hardwareInstancedRendering)) {
  26970. return false;
  26971. }
  26972. }
  26973. }
  26974. // Post-processes
  26975. if (this.activeCameras && this.activeCameras.length > 0) {
  26976. for (var _b = 0, _c = this.activeCameras; _b < _c.length; _b++) {
  26977. var camera = _c[_b];
  26978. if (!camera.isReady(true)) {
  26979. return false;
  26980. }
  26981. }
  26982. }
  26983. else if (this.activeCamera) {
  26984. if (!this.activeCamera.isReady(true)) {
  26985. return false;
  26986. }
  26987. }
  26988. // Particles
  26989. for (var _d = 0, _e = this.particleSystems; _d < _e.length; _d++) {
  26990. var particleSystem = _e[_d];
  26991. if (!particleSystem.isReady()) {
  26992. return false;
  26993. }
  26994. }
  26995. return true;
  26996. };
  26997. /** Resets all cached information relative to material (including effect and visibility) */
  26998. Scene.prototype.resetCachedMaterial = function () {
  26999. this._cachedMaterial = null;
  27000. this._cachedEffect = null;
  27001. this._cachedVisibility = null;
  27002. };
  27003. /**
  27004. * Registers a function to be called before every frame render
  27005. * @param func defines the function to register
  27006. */
  27007. Scene.prototype.registerBeforeRender = function (func) {
  27008. this.onBeforeRenderObservable.add(func);
  27009. };
  27010. /**
  27011. * Unregisters a function called before every frame render
  27012. * @param func defines the function to unregister
  27013. */
  27014. Scene.prototype.unregisterBeforeRender = function (func) {
  27015. this.onBeforeRenderObservable.removeCallback(func);
  27016. };
  27017. /**
  27018. * Registers a function to be called after every frame render
  27019. * @param func defines the function to register
  27020. */
  27021. Scene.prototype.registerAfterRender = function (func) {
  27022. this.onAfterRenderObservable.add(func);
  27023. };
  27024. /**
  27025. * Unregisters a function called after every frame render
  27026. * @param func defines the function to unregister
  27027. */
  27028. Scene.prototype.unregisterAfterRender = function (func) {
  27029. this.onAfterRenderObservable.removeCallback(func);
  27030. };
  27031. Scene.prototype._executeOnceBeforeRender = function (func) {
  27032. var _this = this;
  27033. var execFunc = function () {
  27034. func();
  27035. setTimeout(function () {
  27036. _this.unregisterBeforeRender(execFunc);
  27037. });
  27038. };
  27039. this.registerBeforeRender(execFunc);
  27040. };
  27041. /**
  27042. * The provided function will run before render once and will be disposed afterwards.
  27043. * A timeout delay can be provided so that the function will be executed in N ms.
  27044. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  27045. * @param func The function to be executed.
  27046. * @param timeout optional delay in ms
  27047. */
  27048. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  27049. var _this = this;
  27050. if (timeout !== undefined) {
  27051. setTimeout(function () {
  27052. _this._executeOnceBeforeRender(func);
  27053. }, timeout);
  27054. }
  27055. else {
  27056. this._executeOnceBeforeRender(func);
  27057. }
  27058. };
  27059. /** @hidden */
  27060. Scene.prototype._addPendingData = function (data) {
  27061. this._pendingData.push(data);
  27062. };
  27063. /** @hidden */
  27064. Scene.prototype._removePendingData = function (data) {
  27065. var wasLoading = this.isLoading;
  27066. var index = this._pendingData.indexOf(data);
  27067. if (index !== -1) {
  27068. this._pendingData.splice(index, 1);
  27069. }
  27070. if (wasLoading && !this.isLoading) {
  27071. this.onDataLoadedObservable.notifyObservers(this);
  27072. }
  27073. };
  27074. /**
  27075. * Returns the number of items waiting to be loaded
  27076. * @returns the number of items waiting to be loaded
  27077. */
  27078. Scene.prototype.getWaitingItemsCount = function () {
  27079. return this._pendingData.length;
  27080. };
  27081. Object.defineProperty(Scene.prototype, "isLoading", {
  27082. /**
  27083. * Returns a boolean indicating if the scene is still loading data
  27084. */
  27085. get: function () {
  27086. return this._pendingData.length > 0;
  27087. },
  27088. enumerable: true,
  27089. configurable: true
  27090. });
  27091. /**
  27092. * Registers a function to be executed when the scene is ready
  27093. * @param {Function} func - the function to be executed
  27094. */
  27095. Scene.prototype.executeWhenReady = function (func) {
  27096. var _this = this;
  27097. this.onReadyObservable.add(func);
  27098. if (this._executeWhenReadyTimeoutId !== -1) {
  27099. return;
  27100. }
  27101. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27102. _this._checkIsReady();
  27103. }, 150);
  27104. };
  27105. /**
  27106. * Returns a promise that resolves when the scene is ready
  27107. * @returns A promise that resolves when the scene is ready
  27108. */
  27109. Scene.prototype.whenReadyAsync = function () {
  27110. var _this = this;
  27111. return new Promise(function (resolve) {
  27112. _this.executeWhenReady(function () {
  27113. resolve();
  27114. });
  27115. });
  27116. };
  27117. /** @hidden */
  27118. Scene.prototype._checkIsReady = function () {
  27119. var _this = this;
  27120. this._registerTransientComponents();
  27121. if (this.isReady()) {
  27122. this.onReadyObservable.notifyObservers(this);
  27123. this.onReadyObservable.clear();
  27124. this._executeWhenReadyTimeoutId = -1;
  27125. return;
  27126. }
  27127. this._executeWhenReadyTimeoutId = setTimeout(function () {
  27128. _this._checkIsReady();
  27129. }, 150);
  27130. };
  27131. // Animations
  27132. /**
  27133. * Will start the animation sequence of a given target
  27134. * @param target defines the target
  27135. * @param from defines from which frame should animation start
  27136. * @param to defines until which frame should animation run.
  27137. * @param weight defines the weight to apply to the animation (1.0 by default)
  27138. * @param loop defines if the animation loops
  27139. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27140. * @param onAnimationEnd defines the function to be executed when the animation ends
  27141. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27142. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27143. * @returns the animatable object created for this animation
  27144. */
  27145. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable, targetMask) {
  27146. if (weight === void 0) { weight = 1.0; }
  27147. if (speedRatio === void 0) { speedRatio = 1.0; }
  27148. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false, targetMask);
  27149. returnedAnimatable.weight = weight;
  27150. return returnedAnimatable;
  27151. };
  27152. /**
  27153. * Will start the animation sequence of a given target
  27154. * @param target defines the target
  27155. * @param from defines from which frame should animation start
  27156. * @param to defines until which frame should animation run.
  27157. * @param loop defines if the animation loops
  27158. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  27159. * @param onAnimationEnd defines the function to be executed when the animation ends
  27160. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  27161. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  27162. * @param targetMask defines if the target should be animated if animations are present (this is called recursively on descendant animatables regardless of return value)
  27163. * @returns the animatable object created for this animation
  27164. */
  27165. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask) {
  27166. if (speedRatio === void 0) { speedRatio = 1.0; }
  27167. if (stopCurrent === void 0) { stopCurrent = true; }
  27168. if (from > to && speedRatio > 0) {
  27169. speedRatio *= -1;
  27170. }
  27171. if (stopCurrent) {
  27172. this.stopAnimation(target, undefined, targetMask);
  27173. }
  27174. if (!animatable) {
  27175. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  27176. }
  27177. var shouldRunTargetAnimations = targetMask ? targetMask(target) : true;
  27178. // Local animations
  27179. if (target.animations && shouldRunTargetAnimations) {
  27180. animatable.appendAnimations(target, target.animations);
  27181. }
  27182. // Children animations
  27183. if (target.getAnimatables) {
  27184. var animatables = target.getAnimatables();
  27185. for (var index = 0; index < animatables.length; index++) {
  27186. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent, targetMask);
  27187. }
  27188. }
  27189. animatable.reset();
  27190. return animatable;
  27191. };
  27192. /**
  27193. * Begin a new animation on a given node
  27194. * @param target defines the target where the animation will take place
  27195. * @param animations defines the list of animations to start
  27196. * @param from defines the initial value
  27197. * @param to defines the final value
  27198. * @param loop defines if you want animation to loop (off by default)
  27199. * @param speedRatio defines the speed ratio to apply to all animations
  27200. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27201. * @returns the list of created animatables
  27202. */
  27203. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27204. if (speedRatio === undefined) {
  27205. speedRatio = 1.0;
  27206. }
  27207. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  27208. return animatable;
  27209. };
  27210. /**
  27211. * Begin a new animation on a given node and its hierarchy
  27212. * @param target defines the root node where the animation will take place
  27213. * @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.
  27214. * @param animations defines the list of animations to start
  27215. * @param from defines the initial value
  27216. * @param to defines the final value
  27217. * @param loop defines if you want animation to loop (off by default)
  27218. * @param speedRatio defines the speed ratio to apply to all animations
  27219. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  27220. * @returns the list of animatables created for all nodes
  27221. */
  27222. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  27223. var children = target.getDescendants(directDescendantsOnly);
  27224. var result = [];
  27225. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  27226. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  27227. var child = children_1[_i];
  27228. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  27229. }
  27230. return result;
  27231. };
  27232. /**
  27233. * Gets the animatable associated with a specific target
  27234. * @param target defines the target of the animatable
  27235. * @returns the required animatable if found
  27236. */
  27237. Scene.prototype.getAnimatableByTarget = function (target) {
  27238. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27239. if (this._activeAnimatables[index].target === target) {
  27240. return this._activeAnimatables[index];
  27241. }
  27242. }
  27243. return null;
  27244. };
  27245. /**
  27246. * Gets all animatables associated with a given target
  27247. * @param target defines the target to look animatables for
  27248. * @returns an array of Animatables
  27249. */
  27250. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  27251. var result = [];
  27252. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27253. if (this._activeAnimatables[index].target === target) {
  27254. result.push(this._activeAnimatables[index]);
  27255. }
  27256. }
  27257. return result;
  27258. };
  27259. Object.defineProperty(Scene.prototype, "animatables", {
  27260. /**
  27261. * Gets all animatable attached to the scene
  27262. */
  27263. get: function () {
  27264. return this._activeAnimatables;
  27265. },
  27266. enumerable: true,
  27267. configurable: true
  27268. });
  27269. /**
  27270. * Will stop the animation of the given target
  27271. * @param target - the target
  27272. * @param animationName - the name of the animation to stop (all animations will be stopped if both this and targetMask are empty)
  27273. * @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)
  27274. */
  27275. Scene.prototype.stopAnimation = function (target, animationName, targetMask) {
  27276. var animatables = this.getAllAnimatablesByTarget(target);
  27277. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  27278. var animatable = animatables_1[_i];
  27279. animatable.stop(animationName, targetMask);
  27280. }
  27281. };
  27282. /**
  27283. * Stops and removes all animations that have been applied to the scene
  27284. */
  27285. Scene.prototype.stopAllAnimations = function () {
  27286. if (this._activeAnimatables) {
  27287. for (var i = 0; i < this._activeAnimatables.length; i++) {
  27288. this._activeAnimatables[i].stop();
  27289. }
  27290. this._activeAnimatables = [];
  27291. }
  27292. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  27293. var group = _a[_i];
  27294. group.stop();
  27295. }
  27296. };
  27297. Scene.prototype._animate = function () {
  27298. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  27299. return;
  27300. }
  27301. // Getting time
  27302. var now = BABYLON.Tools.Now;
  27303. if (!this._animationTimeLast) {
  27304. if (this._pendingData.length > 0) {
  27305. return;
  27306. }
  27307. this._animationTimeLast = now;
  27308. }
  27309. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  27310. this._animationTime += deltaTime;
  27311. this._animationTimeLast = now;
  27312. for (var index = 0; index < this._activeAnimatables.length; index++) {
  27313. this._activeAnimatables[index]._animate(this._animationTime);
  27314. }
  27315. // Late animation bindings
  27316. this._processLateAnimationBindings();
  27317. };
  27318. /** @hidden */
  27319. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  27320. var target = runtimeAnimation.target;
  27321. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  27322. if (!target._lateAnimationHolders) {
  27323. target._lateAnimationHolders = {};
  27324. }
  27325. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  27326. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  27327. totalWeight: 0,
  27328. animations: [],
  27329. originalValue: originalValue
  27330. };
  27331. }
  27332. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  27333. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  27334. };
  27335. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  27336. var normalizer = 1.0;
  27337. var finalPosition = BABYLON.Tmp.Vector3[0];
  27338. var finalScaling = BABYLON.Tmp.Vector3[1];
  27339. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  27340. var startIndex = 0;
  27341. var originalAnimation = holder.animations[0];
  27342. var originalValue = holder.originalValue;
  27343. var scale = 1;
  27344. if (holder.totalWeight < 1.0) {
  27345. // We need to mix the original value in
  27346. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27347. scale = 1.0 - holder.totalWeight;
  27348. }
  27349. else {
  27350. startIndex = 1;
  27351. // We need to normalize the weights
  27352. normalizer = holder.totalWeight;
  27353. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  27354. scale = originalAnimation.weight / normalizer;
  27355. if (scale == 1) {
  27356. return originalAnimation.currentValue;
  27357. }
  27358. }
  27359. finalScaling.scaleInPlace(scale);
  27360. finalPosition.scaleInPlace(scale);
  27361. finalQuaternion.scaleInPlace(scale);
  27362. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27363. var runtimeAnimation = holder.animations[animIndex];
  27364. var scale = runtimeAnimation.weight / normalizer;
  27365. var currentPosition = BABYLON.Tmp.Vector3[2];
  27366. var currentScaling = BABYLON.Tmp.Vector3[3];
  27367. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  27368. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  27369. currentScaling.scaleAndAddToRef(scale, finalScaling);
  27370. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  27371. currentPosition.scaleAndAddToRef(scale, finalPosition);
  27372. }
  27373. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  27374. return originalAnimation._workValue;
  27375. };
  27376. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder, refQuaternion) {
  27377. var originalAnimation = holder.animations[0];
  27378. var originalValue = holder.originalValue;
  27379. if (holder.animations.length === 1) {
  27380. BABYLON.Quaternion.SlerpToRef(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight), refQuaternion);
  27381. return refQuaternion;
  27382. }
  27383. var normalizer = 1.0;
  27384. var quaternions;
  27385. var weights;
  27386. if (holder.totalWeight < 1.0) {
  27387. var scale = 1.0 - holder.totalWeight;
  27388. quaternions = [];
  27389. weights = [];
  27390. quaternions.push(originalValue);
  27391. weights.push(scale);
  27392. }
  27393. else {
  27394. if (holder.animations.length === 2) { // Slerp as soon as we can
  27395. BABYLON.Quaternion.SlerpToRef(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight, refQuaternion);
  27396. return refQuaternion;
  27397. }
  27398. quaternions = [];
  27399. weights = [];
  27400. normalizer = holder.totalWeight;
  27401. }
  27402. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  27403. var runtimeAnimation = holder.animations[animIndex];
  27404. quaternions.push(runtimeAnimation.currentValue);
  27405. weights.push(runtimeAnimation.weight / normalizer);
  27406. }
  27407. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  27408. var cumulativeAmount = 0;
  27409. var cumulativeQuaternion = null;
  27410. for (var index = 0; index < quaternions.length;) {
  27411. if (!cumulativeQuaternion) {
  27412. BABYLON.Quaternion.SlerpToRef(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]), refQuaternion);
  27413. cumulativeQuaternion = refQuaternion;
  27414. cumulativeAmount = weights[index] + weights[index + 1];
  27415. index += 2;
  27416. continue;
  27417. }
  27418. cumulativeAmount += weights[index];
  27419. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  27420. index++;
  27421. }
  27422. return cumulativeQuaternion;
  27423. };
  27424. Scene.prototype._processLateAnimationBindings = function () {
  27425. if (!this._registeredForLateAnimationBindings.length) {
  27426. return;
  27427. }
  27428. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  27429. var target = this._registeredForLateAnimationBindings.data[index];
  27430. for (var path in target._lateAnimationHolders) {
  27431. var holder = target._lateAnimationHolders[path];
  27432. var originalAnimation = holder.animations[0];
  27433. var originalValue = holder.originalValue;
  27434. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  27435. var finalValue = target[path];
  27436. if (matrixDecomposeMode) {
  27437. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  27438. }
  27439. else {
  27440. var quaternionMode = originalValue.w !== undefined;
  27441. if (quaternionMode) {
  27442. finalValue = this._processLateAnimationBindingsForQuaternions(holder, finalValue || BABYLON.Quaternion.Identity());
  27443. }
  27444. else {
  27445. var startIndex = 0;
  27446. var normalizer = 1.0;
  27447. if (holder.totalWeight < 1.0) {
  27448. // We need to mix the original value in
  27449. if (originalValue.scale) {
  27450. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  27451. }
  27452. else {
  27453. finalValue = originalValue * (1.0 - holder.totalWeight);
  27454. }
  27455. }
  27456. else {
  27457. // We need to normalize the weights
  27458. normalizer = holder.totalWeight;
  27459. var scale_1 = originalAnimation.weight / normalizer;
  27460. if (scale_1 !== 1) {
  27461. if (originalAnimation.currentValue.scale) {
  27462. finalValue = originalAnimation.currentValue.scale(scale_1);
  27463. }
  27464. else {
  27465. finalValue = originalAnimation.currentValue * scale_1;
  27466. }
  27467. }
  27468. else {
  27469. finalValue = originalAnimation.currentValue;
  27470. }
  27471. startIndex = 1;
  27472. }
  27473. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  27474. var runtimeAnimation = holder.animations[animIndex];
  27475. var scale = runtimeAnimation.weight / normalizer;
  27476. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  27477. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  27478. }
  27479. else {
  27480. finalValue += runtimeAnimation.currentValue * scale;
  27481. }
  27482. }
  27483. }
  27484. }
  27485. target[path] = finalValue;
  27486. }
  27487. target._lateAnimationHolders = {};
  27488. }
  27489. this._registeredForLateAnimationBindings.reset();
  27490. };
  27491. // Matrix
  27492. /** @hidden */
  27493. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  27494. this._useAlternateCameraConfiguration = active;
  27495. };
  27496. /**
  27497. * Gets the current view matrix
  27498. * @returns a Matrix
  27499. */
  27500. Scene.prototype.getViewMatrix = function () {
  27501. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  27502. };
  27503. /**
  27504. * Gets the current projection matrix
  27505. * @returns a Matrix
  27506. */
  27507. Scene.prototype.getProjectionMatrix = function () {
  27508. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  27509. };
  27510. /**
  27511. * Gets the current transform matrix
  27512. * @returns a Matrix made of View * Projection
  27513. */
  27514. Scene.prototype.getTransformMatrix = function () {
  27515. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  27516. };
  27517. /**
  27518. * Sets the current transform matrix
  27519. * @param view defines the View matrix to use
  27520. * @param projection defines the Projection matrix to use
  27521. */
  27522. Scene.prototype.setTransformMatrix = function (view, projection) {
  27523. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  27524. return;
  27525. }
  27526. this._viewUpdateFlag = view.updateFlag;
  27527. this._projectionUpdateFlag = projection.updateFlag;
  27528. this._viewMatrix = view;
  27529. this._projectionMatrix = projection;
  27530. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  27531. // Update frustum
  27532. if (!this._frustumPlanes) {
  27533. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  27534. }
  27535. else {
  27536. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  27537. }
  27538. if (this.activeCamera && this.activeCamera._alternateCamera) {
  27539. var otherCamera = this.activeCamera._alternateCamera;
  27540. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  27541. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  27542. }
  27543. if (this._sceneUbo.useUbo) {
  27544. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  27545. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  27546. this._sceneUbo.update();
  27547. }
  27548. };
  27549. /** @hidden */
  27550. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  27551. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  27552. return;
  27553. }
  27554. this._alternateViewUpdateFlag = view.updateFlag;
  27555. this._alternateProjectionUpdateFlag = projection.updateFlag;
  27556. this._alternateViewMatrix = view;
  27557. this._alternateProjectionMatrix = projection;
  27558. if (!this._alternateTransformMatrix) {
  27559. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  27560. }
  27561. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  27562. if (!this._alternateSceneUbo) {
  27563. this._createAlternateUbo();
  27564. }
  27565. if (this._alternateSceneUbo.useUbo) {
  27566. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  27567. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  27568. this._alternateSceneUbo.update();
  27569. }
  27570. };
  27571. /**
  27572. * Gets the uniform buffer used to store scene data
  27573. * @returns a UniformBuffer
  27574. */
  27575. Scene.prototype.getSceneUniformBuffer = function () {
  27576. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  27577. };
  27578. /**
  27579. * Gets an unique (relatively to the current scene) Id
  27580. * @returns an unique number for the scene
  27581. */
  27582. Scene.prototype.getUniqueId = function () {
  27583. var result = Scene._uniqueIdCounter;
  27584. Scene._uniqueIdCounter++;
  27585. return result;
  27586. };
  27587. /**
  27588. * Add a mesh to the list of scene's meshes
  27589. * @param newMesh defines the mesh to add
  27590. * @param recursive if all child meshes should also be added to the scene
  27591. */
  27592. Scene.prototype.addMesh = function (newMesh, recursive) {
  27593. var _this = this;
  27594. if (recursive === void 0) { recursive = false; }
  27595. this.meshes.push(newMesh);
  27596. //notify the collision coordinator
  27597. if (this.collisionCoordinator) {
  27598. this.collisionCoordinator.onMeshAdded(newMesh);
  27599. }
  27600. newMesh._resyncLightSources();
  27601. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  27602. if (recursive) {
  27603. newMesh.getChildMeshes().forEach(function (m) {
  27604. _this.addMesh(m);
  27605. });
  27606. }
  27607. };
  27608. /**
  27609. * Remove a mesh for the list of scene's meshes
  27610. * @param toRemove defines the mesh to remove
  27611. * @param recursive if all child meshes should also be removed from the scene
  27612. * @returns the index where the mesh was in the mesh list
  27613. */
  27614. Scene.prototype.removeMesh = function (toRemove, recursive) {
  27615. var _this = this;
  27616. if (recursive === void 0) { recursive = false; }
  27617. var index = this.meshes.indexOf(toRemove);
  27618. if (index !== -1) {
  27619. // Remove from the scene if mesh found
  27620. this.meshes.splice(index, 1);
  27621. }
  27622. this.onMeshRemovedObservable.notifyObservers(toRemove);
  27623. if (recursive) {
  27624. toRemove.getChildMeshes().forEach(function (m) {
  27625. _this.removeMesh(m);
  27626. });
  27627. }
  27628. return index;
  27629. };
  27630. /**
  27631. * Add a transform node to the list of scene's transform nodes
  27632. * @param newTransformNode defines the transform node to add
  27633. */
  27634. Scene.prototype.addTransformNode = function (newTransformNode) {
  27635. this.transformNodes.push(newTransformNode);
  27636. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  27637. };
  27638. /**
  27639. * Remove a transform node for the list of scene's transform nodes
  27640. * @param toRemove defines the transform node to remove
  27641. * @returns the index where the transform node was in the transform node list
  27642. */
  27643. Scene.prototype.removeTransformNode = function (toRemove) {
  27644. var index = this.transformNodes.indexOf(toRemove);
  27645. if (index !== -1) {
  27646. // Remove from the scene if found
  27647. this.transformNodes.splice(index, 1);
  27648. }
  27649. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  27650. return index;
  27651. };
  27652. /**
  27653. * Remove a skeleton for the list of scene's skeletons
  27654. * @param toRemove defines the skeleton to remove
  27655. * @returns the index where the skeleton was in the skeleton list
  27656. */
  27657. Scene.prototype.removeSkeleton = function (toRemove) {
  27658. var index = this.skeletons.indexOf(toRemove);
  27659. if (index !== -1) {
  27660. // Remove from the scene if found
  27661. this.skeletons.splice(index, 1);
  27662. }
  27663. return index;
  27664. };
  27665. /**
  27666. * Remove a morph target for the list of scene's morph targets
  27667. * @param toRemove defines the morph target to remove
  27668. * @returns the index where the morph target was in the morph target list
  27669. */
  27670. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  27671. var index = this.morphTargetManagers.indexOf(toRemove);
  27672. if (index !== -1) {
  27673. // Remove from the scene if found
  27674. this.morphTargetManagers.splice(index, 1);
  27675. }
  27676. return index;
  27677. };
  27678. /**
  27679. * Remove a light for the list of scene's lights
  27680. * @param toRemove defines the light to remove
  27681. * @returns the index where the light was in the light list
  27682. */
  27683. Scene.prototype.removeLight = function (toRemove) {
  27684. var index = this.lights.indexOf(toRemove);
  27685. if (index !== -1) {
  27686. // Remove from meshes
  27687. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27688. var mesh = _a[_i];
  27689. mesh._removeLightSource(toRemove);
  27690. }
  27691. // Remove from the scene if mesh found
  27692. this.lights.splice(index, 1);
  27693. this.sortLightsByPriority();
  27694. }
  27695. this.onLightRemovedObservable.notifyObservers(toRemove);
  27696. return index;
  27697. };
  27698. /**
  27699. * Remove a camera for the list of scene's cameras
  27700. * @param toRemove defines the camera to remove
  27701. * @returns the index where the camera was in the camera list
  27702. */
  27703. Scene.prototype.removeCamera = function (toRemove) {
  27704. var index = this.cameras.indexOf(toRemove);
  27705. if (index !== -1) {
  27706. // Remove from the scene if mesh found
  27707. this.cameras.splice(index, 1);
  27708. }
  27709. // Remove from activeCameras
  27710. var index2 = this.activeCameras.indexOf(toRemove);
  27711. if (index2 !== -1) {
  27712. // Remove from the scene if mesh found
  27713. this.activeCameras.splice(index2, 1);
  27714. }
  27715. // Reset the activeCamera
  27716. if (this.activeCamera === toRemove) {
  27717. if (this.cameras.length > 0) {
  27718. this.activeCamera = this.cameras[0];
  27719. }
  27720. else {
  27721. this.activeCamera = null;
  27722. }
  27723. }
  27724. this.onCameraRemovedObservable.notifyObservers(toRemove);
  27725. return index;
  27726. };
  27727. /**
  27728. * Remove a particle system for the list of scene's particle systems
  27729. * @param toRemove defines the particle system to remove
  27730. * @returns the index where the particle system was in the particle system list
  27731. */
  27732. Scene.prototype.removeParticleSystem = function (toRemove) {
  27733. var index = this.particleSystems.indexOf(toRemove);
  27734. if (index !== -1) {
  27735. this.particleSystems.splice(index, 1);
  27736. }
  27737. return index;
  27738. };
  27739. /**
  27740. * Remove a animation for the list of scene's animations
  27741. * @param toRemove defines the animation to remove
  27742. * @returns the index where the animation was in the animation list
  27743. */
  27744. Scene.prototype.removeAnimation = function (toRemove) {
  27745. var index = this.animations.indexOf(toRemove);
  27746. if (index !== -1) {
  27747. this.animations.splice(index, 1);
  27748. }
  27749. return index;
  27750. };
  27751. /**
  27752. * Removes the given animation group from this scene.
  27753. * @param toRemove The animation group to remove
  27754. * @returns The index of the removed animation group
  27755. */
  27756. Scene.prototype.removeAnimationGroup = function (toRemove) {
  27757. var index = this.animationGroups.indexOf(toRemove);
  27758. if (index !== -1) {
  27759. this.animationGroups.splice(index, 1);
  27760. }
  27761. return index;
  27762. };
  27763. /**
  27764. * Removes the given multi-material from this scene.
  27765. * @param toRemove The multi-material to remove
  27766. * @returns The index of the removed multi-material
  27767. */
  27768. Scene.prototype.removeMultiMaterial = function (toRemove) {
  27769. var index = this.multiMaterials.indexOf(toRemove);
  27770. if (index !== -1) {
  27771. this.multiMaterials.splice(index, 1);
  27772. }
  27773. return index;
  27774. };
  27775. /**
  27776. * Removes the given material from this scene.
  27777. * @param toRemove The material to remove
  27778. * @returns The index of the removed material
  27779. */
  27780. Scene.prototype.removeMaterial = function (toRemove) {
  27781. var index = this.materials.indexOf(toRemove);
  27782. if (index !== -1) {
  27783. this.materials.splice(index, 1);
  27784. }
  27785. this.onMaterialRemovedObservable.notifyObservers(toRemove);
  27786. return index;
  27787. };
  27788. /**
  27789. * Removes the given action manager from this scene.
  27790. * @param toRemove The action manager to remove
  27791. * @returns The index of the removed action manager
  27792. */
  27793. Scene.prototype.removeActionManager = function (toRemove) {
  27794. var index = this.actionManagers.indexOf(toRemove);
  27795. if (index !== -1) {
  27796. this.actionManagers.splice(index, 1);
  27797. }
  27798. return index;
  27799. };
  27800. /**
  27801. * Removes the given texture from this scene.
  27802. * @param toRemove The texture to remove
  27803. * @returns The index of the removed texture
  27804. */
  27805. Scene.prototype.removeTexture = function (toRemove) {
  27806. var index = this.textures.indexOf(toRemove);
  27807. if (index !== -1) {
  27808. this.textures.splice(index, 1);
  27809. }
  27810. this.onTextureRemovedObservable.notifyObservers(toRemove);
  27811. return index;
  27812. };
  27813. /**
  27814. * Adds the given light to this scene
  27815. * @param newLight The light to add
  27816. */
  27817. Scene.prototype.addLight = function (newLight) {
  27818. this.lights.push(newLight);
  27819. this.sortLightsByPriority();
  27820. // Add light to all meshes (To support if the light is removed and then readded)
  27821. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  27822. var mesh = _a[_i];
  27823. if (mesh._lightSources.indexOf(newLight) === -1) {
  27824. mesh._lightSources.push(newLight);
  27825. mesh._resyncLightSources();
  27826. }
  27827. }
  27828. this.onNewLightAddedObservable.notifyObservers(newLight);
  27829. };
  27830. /**
  27831. * Sorts the list list based on light priorities
  27832. */
  27833. Scene.prototype.sortLightsByPriority = function () {
  27834. if (this.requireLightSorting) {
  27835. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  27836. }
  27837. };
  27838. /**
  27839. * Adds the given camera to this scene
  27840. * @param newCamera The camera to add
  27841. */
  27842. Scene.prototype.addCamera = function (newCamera) {
  27843. this.cameras.push(newCamera);
  27844. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  27845. };
  27846. /**
  27847. * Adds the given skeleton to this scene
  27848. * @param newSkeleton The skeleton to add
  27849. */
  27850. Scene.prototype.addSkeleton = function (newSkeleton) {
  27851. this.skeletons.push(newSkeleton);
  27852. };
  27853. /**
  27854. * Adds the given particle system to this scene
  27855. * @param newParticleSystem The particle system to add
  27856. */
  27857. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  27858. this.particleSystems.push(newParticleSystem);
  27859. };
  27860. /**
  27861. * Adds the given animation to this scene
  27862. * @param newAnimation The animation to add
  27863. */
  27864. Scene.prototype.addAnimation = function (newAnimation) {
  27865. this.animations.push(newAnimation);
  27866. };
  27867. /**
  27868. * Adds the given animation group to this scene.
  27869. * @param newAnimationGroup The animation group to add
  27870. */
  27871. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  27872. this.animationGroups.push(newAnimationGroup);
  27873. };
  27874. /**
  27875. * Adds the given multi-material to this scene
  27876. * @param newMultiMaterial The multi-material to add
  27877. */
  27878. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  27879. this.multiMaterials.push(newMultiMaterial);
  27880. };
  27881. /**
  27882. * Adds the given material to this scene
  27883. * @param newMaterial The material to add
  27884. */
  27885. Scene.prototype.addMaterial = function (newMaterial) {
  27886. this.materials.push(newMaterial);
  27887. this.onNewMaterialAddedObservable.notifyObservers(newMaterial);
  27888. };
  27889. /**
  27890. * Adds the given morph target to this scene
  27891. * @param newMorphTargetManager The morph target to add
  27892. */
  27893. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  27894. this.morphTargetManagers.push(newMorphTargetManager);
  27895. };
  27896. /**
  27897. * Adds the given geometry to this scene
  27898. * @param newGeometry The geometry to add
  27899. */
  27900. Scene.prototype.addGeometry = function (newGeometry) {
  27901. this.geometries.push(newGeometry);
  27902. };
  27903. /**
  27904. * Adds the given action manager to this scene
  27905. * @param newActionManager The action manager to add
  27906. */
  27907. Scene.prototype.addActionManager = function (newActionManager) {
  27908. this.actionManagers.push(newActionManager);
  27909. };
  27910. /**
  27911. * Adds the given texture to this scene.
  27912. * @param newTexture The texture to add
  27913. */
  27914. Scene.prototype.addTexture = function (newTexture) {
  27915. this.textures.push(newTexture);
  27916. this.onNewTextureAddedObservable.notifyObservers(newTexture);
  27917. };
  27918. /**
  27919. * Switch active camera
  27920. * @param newCamera defines the new active camera
  27921. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  27922. */
  27923. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  27924. if (attachControl === void 0) { attachControl = true; }
  27925. var canvas = this._engine.getRenderingCanvas();
  27926. if (!canvas) {
  27927. return;
  27928. }
  27929. if (this.activeCamera) {
  27930. this.activeCamera.detachControl(canvas);
  27931. }
  27932. this.activeCamera = newCamera;
  27933. if (attachControl) {
  27934. newCamera.attachControl(canvas);
  27935. }
  27936. };
  27937. /**
  27938. * sets the active camera of the scene using its ID
  27939. * @param id defines the camera's ID
  27940. * @return the new active camera or null if none found.
  27941. */
  27942. Scene.prototype.setActiveCameraByID = function (id) {
  27943. var camera = this.getCameraByID(id);
  27944. if (camera) {
  27945. this.activeCamera = camera;
  27946. return camera;
  27947. }
  27948. return null;
  27949. };
  27950. /**
  27951. * sets the active camera of the scene using its name
  27952. * @param name defines the camera's name
  27953. * @returns the new active camera or null if none found.
  27954. */
  27955. Scene.prototype.setActiveCameraByName = function (name) {
  27956. var camera = this.getCameraByName(name);
  27957. if (camera) {
  27958. this.activeCamera = camera;
  27959. return camera;
  27960. }
  27961. return null;
  27962. };
  27963. /**
  27964. * get an animation group using its name
  27965. * @param name defines the material's name
  27966. * @return the animation group or null if none found.
  27967. */
  27968. Scene.prototype.getAnimationGroupByName = function (name) {
  27969. for (var index = 0; index < this.animationGroups.length; index++) {
  27970. if (this.animationGroups[index].name === name) {
  27971. return this.animationGroups[index];
  27972. }
  27973. }
  27974. return null;
  27975. };
  27976. /**
  27977. * get a material using its id
  27978. * @param id defines the material's ID
  27979. * @return the material or null if none found.
  27980. */
  27981. Scene.prototype.getMaterialByID = function (id) {
  27982. for (var index = 0; index < this.materials.length; index++) {
  27983. if (this.materials[index].id === id) {
  27984. return this.materials[index];
  27985. }
  27986. }
  27987. return null;
  27988. };
  27989. /**
  27990. * Gets a material using its name
  27991. * @param name defines the material's name
  27992. * @return the material or null if none found.
  27993. */
  27994. Scene.prototype.getMaterialByName = function (name) {
  27995. for (var index = 0; index < this.materials.length; index++) {
  27996. if (this.materials[index].name === name) {
  27997. return this.materials[index];
  27998. }
  27999. }
  28000. return null;
  28001. };
  28002. /**
  28003. * Gets a camera using its id
  28004. * @param id defines the id to look for
  28005. * @returns the camera or null if not found
  28006. */
  28007. Scene.prototype.getCameraByID = function (id) {
  28008. for (var index = 0; index < this.cameras.length; index++) {
  28009. if (this.cameras[index].id === id) {
  28010. return this.cameras[index];
  28011. }
  28012. }
  28013. return null;
  28014. };
  28015. /**
  28016. * Gets a camera using its unique id
  28017. * @param uniqueId defines the unique id to look for
  28018. * @returns the camera or null if not found
  28019. */
  28020. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  28021. for (var index = 0; index < this.cameras.length; index++) {
  28022. if (this.cameras[index].uniqueId === uniqueId) {
  28023. return this.cameras[index];
  28024. }
  28025. }
  28026. return null;
  28027. };
  28028. /**
  28029. * Gets a camera using its name
  28030. * @param name defines the camera's name
  28031. * @return the camera or null if none found.
  28032. */
  28033. Scene.prototype.getCameraByName = function (name) {
  28034. for (var index = 0; index < this.cameras.length; index++) {
  28035. if (this.cameras[index].name === name) {
  28036. return this.cameras[index];
  28037. }
  28038. }
  28039. return null;
  28040. };
  28041. /**
  28042. * Gets a bone using its id
  28043. * @param id defines the bone's id
  28044. * @return the bone or null if not found
  28045. */
  28046. Scene.prototype.getBoneByID = function (id) {
  28047. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28048. var skeleton = this.skeletons[skeletonIndex];
  28049. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28050. if (skeleton.bones[boneIndex].id === id) {
  28051. return skeleton.bones[boneIndex];
  28052. }
  28053. }
  28054. }
  28055. return null;
  28056. };
  28057. /**
  28058. * Gets a bone using its id
  28059. * @param name defines the bone's name
  28060. * @return the bone or null if not found
  28061. */
  28062. Scene.prototype.getBoneByName = function (name) {
  28063. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  28064. var skeleton = this.skeletons[skeletonIndex];
  28065. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  28066. if (skeleton.bones[boneIndex].name === name) {
  28067. return skeleton.bones[boneIndex];
  28068. }
  28069. }
  28070. }
  28071. return null;
  28072. };
  28073. /**
  28074. * Gets a light node using its name
  28075. * @param name defines the the light's name
  28076. * @return the light or null if none found.
  28077. */
  28078. Scene.prototype.getLightByName = function (name) {
  28079. for (var index = 0; index < this.lights.length; index++) {
  28080. if (this.lights[index].name === name) {
  28081. return this.lights[index];
  28082. }
  28083. }
  28084. return null;
  28085. };
  28086. /**
  28087. * Gets a light node using its id
  28088. * @param id defines the light's id
  28089. * @return the light or null if none found.
  28090. */
  28091. Scene.prototype.getLightByID = function (id) {
  28092. for (var index = 0; index < this.lights.length; index++) {
  28093. if (this.lights[index].id === id) {
  28094. return this.lights[index];
  28095. }
  28096. }
  28097. return null;
  28098. };
  28099. /**
  28100. * Gets a light node using its scene-generated unique ID
  28101. * @param uniqueId defines the light's unique id
  28102. * @return the light or null if none found.
  28103. */
  28104. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  28105. for (var index = 0; index < this.lights.length; index++) {
  28106. if (this.lights[index].uniqueId === uniqueId) {
  28107. return this.lights[index];
  28108. }
  28109. }
  28110. return null;
  28111. };
  28112. /**
  28113. * Gets a particle system by id
  28114. * @param id defines the particle system id
  28115. * @return the corresponding system or null if none found
  28116. */
  28117. Scene.prototype.getParticleSystemByID = function (id) {
  28118. for (var index = 0; index < this.particleSystems.length; index++) {
  28119. if (this.particleSystems[index].id === id) {
  28120. return this.particleSystems[index];
  28121. }
  28122. }
  28123. return null;
  28124. };
  28125. /**
  28126. * Gets a geometry using its ID
  28127. * @param id defines the geometry's id
  28128. * @return the geometry or null if none found.
  28129. */
  28130. Scene.prototype.getGeometryByID = function (id) {
  28131. for (var index = 0; index < this.geometries.length; index++) {
  28132. if (this.geometries[index].id === id) {
  28133. return this.geometries[index];
  28134. }
  28135. }
  28136. return null;
  28137. };
  28138. /**
  28139. * Add a new geometry to this scene
  28140. * @param geometry defines the geometry to be added to the scene.
  28141. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  28142. * @return a boolean defining if the geometry was added or not
  28143. */
  28144. Scene.prototype.pushGeometry = function (geometry, force) {
  28145. if (!force && this.getGeometryByID(geometry.id)) {
  28146. return false;
  28147. }
  28148. this.geometries.push(geometry);
  28149. //notify the collision coordinator
  28150. if (this.collisionCoordinator) {
  28151. this.collisionCoordinator.onGeometryAdded(geometry);
  28152. }
  28153. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  28154. return true;
  28155. };
  28156. /**
  28157. * Removes an existing geometry
  28158. * @param geometry defines the geometry to be removed from the scene
  28159. * @return a boolean defining if the geometry was removed or not
  28160. */
  28161. Scene.prototype.removeGeometry = function (geometry) {
  28162. var index = this.geometries.indexOf(geometry);
  28163. if (index > -1) {
  28164. this.geometries.splice(index, 1);
  28165. //notify the collision coordinator
  28166. if (this.collisionCoordinator) {
  28167. this.collisionCoordinator.onGeometryDeleted(geometry);
  28168. }
  28169. this.onGeometryRemovedObservable.notifyObservers(geometry);
  28170. return true;
  28171. }
  28172. return false;
  28173. };
  28174. /**
  28175. * Gets the list of geometries attached to the scene
  28176. * @returns an array of Geometry
  28177. */
  28178. Scene.prototype.getGeometries = function () {
  28179. return this.geometries;
  28180. };
  28181. /**
  28182. * Gets the first added mesh found of a given ID
  28183. * @param id defines the id to search for
  28184. * @return the mesh found or null if not found at all
  28185. */
  28186. Scene.prototype.getMeshByID = function (id) {
  28187. for (var index = 0; index < this.meshes.length; index++) {
  28188. if (this.meshes[index].id === id) {
  28189. return this.meshes[index];
  28190. }
  28191. }
  28192. return null;
  28193. };
  28194. /**
  28195. * Gets a list of meshes using their id
  28196. * @param id defines the id to search for
  28197. * @returns a list of meshes
  28198. */
  28199. Scene.prototype.getMeshesByID = function (id) {
  28200. return this.meshes.filter(function (m) {
  28201. return m.id === id;
  28202. });
  28203. };
  28204. /**
  28205. * Gets the first added transform node found of a given ID
  28206. * @param id defines the id to search for
  28207. * @return the found transform node or null if not found at all.
  28208. */
  28209. Scene.prototype.getTransformNodeByID = function (id) {
  28210. for (var index = 0; index < this.transformNodes.length; index++) {
  28211. if (this.transformNodes[index].id === id) {
  28212. return this.transformNodes[index];
  28213. }
  28214. }
  28215. return null;
  28216. };
  28217. /**
  28218. * Gets a list of transform nodes using their id
  28219. * @param id defines the id to search for
  28220. * @returns a list of transform nodes
  28221. */
  28222. Scene.prototype.getTransformNodesByID = function (id) {
  28223. return this.transformNodes.filter(function (m) {
  28224. return m.id === id;
  28225. });
  28226. };
  28227. /**
  28228. * Gets a mesh with its auto-generated unique id
  28229. * @param uniqueId defines the unique id to search for
  28230. * @return the found mesh or null if not found at all.
  28231. */
  28232. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  28233. for (var index = 0; index < this.meshes.length; index++) {
  28234. if (this.meshes[index].uniqueId === uniqueId) {
  28235. return this.meshes[index];
  28236. }
  28237. }
  28238. return null;
  28239. };
  28240. /**
  28241. * Gets a the last added mesh using a given id
  28242. * @param id defines the id to search for
  28243. * @return the found mesh or null if not found at all.
  28244. */
  28245. Scene.prototype.getLastMeshByID = function (id) {
  28246. for (var index = this.meshes.length - 1; index >= 0; index--) {
  28247. if (this.meshes[index].id === id) {
  28248. return this.meshes[index];
  28249. }
  28250. }
  28251. return null;
  28252. };
  28253. /**
  28254. * Gets a the last added node (Mesh, Camera, Light) using a given id
  28255. * @param id defines the id to search for
  28256. * @return the found node or null if not found at all
  28257. */
  28258. Scene.prototype.getLastEntryByID = function (id) {
  28259. var index;
  28260. for (index = this.meshes.length - 1; index >= 0; index--) {
  28261. if (this.meshes[index].id === id) {
  28262. return this.meshes[index];
  28263. }
  28264. }
  28265. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  28266. if (this.transformNodes[index].id === id) {
  28267. return this.transformNodes[index];
  28268. }
  28269. }
  28270. for (index = this.cameras.length - 1; index >= 0; index--) {
  28271. if (this.cameras[index].id === id) {
  28272. return this.cameras[index];
  28273. }
  28274. }
  28275. for (index = this.lights.length - 1; index >= 0; index--) {
  28276. if (this.lights[index].id === id) {
  28277. return this.lights[index];
  28278. }
  28279. }
  28280. return null;
  28281. };
  28282. /**
  28283. * Gets a node (Mesh, Camera, Light) using a given id
  28284. * @param id defines the id to search for
  28285. * @return the found node or null if not found at all
  28286. */
  28287. Scene.prototype.getNodeByID = function (id) {
  28288. var mesh = this.getMeshByID(id);
  28289. if (mesh) {
  28290. return mesh;
  28291. }
  28292. var light = this.getLightByID(id);
  28293. if (light) {
  28294. return light;
  28295. }
  28296. var camera = this.getCameraByID(id);
  28297. if (camera) {
  28298. return camera;
  28299. }
  28300. var bone = this.getBoneByID(id);
  28301. return bone;
  28302. };
  28303. /**
  28304. * Gets a node (Mesh, Camera, Light) using a given name
  28305. * @param name defines the name to search for
  28306. * @return the found node or null if not found at all.
  28307. */
  28308. Scene.prototype.getNodeByName = function (name) {
  28309. var mesh = this.getMeshByName(name);
  28310. if (mesh) {
  28311. return mesh;
  28312. }
  28313. var light = this.getLightByName(name);
  28314. if (light) {
  28315. return light;
  28316. }
  28317. var camera = this.getCameraByName(name);
  28318. if (camera) {
  28319. return camera;
  28320. }
  28321. var bone = this.getBoneByName(name);
  28322. return bone;
  28323. };
  28324. /**
  28325. * Gets a mesh using a given name
  28326. * @param name defines the name to search for
  28327. * @return the found mesh or null if not found at all.
  28328. */
  28329. Scene.prototype.getMeshByName = function (name) {
  28330. for (var index = 0; index < this.meshes.length; index++) {
  28331. if (this.meshes[index].name === name) {
  28332. return this.meshes[index];
  28333. }
  28334. }
  28335. return null;
  28336. };
  28337. /**
  28338. * Gets a transform node using a given name
  28339. * @param name defines the name to search for
  28340. * @return the found transform node or null if not found at all.
  28341. */
  28342. Scene.prototype.getTransformNodeByName = function (name) {
  28343. for (var index = 0; index < this.transformNodes.length; index++) {
  28344. if (this.transformNodes[index].name === name) {
  28345. return this.transformNodes[index];
  28346. }
  28347. }
  28348. return null;
  28349. };
  28350. /**
  28351. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  28352. * @param id defines the id to search for
  28353. * @return the found skeleton or null if not found at all.
  28354. */
  28355. Scene.prototype.getLastSkeletonByID = function (id) {
  28356. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  28357. if (this.skeletons[index].id === id) {
  28358. return this.skeletons[index];
  28359. }
  28360. }
  28361. return null;
  28362. };
  28363. /**
  28364. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  28365. * @param id defines the id to search for
  28366. * @return the found skeleton or null if not found at all.
  28367. */
  28368. Scene.prototype.getSkeletonById = function (id) {
  28369. for (var index = 0; index < this.skeletons.length; index++) {
  28370. if (this.skeletons[index].id === id) {
  28371. return this.skeletons[index];
  28372. }
  28373. }
  28374. return null;
  28375. };
  28376. /**
  28377. * Gets a skeleton using a given name
  28378. * @param name defines the name to search for
  28379. * @return the found skeleton or null if not found at all.
  28380. */
  28381. Scene.prototype.getSkeletonByName = function (name) {
  28382. for (var index = 0; index < this.skeletons.length; index++) {
  28383. if (this.skeletons[index].name === name) {
  28384. return this.skeletons[index];
  28385. }
  28386. }
  28387. return null;
  28388. };
  28389. /**
  28390. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  28391. * @param id defines the id to search for
  28392. * @return the found morph target manager or null if not found at all.
  28393. */
  28394. Scene.prototype.getMorphTargetManagerById = function (id) {
  28395. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  28396. if (this.morphTargetManagers[index].uniqueId === id) {
  28397. return this.morphTargetManagers[index];
  28398. }
  28399. }
  28400. return null;
  28401. };
  28402. /**
  28403. * Gets a boolean indicating if the given mesh is active
  28404. * @param mesh defines the mesh to look for
  28405. * @returns true if the mesh is in the active list
  28406. */
  28407. Scene.prototype.isActiveMesh = function (mesh) {
  28408. return (this._activeMeshes.indexOf(mesh) !== -1);
  28409. };
  28410. Object.defineProperty(Scene.prototype, "uid", {
  28411. /**
  28412. * Return a unique id as a string which can serve as an identifier for the scene
  28413. */
  28414. get: function () {
  28415. if (!this._uid) {
  28416. this._uid = BABYLON.Tools.RandomId();
  28417. }
  28418. return this._uid;
  28419. },
  28420. enumerable: true,
  28421. configurable: true
  28422. });
  28423. /**
  28424. * Add an externaly attached data from its key.
  28425. * This method call will fail and return false, if such key already exists.
  28426. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  28427. * @param key the unique key that identifies the data
  28428. * @param data the data object to associate to the key for this Engine instance
  28429. * @return true if no such key were already present and the data was added successfully, false otherwise
  28430. */
  28431. Scene.prototype.addExternalData = function (key, data) {
  28432. if (!this._externalData) {
  28433. this._externalData = new BABYLON.StringDictionary();
  28434. }
  28435. return this._externalData.add(key, data);
  28436. };
  28437. /**
  28438. * Get an externaly attached data from its key
  28439. * @param key the unique key that identifies the data
  28440. * @return the associated data, if present (can be null), or undefined if not present
  28441. */
  28442. Scene.prototype.getExternalData = function (key) {
  28443. if (!this._externalData) {
  28444. return null;
  28445. }
  28446. return this._externalData.get(key);
  28447. };
  28448. /**
  28449. * Get an externaly attached data from its key, create it using a factory if it's not already present
  28450. * @param key the unique key that identifies the data
  28451. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  28452. * @return the associated data, can be null if the factory returned null.
  28453. */
  28454. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  28455. if (!this._externalData) {
  28456. this._externalData = new BABYLON.StringDictionary();
  28457. }
  28458. return this._externalData.getOrAddWithFactory(key, factory);
  28459. };
  28460. /**
  28461. * Remove an externaly attached data from the Engine instance
  28462. * @param key the unique key that identifies the data
  28463. * @return true if the data was successfully removed, false if it doesn't exist
  28464. */
  28465. Scene.prototype.removeExternalData = function (key) {
  28466. return this._externalData.remove(key);
  28467. };
  28468. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  28469. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  28470. for (var _i = 0, _a = this._evaluateSubMeshStage; _i < _a.length; _i++) {
  28471. var step = _a[_i];
  28472. step.action(mesh, subMesh);
  28473. }
  28474. var material = subMesh.getMaterial();
  28475. if (material !== null && material !== undefined) {
  28476. // Render targets
  28477. if (material.hasRenderTargetTextures && material.getRenderTargetTextures !== undefined) {
  28478. if (this._processedMaterials.indexOf(material) === -1) {
  28479. this._processedMaterials.push(material);
  28480. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  28481. }
  28482. }
  28483. // Dispatch
  28484. this._activeIndices.addCount(subMesh.indexCount, false);
  28485. this._renderingManager.dispatch(subMesh, mesh, material);
  28486. }
  28487. }
  28488. };
  28489. /**
  28490. * Clear the processed materials smart array preventing retention point in material dispose.
  28491. */
  28492. Scene.prototype.freeProcessedMaterials = function () {
  28493. this._processedMaterials.dispose();
  28494. };
  28495. /**
  28496. * Clear the active meshes smart array preventing retention point in mesh dispose.
  28497. */
  28498. Scene.prototype.freeActiveMeshes = function () {
  28499. this._activeMeshes.dispose();
  28500. if (this.activeCamera && this.activeCamera._activeMeshes) {
  28501. this.activeCamera._activeMeshes.dispose();
  28502. }
  28503. if (this.activeCameras) {
  28504. for (var i = 0; i < this.activeCameras.length; i++) {
  28505. var activeCamera = this.activeCameras[i];
  28506. if (activeCamera && activeCamera._activeMeshes) {
  28507. activeCamera._activeMeshes.dispose();
  28508. }
  28509. }
  28510. }
  28511. };
  28512. /**
  28513. * Clear the info related to rendering groups preventing retention points during dispose.
  28514. */
  28515. Scene.prototype.freeRenderingGroups = function () {
  28516. if (this._renderingManager) {
  28517. this._renderingManager.freeRenderingGroups();
  28518. }
  28519. if (this.textures) {
  28520. for (var i = 0; i < this.textures.length; i++) {
  28521. var texture = this.textures[i];
  28522. if (texture && texture.renderList) {
  28523. texture.freeRenderingGroups();
  28524. }
  28525. }
  28526. }
  28527. };
  28528. /** @hidden */
  28529. Scene.prototype._isInIntermediateRendering = function () {
  28530. return this._intermediateRendering;
  28531. };
  28532. /**
  28533. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  28534. * @returns the current scene
  28535. */
  28536. Scene.prototype.freezeActiveMeshes = function () {
  28537. if (!this.activeCamera) {
  28538. return this;
  28539. }
  28540. if (!this._frustumPlanes) {
  28541. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28542. }
  28543. this._evaluateActiveMeshes();
  28544. this._activeMeshesFrozen = true;
  28545. return this;
  28546. };
  28547. /**
  28548. * Use this function to restart evaluating active meshes on every frame
  28549. * @returns the current scene
  28550. */
  28551. Scene.prototype.unfreezeActiveMeshes = function () {
  28552. this._activeMeshesFrozen = false;
  28553. return this;
  28554. };
  28555. Scene.prototype._evaluateActiveMeshes = function () {
  28556. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  28557. return;
  28558. }
  28559. if (!this.activeCamera) {
  28560. return;
  28561. }
  28562. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  28563. this.activeCamera._activeMeshes.reset();
  28564. this._activeMeshes.reset();
  28565. this._renderingManager.reset();
  28566. this._processedMaterials.reset();
  28567. this._activeParticleSystems.reset();
  28568. this._activeSkeletons.reset();
  28569. this._softwareSkinnedMeshes.reset();
  28570. for (var _i = 0, _a = this._beforeEvaluateActiveMeshStage; _i < _a.length; _i++) {
  28571. var step = _a[_i];
  28572. step.action();
  28573. }
  28574. // Determine mesh candidates
  28575. var meshes = this.getActiveMeshCandidates();
  28576. // Check each mesh
  28577. var len = meshes.length;
  28578. for (var i = 0; i < len; i++) {
  28579. var mesh = meshes.data[i];
  28580. if (mesh.isBlocked) {
  28581. continue;
  28582. }
  28583. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  28584. if (!mesh.isReady() || !mesh.isEnabled()) {
  28585. continue;
  28586. }
  28587. mesh.computeWorldMatrix();
  28588. // Intersections
  28589. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers2(BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger)) {
  28590. this._meshesForIntersections.pushNoDuplicate(mesh);
  28591. }
  28592. // Switch to current LOD
  28593. var meshLOD = mesh.getLOD(this.activeCamera);
  28594. if (meshLOD === undefined || meshLOD === null) {
  28595. continue;
  28596. }
  28597. mesh._preActivate();
  28598. if (mesh.isVisible && mesh.visibility > 0 && (mesh.alwaysSelectAsActiveMesh || ((mesh.layerMask & this.activeCamera.layerMask) !== 0 && mesh.isInFrustum(this._frustumPlanes)))) {
  28599. this._activeMeshes.push(mesh);
  28600. this.activeCamera._activeMeshes.push(mesh);
  28601. mesh._activate(this._renderId);
  28602. if (meshLOD !== mesh) {
  28603. meshLOD._activate(this._renderId);
  28604. }
  28605. this._activeMesh(mesh, meshLOD);
  28606. }
  28607. }
  28608. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  28609. // Particle systems
  28610. if (this.particlesEnabled) {
  28611. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  28612. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  28613. var particleSystem = this.particleSystems[particleIndex];
  28614. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  28615. continue;
  28616. }
  28617. var emitter = particleSystem.emitter;
  28618. if (!emitter.position || emitter.isEnabled()) {
  28619. this._activeParticleSystems.push(particleSystem);
  28620. particleSystem.animate();
  28621. this._renderingManager.dispatchParticles(particleSystem);
  28622. }
  28623. }
  28624. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  28625. }
  28626. };
  28627. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  28628. if (this._skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  28629. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  28630. mesh.skeleton.prepare();
  28631. }
  28632. if (!mesh.computeBonesUsingShaders) {
  28633. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  28634. }
  28635. }
  28636. for (var _i = 0, _a = this._activeMeshStage; _i < _a.length; _i++) {
  28637. var step = _a[_i];
  28638. step.action(sourceMesh, mesh);
  28639. }
  28640. if (mesh !== undefined && mesh !== null
  28641. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  28642. var subMeshes = this.getActiveSubMeshCandidates(mesh);
  28643. var len = subMeshes.length;
  28644. for (var i = 0; i < len; i++) {
  28645. var subMesh = subMeshes.data[i];
  28646. this._evaluateSubMesh(subMesh, mesh);
  28647. }
  28648. }
  28649. };
  28650. /**
  28651. * Update the transform matrix to update from the current active camera
  28652. * @param force defines a boolean used to force the update even if cache is up to date
  28653. */
  28654. Scene.prototype.updateTransformMatrix = function (force) {
  28655. if (!this.activeCamera) {
  28656. return;
  28657. }
  28658. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  28659. };
  28660. /**
  28661. * 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)
  28662. * @param alternateCamera defines the camera to use
  28663. */
  28664. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  28665. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  28666. };
  28667. Scene.prototype._renderForCamera = function (camera, rigParent) {
  28668. if (camera && camera._skipRendering) {
  28669. return;
  28670. }
  28671. var engine = this._engine;
  28672. this.activeCamera = camera;
  28673. if (!this.activeCamera)
  28674. throw new Error("Active camera not set");
  28675. // Viewport
  28676. engine.setViewport(this.activeCamera.viewport);
  28677. // Camera
  28678. this.resetCachedMaterial();
  28679. this._renderId++;
  28680. this.updateTransformMatrix();
  28681. if (camera._alternateCamera) {
  28682. this.updateAlternateTransformMatrix(camera._alternateCamera);
  28683. this._alternateRendering = true;
  28684. }
  28685. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  28686. // Meshes
  28687. this._evaluateActiveMeshes();
  28688. // Software skinning
  28689. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  28690. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  28691. mesh.applySkeleton(mesh.skeleton);
  28692. }
  28693. // Render targets
  28694. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28695. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  28696. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  28697. }
  28698. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  28699. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  28700. }
  28701. // Collects render targets from external components.
  28702. for (var _i = 0, _a = this._gatherActiveCameraRenderTargetsStage; _i < _a.length; _i++) {
  28703. var step = _a[_i];
  28704. step.action(this._renderTargets);
  28705. }
  28706. if (this.renderTargetsEnabled) {
  28707. this._intermediateRendering = true;
  28708. if (this._renderTargets.length > 0) {
  28709. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28710. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  28711. var renderTarget = this._renderTargets.data[renderIndex];
  28712. if (renderTarget._shouldRender()) {
  28713. this._renderId++;
  28714. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  28715. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  28716. }
  28717. }
  28718. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  28719. this._renderId++;
  28720. }
  28721. for (var _b = 0, _c = this._cameraDrawRenderTargetStage; _b < _c.length; _b++) {
  28722. var step = _c[_b];
  28723. step.action(this.activeCamera);
  28724. }
  28725. this._intermediateRendering = false;
  28726. engine.restoreDefaultFramebuffer(); // Restore back buffer if needed
  28727. }
  28728. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28729. // Prepare Frame
  28730. if (this.postProcessManager) {
  28731. this.postProcessManager._prepareFrame();
  28732. }
  28733. // Before Camera Draw
  28734. for (var _d = 0, _e = this._beforeCameraDrawStage; _d < _e.length; _d++) {
  28735. var step = _e[_d];
  28736. step.action(this.activeCamera);
  28737. }
  28738. // Render
  28739. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  28740. this._renderingManager.render(null, null, true, true);
  28741. this.onAfterDrawPhaseObservable.notifyObservers(this);
  28742. // After Camera Draw
  28743. for (var _f = 0, _g = this._afterCameraDrawStage; _f < _g.length; _f++) {
  28744. var step = _g[_f];
  28745. step.action(this.activeCamera);
  28746. }
  28747. // Finalize frame
  28748. if (this.postProcessManager) {
  28749. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  28750. }
  28751. // Reset some special arrays
  28752. this._renderTargets.reset();
  28753. this._alternateRendering = false;
  28754. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  28755. };
  28756. Scene.prototype._processSubCameras = function (camera) {
  28757. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  28758. this._renderForCamera(camera);
  28759. return;
  28760. }
  28761. // rig cameras
  28762. for (var index = 0; index < camera._rigCameras.length; index++) {
  28763. this._renderForCamera(camera._rigCameras[index], camera);
  28764. }
  28765. this.activeCamera = camera;
  28766. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  28767. };
  28768. Scene.prototype._checkIntersections = function () {
  28769. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  28770. var sourceMesh = this._meshesForIntersections.data[index];
  28771. if (!sourceMesh.actionManager) {
  28772. continue;
  28773. }
  28774. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  28775. var action = sourceMesh.actionManager.actions[actionIndex];
  28776. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28777. var parameters = action.getTriggerParameter();
  28778. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  28779. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  28780. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  28781. if (areIntersecting && currentIntersectionInProgress === -1) {
  28782. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  28783. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28784. sourceMesh._intersectionsInProgress.push(otherMesh);
  28785. }
  28786. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28787. sourceMesh._intersectionsInProgress.push(otherMesh);
  28788. }
  28789. }
  28790. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28791. //They intersected, and now they don't.
  28792. //is this trigger an exit trigger? execute an event.
  28793. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28794. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28795. }
  28796. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28797. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28798. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28799. return otherMesh === parameterMesh;
  28800. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28801. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28802. }
  28803. }
  28804. }
  28805. }
  28806. }
  28807. };
  28808. /** @hidden */
  28809. Scene.prototype._advancePhysicsEngineStep = function (step) {
  28810. // Do nothing. Code will be replaced if physics engine component is referenced
  28811. };
  28812. /**
  28813. * Render the scene
  28814. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28815. */
  28816. Scene.prototype.render = function (updateCameras) {
  28817. if (updateCameras === void 0) { updateCameras = true; }
  28818. if (this.isDisposed) {
  28819. return;
  28820. }
  28821. this._frameId++;
  28822. // Register components that have been associated lately to the scene.
  28823. this._registerTransientComponents();
  28824. this._activeParticles.fetchNewFrame();
  28825. this._totalVertices.fetchNewFrame();
  28826. this._activeIndices.fetchNewFrame();
  28827. this._activeBones.fetchNewFrame();
  28828. this._meshesForIntersections.reset();
  28829. this.resetCachedMaterial();
  28830. this.onBeforeAnimationsObservable.notifyObservers(this);
  28831. // Actions
  28832. if (this.actionManager) {
  28833. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28834. }
  28835. if (this._engine.isDeterministicLockStep()) {
  28836. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28837. var defaultFPS = (60.0 / 1000.0);
  28838. var defaultFrameTime = this.getDeterministicFrameTime();
  28839. var stepsTaken = 0;
  28840. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28841. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28842. internalSteps = Math.min(internalSteps, maxSubSteps);
  28843. do {
  28844. this.onBeforeStepObservable.notifyObservers(this);
  28845. // Animations
  28846. this._animationRatio = defaultFrameTime * defaultFPS;
  28847. this._animate();
  28848. this.onAfterAnimationsObservable.notifyObservers(this);
  28849. // Physics
  28850. this._advancePhysicsEngineStep(defaultFrameTime);
  28851. this.onAfterStepObservable.notifyObservers(this);
  28852. this._currentStepId++;
  28853. stepsTaken++;
  28854. deltaTime -= defaultFrameTime;
  28855. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28856. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28857. }
  28858. else {
  28859. // Animations
  28860. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28861. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28862. this._animate();
  28863. this.onAfterAnimationsObservable.notifyObservers(this);
  28864. // Physics
  28865. this._advancePhysicsEngineStep(deltaTime);
  28866. }
  28867. // Before camera update steps
  28868. for (var _i = 0, _a = this._beforeCameraUpdateStage; _i < _a.length; _i++) {
  28869. var step = _a[_i];
  28870. step.action();
  28871. }
  28872. // Update Cameras
  28873. if (updateCameras) {
  28874. if (this.activeCameras.length > 0) {
  28875. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28876. var camera = this.activeCameras[cameraIndex];
  28877. camera.update();
  28878. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28879. // rig cameras
  28880. for (var index = 0; index < camera._rigCameras.length; index++) {
  28881. camera._rigCameras[index].update();
  28882. }
  28883. }
  28884. }
  28885. }
  28886. else if (this.activeCamera) {
  28887. this.activeCamera.update();
  28888. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28889. // rig cameras
  28890. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28891. this.activeCamera._rigCameras[index].update();
  28892. }
  28893. }
  28894. }
  28895. }
  28896. // Before render
  28897. this.onBeforeRenderObservable.notifyObservers(this);
  28898. // Customs render targets
  28899. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28900. var engine = this.getEngine();
  28901. var currentActiveCamera = this.activeCamera;
  28902. if (this.renderTargetsEnabled) {
  28903. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28904. this._intermediateRendering = true;
  28905. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28906. var renderTarget = this.customRenderTargets[customIndex];
  28907. if (renderTarget._shouldRender()) {
  28908. this._renderId++;
  28909. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28910. if (!this.activeCamera)
  28911. throw new Error("Active camera not set");
  28912. // Viewport
  28913. engine.setViewport(this.activeCamera.viewport);
  28914. // Camera
  28915. this.updateTransformMatrix();
  28916. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28917. }
  28918. }
  28919. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28920. this._intermediateRendering = false;
  28921. this._renderId++;
  28922. }
  28923. // Restore back buffer
  28924. if (this.customRenderTargets.length > 0) {
  28925. engine.restoreDefaultFramebuffer();
  28926. }
  28927. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28928. this.activeCamera = currentActiveCamera;
  28929. for (var _b = 0, _c = this._beforeClearStage; _b < _c.length; _b++) {
  28930. var step = _c[_b];
  28931. step.action();
  28932. }
  28933. // Clear
  28934. if (this.autoClearDepthAndStencil || this.autoClear) {
  28935. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28936. }
  28937. // Collects render targets from external components.
  28938. for (var _d = 0, _e = this._gatherRenderTargetsStage; _d < _e.length; _d++) {
  28939. var step = _e[_d];
  28940. step.action(this._renderTargets);
  28941. }
  28942. // Multi-cameras?
  28943. if (this.activeCameras.length > 0) {
  28944. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28945. if (cameraIndex > 0) {
  28946. this._engine.clear(null, false, true, true);
  28947. }
  28948. this._processSubCameras(this.activeCameras[cameraIndex]);
  28949. }
  28950. }
  28951. else {
  28952. if (!this.activeCamera) {
  28953. throw new Error("No camera defined");
  28954. }
  28955. this._processSubCameras(this.activeCamera);
  28956. }
  28957. // Intersection checks
  28958. this._checkIntersections();
  28959. // Executes the after render stage actions.
  28960. for (var _f = 0, _g = this._afterRenderStage; _f < _g.length; _f++) {
  28961. var step = _g[_f];
  28962. step.action();
  28963. }
  28964. // After render
  28965. if (this.afterRender) {
  28966. this.afterRender();
  28967. }
  28968. this.onAfterRenderObservable.notifyObservers(this);
  28969. // Cleaning
  28970. if (this._toBeDisposed.length) {
  28971. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28972. var data = this._toBeDisposed[index];
  28973. if (data) {
  28974. data.dispose();
  28975. }
  28976. }
  28977. this._toBeDisposed = [];
  28978. }
  28979. if (this.dumpNextRenderTargets) {
  28980. this.dumpNextRenderTargets = false;
  28981. }
  28982. this._activeBones.addCount(0, true);
  28983. this._activeIndices.addCount(0, true);
  28984. this._activeParticles.addCount(0, true);
  28985. };
  28986. /**
  28987. * Freeze all materials
  28988. * A frozen material will not be updatable but should be faster to render
  28989. */
  28990. Scene.prototype.freezeMaterials = function () {
  28991. for (var i = 0; i < this.materials.length; i++) {
  28992. this.materials[i].freeze();
  28993. }
  28994. };
  28995. /**
  28996. * Unfreeze all materials
  28997. * A frozen material will not be updatable but should be faster to render
  28998. */
  28999. Scene.prototype.unfreezeMaterials = function () {
  29000. for (var i = 0; i < this.materials.length; i++) {
  29001. this.materials[i].unfreeze();
  29002. }
  29003. };
  29004. /**
  29005. * Releases all held ressources
  29006. */
  29007. Scene.prototype.dispose = function () {
  29008. this.beforeRender = null;
  29009. this.afterRender = null;
  29010. this.skeletons = [];
  29011. this.morphTargetManagers = [];
  29012. this._transientComponents = [];
  29013. this._isReadyForMeshStage.clear();
  29014. this._beforeEvaluateActiveMeshStage.clear();
  29015. this._evaluateSubMeshStage.clear();
  29016. this._activeMeshStage.clear();
  29017. this._cameraDrawRenderTargetStage.clear();
  29018. this._beforeCameraDrawStage.clear();
  29019. this._beforeRenderingGroupDrawStage.clear();
  29020. this._beforeRenderingMeshStage.clear();
  29021. this._afterRenderingMeshStage.clear();
  29022. this._afterRenderingGroupDrawStage.clear();
  29023. this._afterCameraDrawStage.clear();
  29024. this._afterRenderStage.clear();
  29025. this._beforeCameraUpdateStage.clear();
  29026. this._beforeClearStage.clear();
  29027. this._gatherRenderTargetsStage.clear();
  29028. this._gatherActiveCameraRenderTargetsStage.clear();
  29029. this._pointerMoveStage.clear();
  29030. this._pointerDownStage.clear();
  29031. this._pointerUpStage.clear();
  29032. for (var _i = 0, _a = this._components; _i < _a.length; _i++) {
  29033. var component = _a[_i];
  29034. component.dispose();
  29035. }
  29036. this.importedMeshesFiles = new Array();
  29037. this.stopAllAnimations();
  29038. this.resetCachedMaterial();
  29039. // Smart arrays
  29040. if (this.activeCamera) {
  29041. this.activeCamera._activeMeshes.dispose();
  29042. this.activeCamera = null;
  29043. }
  29044. this._activeMeshes.dispose();
  29045. this._renderingManager.dispose();
  29046. this._processedMaterials.dispose();
  29047. this._activeParticleSystems.dispose();
  29048. this._activeSkeletons.dispose();
  29049. this._softwareSkinnedMeshes.dispose();
  29050. this._renderTargets.dispose();
  29051. this._registeredForLateAnimationBindings.dispose();
  29052. this._meshesForIntersections.dispose();
  29053. this._toBeDisposed = [];
  29054. // Abort active requests
  29055. for (var _b = 0, _c = this._activeRequests; _b < _c.length; _b++) {
  29056. var request = _c[_b];
  29057. request.abort();
  29058. }
  29059. // Events
  29060. this.onDisposeObservable.notifyObservers(this);
  29061. this.onDisposeObservable.clear();
  29062. this.onBeforeRenderObservable.clear();
  29063. this.onAfterRenderObservable.clear();
  29064. this.onBeforeRenderTargetsRenderObservable.clear();
  29065. this.onAfterRenderTargetsRenderObservable.clear();
  29066. this.onAfterStepObservable.clear();
  29067. this.onBeforeStepObservable.clear();
  29068. this.onBeforeActiveMeshesEvaluationObservable.clear();
  29069. this.onAfterActiveMeshesEvaluationObservable.clear();
  29070. this.onBeforeParticlesRenderingObservable.clear();
  29071. this.onAfterParticlesRenderingObservable.clear();
  29072. this.onBeforeDrawPhaseObservable.clear();
  29073. this.onAfterDrawPhaseObservable.clear();
  29074. this.onBeforeAnimationsObservable.clear();
  29075. this.onAfterAnimationsObservable.clear();
  29076. this.onDataLoadedObservable.clear();
  29077. this.onBeforeRenderingGroupObservable.clear();
  29078. this.onAfterRenderingGroupObservable.clear();
  29079. this.onMeshImportedObservable.clear();
  29080. this.onBeforeCameraRenderObservable.clear();
  29081. this.onAfterCameraRenderObservable.clear();
  29082. this.onReadyObservable.clear();
  29083. this.onNewCameraAddedObservable.clear();
  29084. this.onCameraRemovedObservable.clear();
  29085. this.onNewLightAddedObservable.clear();
  29086. this.onLightRemovedObservable.clear();
  29087. this.onNewGeometryAddedObservable.clear();
  29088. this.onGeometryRemovedObservable.clear();
  29089. this.onNewTransformNodeAddedObservable.clear();
  29090. this.onTransformNodeRemovedObservable.clear();
  29091. this.onNewMeshAddedObservable.clear();
  29092. this.onMeshRemovedObservable.clear();
  29093. this.onNewMaterialAddedObservable.clear();
  29094. this.onMaterialRemovedObservable.clear();
  29095. this.onNewTextureAddedObservable.clear();
  29096. this.onTextureRemovedObservable.clear();
  29097. this.onPrePointerObservable.clear();
  29098. this.onPointerObservable.clear();
  29099. this.onPreKeyboardObservable.clear();
  29100. this.onKeyboardObservable.clear();
  29101. this.detachControl();
  29102. // Detach cameras
  29103. var canvas = this._engine.getRenderingCanvas();
  29104. if (canvas) {
  29105. var index;
  29106. for (index = 0; index < this.cameras.length; index++) {
  29107. this.cameras[index].detachControl(canvas);
  29108. }
  29109. }
  29110. // Release animation groups
  29111. while (this.animationGroups.length) {
  29112. this.animationGroups[0].dispose();
  29113. }
  29114. // Release lights
  29115. while (this.lights.length) {
  29116. this.lights[0].dispose();
  29117. }
  29118. // Release meshes
  29119. while (this.meshes.length) {
  29120. this.meshes[0].dispose(true);
  29121. }
  29122. while (this.transformNodes.length) {
  29123. this.removeTransformNode(this.transformNodes[0]);
  29124. }
  29125. // Release cameras
  29126. while (this.cameras.length) {
  29127. this.cameras[0].dispose();
  29128. }
  29129. // Release materials
  29130. if (this.defaultMaterial) {
  29131. this.defaultMaterial.dispose();
  29132. }
  29133. while (this.multiMaterials.length) {
  29134. this.multiMaterials[0].dispose();
  29135. }
  29136. while (this.materials.length) {
  29137. this.materials[0].dispose();
  29138. }
  29139. // Release particles
  29140. while (this.particleSystems.length) {
  29141. this.particleSystems[0].dispose();
  29142. }
  29143. // Release postProcesses
  29144. while (this.postProcesses.length) {
  29145. this.postProcesses[0].dispose();
  29146. }
  29147. // Release textures
  29148. while (this.textures.length) {
  29149. this.textures[0].dispose();
  29150. }
  29151. // Release UBO
  29152. this._sceneUbo.dispose();
  29153. if (this._alternateSceneUbo) {
  29154. this._alternateSceneUbo.dispose();
  29155. }
  29156. // Post-processes
  29157. this.postProcessManager.dispose();
  29158. // Remove from engine
  29159. index = this._engine.scenes.indexOf(this);
  29160. if (index > -1) {
  29161. this._engine.scenes.splice(index, 1);
  29162. }
  29163. this._engine.wipeCaches(true);
  29164. this._isDisposed = true;
  29165. };
  29166. Object.defineProperty(Scene.prototype, "isDisposed", {
  29167. /**
  29168. * Gets if the scene is already disposed
  29169. */
  29170. get: function () {
  29171. return this._isDisposed;
  29172. },
  29173. enumerable: true,
  29174. configurable: true
  29175. });
  29176. /**
  29177. * Call this function to reduce memory footprint of the scene.
  29178. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  29179. */
  29180. Scene.prototype.clearCachedVertexData = function () {
  29181. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29182. var mesh = this.meshes[meshIndex];
  29183. var geometry = mesh.geometry;
  29184. if (geometry) {
  29185. geometry._indices = [];
  29186. for (var vbName in geometry._vertexBuffers) {
  29187. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  29188. continue;
  29189. }
  29190. geometry._vertexBuffers[vbName]._buffer._data = null;
  29191. }
  29192. }
  29193. }
  29194. };
  29195. /**
  29196. * This function will remove the local cached buffer data from texture.
  29197. * It will save memory but will prevent the texture from being rebuilt
  29198. */
  29199. Scene.prototype.cleanCachedTextureBuffer = function () {
  29200. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29201. var baseTexture = _a[_i];
  29202. var buffer = baseTexture._buffer;
  29203. if (buffer) {
  29204. baseTexture._buffer = null;
  29205. }
  29206. }
  29207. };
  29208. /**
  29209. * Get the world extend vectors with an optional filter
  29210. *
  29211. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  29212. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  29213. */
  29214. Scene.prototype.getWorldExtends = function (filterPredicate) {
  29215. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  29216. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  29217. filterPredicate = filterPredicate || (function () { return true; });
  29218. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  29219. mesh.computeWorldMatrix(true);
  29220. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  29221. return;
  29222. }
  29223. var boundingInfo = mesh.getBoundingInfo();
  29224. var minBox = boundingInfo.boundingBox.minimumWorld;
  29225. var maxBox = boundingInfo.boundingBox.maximumWorld;
  29226. BABYLON.Tools.CheckExtends(minBox, min, max);
  29227. BABYLON.Tools.CheckExtends(maxBox, min, max);
  29228. });
  29229. return {
  29230. min: min,
  29231. max: max
  29232. };
  29233. };
  29234. // Picking
  29235. /**
  29236. * Creates a ray that can be used to pick in the scene
  29237. * @param x defines the x coordinate of the origin (on-screen)
  29238. * @param y defines the y coordinate of the origin (on-screen)
  29239. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29240. * @param camera defines the camera to use for the picking
  29241. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29242. * @returns a Ray
  29243. */
  29244. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  29245. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29246. var result = BABYLON.Ray.Zero();
  29247. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  29248. return result;
  29249. };
  29250. /**
  29251. * Creates a ray that can be used to pick in the scene
  29252. * @param x defines the x coordinate of the origin (on-screen)
  29253. * @param y defines the y coordinate of the origin (on-screen)
  29254. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  29255. * @param result defines the ray where to store the picking ray
  29256. * @param camera defines the camera to use for the picking
  29257. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  29258. * @returns the current scene
  29259. */
  29260. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  29261. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  29262. var engine = this._engine;
  29263. if (!camera) {
  29264. if (!this.activeCamera)
  29265. throw new Error("Active camera not set");
  29266. camera = this.activeCamera;
  29267. }
  29268. var cameraViewport = camera.viewport;
  29269. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29270. // Moving coordinates to local viewport world
  29271. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29272. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29273. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  29274. return this;
  29275. };
  29276. /**
  29277. * Creates a ray that can be used to pick in the scene
  29278. * @param x defines the x coordinate of the origin (on-screen)
  29279. * @param y defines the y coordinate of the origin (on-screen)
  29280. * @param camera defines the camera to use for the picking
  29281. * @returns a Ray
  29282. */
  29283. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  29284. var result = BABYLON.Ray.Zero();
  29285. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  29286. return result;
  29287. };
  29288. /**
  29289. * Creates a ray that can be used to pick in the scene
  29290. * @param x defines the x coordinate of the origin (on-screen)
  29291. * @param y defines the y coordinate of the origin (on-screen)
  29292. * @param result defines the ray where to store the picking ray
  29293. * @param camera defines the camera to use for the picking
  29294. * @returns the current scene
  29295. */
  29296. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  29297. if (!BABYLON.PickingInfo) {
  29298. return this;
  29299. }
  29300. var engine = this._engine;
  29301. if (!camera) {
  29302. if (!this.activeCamera)
  29303. throw new Error("Active camera not set");
  29304. camera = this.activeCamera;
  29305. }
  29306. var cameraViewport = camera.viewport;
  29307. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  29308. var identity = BABYLON.Matrix.Identity();
  29309. // Moving coordinates to local viewport world
  29310. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  29311. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  29312. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  29313. return this;
  29314. };
  29315. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  29316. if (!BABYLON.PickingInfo) {
  29317. return null;
  29318. }
  29319. var pickingInfo = null;
  29320. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29321. var mesh = this.meshes[meshIndex];
  29322. if (predicate) {
  29323. if (!predicate(mesh)) {
  29324. continue;
  29325. }
  29326. }
  29327. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29328. continue;
  29329. }
  29330. var world = mesh.getWorldMatrix();
  29331. var ray = rayFunction(world);
  29332. var result = mesh.intersects(ray, fastCheck);
  29333. if (!result || !result.hit)
  29334. continue;
  29335. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  29336. continue;
  29337. pickingInfo = result;
  29338. if (fastCheck) {
  29339. break;
  29340. }
  29341. }
  29342. return pickingInfo || new BABYLON.PickingInfo();
  29343. };
  29344. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  29345. if (!BABYLON.PickingInfo) {
  29346. return null;
  29347. }
  29348. var pickingInfos = new Array();
  29349. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  29350. var mesh = this.meshes[meshIndex];
  29351. if (predicate) {
  29352. if (!predicate(mesh)) {
  29353. continue;
  29354. }
  29355. }
  29356. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  29357. continue;
  29358. }
  29359. var world = mesh.getWorldMatrix();
  29360. var ray = rayFunction(world);
  29361. var result = mesh.intersects(ray, false);
  29362. if (!result || !result.hit)
  29363. continue;
  29364. pickingInfos.push(result);
  29365. }
  29366. return pickingInfos;
  29367. };
  29368. /** Launch a ray to try to pick a mesh in the scene
  29369. * @param x position on screen
  29370. * @param y position on screen
  29371. * @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
  29372. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  29373. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29374. * @returns a PickingInfo
  29375. */
  29376. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  29377. var _this = this;
  29378. if (!BABYLON.PickingInfo) {
  29379. return null;
  29380. }
  29381. var result = this._internalPick(function (world) {
  29382. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  29383. return _this._tempPickingRay;
  29384. }, predicate, fastCheck);
  29385. if (result) {
  29386. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  29387. }
  29388. return result;
  29389. };
  29390. /** Use the given ray to pick a mesh in the scene
  29391. * @param ray The ray to use to pick meshes
  29392. * @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
  29393. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  29394. * @returns a PickingInfo
  29395. */
  29396. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  29397. var _this = this;
  29398. var result = this._internalPick(function (world) {
  29399. if (!_this._pickWithRayInverseMatrix) {
  29400. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29401. }
  29402. world.invertToRef(_this._pickWithRayInverseMatrix);
  29403. if (!_this._cachedRayForTransform) {
  29404. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29405. }
  29406. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29407. return _this._cachedRayForTransform;
  29408. }, predicate, fastCheck);
  29409. if (result) {
  29410. result.ray = ray;
  29411. }
  29412. return result;
  29413. };
  29414. /**
  29415. * Launch a ray to try to pick a mesh in the scene
  29416. * @param x X position on screen
  29417. * @param y Y position on screen
  29418. * @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
  29419. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  29420. * @returns an array of PickingInfo
  29421. */
  29422. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  29423. var _this = this;
  29424. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  29425. };
  29426. /**
  29427. * Launch a ray to try to pick a mesh in the scene
  29428. * @param ray Ray to use
  29429. * @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
  29430. * @returns an array of PickingInfo
  29431. */
  29432. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  29433. var _this = this;
  29434. return this._internalMultiPick(function (world) {
  29435. if (!_this._pickWithRayInverseMatrix) {
  29436. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  29437. }
  29438. world.invertToRef(_this._pickWithRayInverseMatrix);
  29439. if (!_this._cachedRayForTransform) {
  29440. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  29441. }
  29442. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  29443. return _this._cachedRayForTransform;
  29444. }, predicate);
  29445. };
  29446. /**
  29447. * Force the value of meshUnderPointer
  29448. * @param mesh defines the mesh to use
  29449. */
  29450. Scene.prototype.setPointerOverMesh = function (mesh) {
  29451. if (this._pointerOverMesh === mesh) {
  29452. return;
  29453. }
  29454. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29455. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29456. }
  29457. this._pointerOverMesh = mesh;
  29458. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  29459. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  29460. }
  29461. };
  29462. /**
  29463. * Gets the mesh under the pointer
  29464. * @returns a Mesh or null if no mesh is under the pointer
  29465. */
  29466. Scene.prototype.getPointerOverMesh = function () {
  29467. return this._pointerOverMesh;
  29468. };
  29469. // Misc.
  29470. /** @hidden */
  29471. Scene.prototype._rebuildGeometries = function () {
  29472. for (var _i = 0, _a = this.geometries; _i < _a.length; _i++) {
  29473. var geometry = _a[_i];
  29474. geometry._rebuild();
  29475. }
  29476. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29477. var mesh = _c[_b];
  29478. mesh._rebuild();
  29479. }
  29480. if (this.postProcessManager) {
  29481. this.postProcessManager._rebuild();
  29482. }
  29483. for (var _d = 0, _e = this._components; _d < _e.length; _d++) {
  29484. var component = _e[_d];
  29485. component.rebuild();
  29486. }
  29487. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  29488. var system = _g[_f];
  29489. system.rebuild();
  29490. }
  29491. };
  29492. /** @hidden */
  29493. Scene.prototype._rebuildTextures = function () {
  29494. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29495. var texture = _a[_i];
  29496. texture._rebuild();
  29497. }
  29498. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29499. };
  29500. // Tags
  29501. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29502. if (tagsQuery === undefined) {
  29503. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29504. return list;
  29505. }
  29506. var listByTags = [];
  29507. forEach = forEach || (function (item) { return; });
  29508. for (var i in list) {
  29509. var item = list[i];
  29510. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29511. listByTags.push(item);
  29512. forEach(item);
  29513. }
  29514. }
  29515. return listByTags;
  29516. };
  29517. /**
  29518. * Get a list of meshes by tags
  29519. * @param tagsQuery defines the tags query to use
  29520. * @param forEach defines a predicate used to filter results
  29521. * @returns an array of Mesh
  29522. */
  29523. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29524. return this._getByTags(this.meshes, tagsQuery, forEach);
  29525. };
  29526. /**
  29527. * Get a list of cameras by tags
  29528. * @param tagsQuery defines the tags query to use
  29529. * @param forEach defines a predicate used to filter results
  29530. * @returns an array of Camera
  29531. */
  29532. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29533. return this._getByTags(this.cameras, tagsQuery, forEach);
  29534. };
  29535. /**
  29536. * Get a list of lights by tags
  29537. * @param tagsQuery defines the tags query to use
  29538. * @param forEach defines a predicate used to filter results
  29539. * @returns an array of Light
  29540. */
  29541. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29542. return this._getByTags(this.lights, tagsQuery, forEach);
  29543. };
  29544. /**
  29545. * Get a list of materials by tags
  29546. * @param tagsQuery defines the tags query to use
  29547. * @param forEach defines a predicate used to filter results
  29548. * @returns an array of Material
  29549. */
  29550. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29551. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29552. };
  29553. /**
  29554. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29555. * This allowed control for front to back rendering or reversly depending of the special needs.
  29556. *
  29557. * @param renderingGroupId The rendering group id corresponding to its index
  29558. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29559. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29560. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29561. */
  29562. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29563. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29564. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29565. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29566. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29567. };
  29568. /**
  29569. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29570. *
  29571. * @param renderingGroupId The rendering group id corresponding to its index
  29572. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29573. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29574. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29575. */
  29576. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29577. if (depth === void 0) { depth = true; }
  29578. if (stencil === void 0) { stencil = true; }
  29579. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29580. };
  29581. /**
  29582. * Gets the current auto clear configuration for one rendering group of the rendering
  29583. * manager.
  29584. * @param index the rendering group index to get the information for
  29585. * @returns The auto clear setup for the requested rendering group
  29586. */
  29587. Scene.prototype.getAutoClearDepthStencilSetup = function (index) {
  29588. return this._renderingManager.getAutoClearDepthStencilSetup(index);
  29589. };
  29590. Object.defineProperty(Scene.prototype, "blockMaterialDirtyMechanism", {
  29591. /** Gets or sets a boolean blocking all the calls to markAllMaterialsAsDirty (ie. the materials won't be updated if they are out of sync) */
  29592. get: function () {
  29593. return this._blockMaterialDirtyMechanism;
  29594. },
  29595. set: function (value) {
  29596. if (this._blockMaterialDirtyMechanism === value) {
  29597. return;
  29598. }
  29599. this._blockMaterialDirtyMechanism = value;
  29600. if (!value) { // Do a complete update
  29601. this.markAllMaterialsAsDirty(BABYLON.Material.AllDirtyFlag);
  29602. }
  29603. },
  29604. enumerable: true,
  29605. configurable: true
  29606. });
  29607. /**
  29608. * Will flag all materials as dirty to trigger new shader compilation
  29609. * @param flag defines the flag used to specify which material part must be marked as dirty
  29610. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29611. */
  29612. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29613. if (this._blockMaterialDirtyMechanism) {
  29614. return;
  29615. }
  29616. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29617. var material = _a[_i];
  29618. if (predicate && !predicate(material)) {
  29619. continue;
  29620. }
  29621. material.markAsDirty(flag);
  29622. }
  29623. };
  29624. /** @hidden */
  29625. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29626. var _this = this;
  29627. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29628. this._activeRequests.push(request);
  29629. request.onCompleteObservable.add(function (request) {
  29630. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29631. });
  29632. return request;
  29633. };
  29634. /** @hidden */
  29635. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29636. var _this = this;
  29637. return new Promise(function (resolve, reject) {
  29638. _this._loadFile(url, function (data) {
  29639. resolve(data);
  29640. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29641. reject(exception);
  29642. });
  29643. });
  29644. };
  29645. // Statics
  29646. Scene._uniqueIdCounter = 0;
  29647. /** The fog is deactivated */
  29648. Scene.FOGMODE_NONE = 0;
  29649. /** The fog density is following an exponential function */
  29650. Scene.FOGMODE_EXP = 1;
  29651. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  29652. Scene.FOGMODE_EXP2 = 2;
  29653. /** The fog density is following a linear function. */
  29654. Scene.FOGMODE_LINEAR = 3;
  29655. /**
  29656. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29657. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29658. */
  29659. Scene.MinDeltaTime = 1.0;
  29660. /**
  29661. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29662. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29663. */
  29664. Scene.MaxDeltaTime = 1000.0;
  29665. /** The distance in pixel that you have to move to prevent some events */
  29666. Scene.DragMovementThreshold = 10; // in pixels
  29667. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29668. Scene.LongPressDelay = 500; // in milliseconds
  29669. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29670. Scene.DoubleClickDelay = 300; // in milliseconds
  29671. /** If you need to check double click without raising a single click at first click, enable this flag */
  29672. Scene.ExclusiveDoubleClickMode = false;
  29673. return Scene;
  29674. }(BABYLON.AbstractScene));
  29675. BABYLON.Scene = Scene;
  29676. })(BABYLON || (BABYLON = {}));
  29677. //# sourceMappingURL=babylon.scene.js.map
  29678. var BABYLON;
  29679. (function (BABYLON) {
  29680. /**
  29681. * Set of assets to keep when moving a scene into an asset container.
  29682. */
  29683. var KeepAssets = /** @class */ (function (_super) {
  29684. __extends(KeepAssets, _super);
  29685. function KeepAssets() {
  29686. return _super !== null && _super.apply(this, arguments) || this;
  29687. }
  29688. return KeepAssets;
  29689. }(BABYLON.AbstractScene));
  29690. BABYLON.KeepAssets = KeepAssets;
  29691. /**
  29692. * Container with a set of assets that can be added or removed from a scene.
  29693. */
  29694. var AssetContainer = /** @class */ (function (_super) {
  29695. __extends(AssetContainer, _super);
  29696. /**
  29697. * Instantiates an AssetContainer.
  29698. * @param scene The scene the AssetContainer belongs to.
  29699. */
  29700. function AssetContainer(scene) {
  29701. var _this = _super.call(this) || this;
  29702. _this.scene = scene;
  29703. return _this;
  29704. }
  29705. /**
  29706. * Adds all the assets from the container to the scene.
  29707. */
  29708. AssetContainer.prototype.addAllToScene = function () {
  29709. var _this = this;
  29710. this.cameras.forEach(function (o) {
  29711. _this.scene.addCamera(o);
  29712. });
  29713. this.lights.forEach(function (o) {
  29714. _this.scene.addLight(o);
  29715. });
  29716. this.meshes.forEach(function (o) {
  29717. _this.scene.addMesh(o);
  29718. });
  29719. this.skeletons.forEach(function (o) {
  29720. _this.scene.addSkeleton(o);
  29721. });
  29722. this.animations.forEach(function (o) {
  29723. _this.scene.addAnimation(o);
  29724. });
  29725. this.animationGroups.forEach(function (o) {
  29726. _this.scene.addAnimationGroup(o);
  29727. });
  29728. this.multiMaterials.forEach(function (o) {
  29729. _this.scene.addMultiMaterial(o);
  29730. });
  29731. this.materials.forEach(function (o) {
  29732. _this.scene.addMaterial(o);
  29733. });
  29734. this.morphTargetManagers.forEach(function (o) {
  29735. _this.scene.addMorphTargetManager(o);
  29736. });
  29737. this.geometries.forEach(function (o) {
  29738. _this.scene.addGeometry(o);
  29739. });
  29740. this.transformNodes.forEach(function (o) {
  29741. _this.scene.addTransformNode(o);
  29742. });
  29743. this.actionManagers.forEach(function (o) {
  29744. _this.scene.addActionManager(o);
  29745. });
  29746. this.textures.forEach(function (o) {
  29747. _this.scene.addTexture(o);
  29748. });
  29749. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29750. var component = _a[_i];
  29751. component.addFromContainer(this.scene);
  29752. }
  29753. };
  29754. /**
  29755. * Removes all the assets in the container from the scene
  29756. */
  29757. AssetContainer.prototype.removeAllFromScene = function () {
  29758. var _this = this;
  29759. this.cameras.forEach(function (o) {
  29760. _this.scene.removeCamera(o);
  29761. });
  29762. this.lights.forEach(function (o) {
  29763. _this.scene.removeLight(o);
  29764. });
  29765. this.meshes.forEach(function (o) {
  29766. _this.scene.removeMesh(o);
  29767. });
  29768. this.skeletons.forEach(function (o) {
  29769. _this.scene.removeSkeleton(o);
  29770. });
  29771. this.animations.forEach(function (o) {
  29772. _this.scene.removeAnimation(o);
  29773. });
  29774. this.animationGroups.forEach(function (o) {
  29775. _this.scene.removeAnimationGroup(o);
  29776. });
  29777. this.multiMaterials.forEach(function (o) {
  29778. _this.scene.removeMultiMaterial(o);
  29779. });
  29780. this.materials.forEach(function (o) {
  29781. _this.scene.removeMaterial(o);
  29782. });
  29783. this.morphTargetManagers.forEach(function (o) {
  29784. _this.scene.removeMorphTargetManager(o);
  29785. });
  29786. this.geometries.forEach(function (o) {
  29787. _this.scene.removeGeometry(o);
  29788. });
  29789. this.transformNodes.forEach(function (o) {
  29790. _this.scene.removeTransformNode(o);
  29791. });
  29792. this.actionManagers.forEach(function (o) {
  29793. _this.scene.removeActionManager(o);
  29794. });
  29795. this.textures.forEach(function (o) {
  29796. _this.scene.removeTexture(o);
  29797. });
  29798. for (var _i = 0, _a = this.scene._serializableComponents; _i < _a.length; _i++) {
  29799. var component = _a[_i];
  29800. component.removeFromContainer(this.scene);
  29801. }
  29802. };
  29803. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29804. if (!sourceAssets) {
  29805. return;
  29806. }
  29807. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29808. var asset = sourceAssets_1[_i];
  29809. var move = true;
  29810. if (keepAssets) {
  29811. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29812. var keepAsset = keepAssets_1[_a];
  29813. if (asset === keepAsset) {
  29814. move = false;
  29815. break;
  29816. }
  29817. }
  29818. }
  29819. if (move) {
  29820. targetAssets.push(asset);
  29821. }
  29822. }
  29823. };
  29824. /**
  29825. * Removes all the assets contained in the scene and adds them to the container.
  29826. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29827. */
  29828. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29829. if (keepAssets === undefined) {
  29830. keepAssets = new KeepAssets();
  29831. }
  29832. for (var key in this) {
  29833. if (this.hasOwnProperty(key)) {
  29834. this[key] = this[key] || [];
  29835. this._moveAssets(this.scene[key], this[key], keepAssets[key]);
  29836. }
  29837. }
  29838. this.removeAllFromScene();
  29839. };
  29840. /**
  29841. * 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.
  29842. * @returns the root mesh
  29843. */
  29844. AssetContainer.prototype.createRootMesh = function () {
  29845. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29846. this.meshes.forEach(function (m) {
  29847. if (!m.parent) {
  29848. rootMesh.addChild(m);
  29849. }
  29850. });
  29851. this.meshes.unshift(rootMesh);
  29852. return rootMesh;
  29853. };
  29854. return AssetContainer;
  29855. }(BABYLON.AbstractScene));
  29856. BABYLON.AssetContainer = AssetContainer;
  29857. })(BABYLON || (BABYLON = {}));
  29858. //# sourceMappingURL=babylon.assetContainer.js.map
  29859. var BABYLON;
  29860. (function (BABYLON) {
  29861. /**
  29862. * Class used to store data that will be store in GPU memory
  29863. */
  29864. var Buffer = /** @class */ (function () {
  29865. /**
  29866. * Constructor
  29867. * @param engine the engine
  29868. * @param data the data to use for this buffer
  29869. * @param updatable whether the data is updatable
  29870. * @param stride the stride (optional)
  29871. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29872. * @param instanced whether the buffer is instanced (optional)
  29873. * @param useBytes set to true if the stride in in bytes (optional)
  29874. */
  29875. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29876. if (stride === void 0) { stride = 0; }
  29877. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29878. if (instanced === void 0) { instanced = false; }
  29879. if (useBytes === void 0) { useBytes = false; }
  29880. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29881. this._engine = engine.getScene().getEngine();
  29882. }
  29883. else {
  29884. this._engine = engine;
  29885. }
  29886. this._updatable = updatable;
  29887. this._instanced = instanced;
  29888. this._data = data;
  29889. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29890. if (!postponeInternalCreation) { // by default
  29891. this.create();
  29892. }
  29893. }
  29894. /**
  29895. * Create a new VertexBuffer based on the current buffer
  29896. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29897. * @param offset defines offset in the buffer (0 by default)
  29898. * @param size defines the size in floats of attributes (position is 3 for instance)
  29899. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29900. * @param instanced defines if the vertex buffer contains indexed data
  29901. * @param useBytes defines if the offset and stride are in bytes
  29902. * @returns the new vertex buffer
  29903. */
  29904. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29905. if (useBytes === void 0) { useBytes = false; }
  29906. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29907. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29908. // a lot of these parameters are ignored as they are overriden by the buffer
  29909. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29910. };
  29911. // Properties
  29912. /**
  29913. * Gets a boolean indicating if the Buffer is updatable?
  29914. * @returns true if the buffer is updatable
  29915. */
  29916. Buffer.prototype.isUpdatable = function () {
  29917. return this._updatable;
  29918. };
  29919. /**
  29920. * Gets current buffer's data
  29921. * @returns a DataArray or null
  29922. */
  29923. Buffer.prototype.getData = function () {
  29924. return this._data;
  29925. };
  29926. /**
  29927. * Gets underlying native buffer
  29928. * @returns underlying native buffer
  29929. */
  29930. Buffer.prototype.getBuffer = function () {
  29931. return this._buffer;
  29932. };
  29933. /**
  29934. * Gets the stride in float32 units (i.e. byte stride / 4).
  29935. * May not be an integer if the byte stride is not divisible by 4.
  29936. * DEPRECATED. Use byteStride instead.
  29937. * @returns the stride in float32 units
  29938. */
  29939. Buffer.prototype.getStrideSize = function () {
  29940. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29941. };
  29942. // Methods
  29943. /**
  29944. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  29945. * @param data defines the data to store
  29946. */
  29947. Buffer.prototype.create = function (data) {
  29948. if (data === void 0) { data = null; }
  29949. if (!data && this._buffer) {
  29950. return; // nothing to do
  29951. }
  29952. data = data || this._data;
  29953. if (!data) {
  29954. return;
  29955. }
  29956. if (!this._buffer) { // create buffer
  29957. if (this._updatable) {
  29958. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29959. this._data = data;
  29960. }
  29961. else {
  29962. this._buffer = this._engine.createVertexBuffer(data);
  29963. }
  29964. }
  29965. else if (this._updatable) { // update buffer
  29966. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29967. this._data = data;
  29968. }
  29969. };
  29970. /** @hidden */
  29971. Buffer.prototype._rebuild = function () {
  29972. this._buffer = null;
  29973. this.create(this._data);
  29974. };
  29975. /**
  29976. * Update current buffer data
  29977. * @param data defines the data to store
  29978. */
  29979. Buffer.prototype.update = function (data) {
  29980. this.create(data);
  29981. };
  29982. /**
  29983. * Updates the data directly.
  29984. * @param data the new data
  29985. * @param offset the new offset
  29986. * @param vertexCount the vertex count (optional)
  29987. * @param useBytes set to true if the offset is in bytes
  29988. */
  29989. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29990. if (useBytes === void 0) { useBytes = false; }
  29991. if (!this._buffer) {
  29992. return;
  29993. }
  29994. if (this._updatable) { // update buffer
  29995. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29996. this._data = null;
  29997. }
  29998. };
  29999. /**
  30000. * Release all resources
  30001. */
  30002. Buffer.prototype.dispose = function () {
  30003. if (!this._buffer) {
  30004. return;
  30005. }
  30006. if (this._engine._releaseBuffer(this._buffer)) {
  30007. this._buffer = null;
  30008. }
  30009. };
  30010. return Buffer;
  30011. }());
  30012. BABYLON.Buffer = Buffer;
  30013. })(BABYLON || (BABYLON = {}));
  30014. //# sourceMappingURL=babylon.buffer.js.map
  30015. var BABYLON;
  30016. (function (BABYLON) {
  30017. /**
  30018. * Specialized buffer used to store vertex data
  30019. */
  30020. var VertexBuffer = /** @class */ (function () {
  30021. /**
  30022. * Constructor
  30023. * @param engine the engine
  30024. * @param data the data to use for this vertex buffer
  30025. * @param kind the vertex buffer kind
  30026. * @param updatable whether the data is updatable
  30027. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  30028. * @param stride the stride (optional)
  30029. * @param instanced whether the buffer is instanced (optional)
  30030. * @param offset the offset of the data (optional)
  30031. * @param size the number of components (optional)
  30032. * @param type the type of the component (optional)
  30033. * @param normalized whether the data contains normalized data (optional)
  30034. * @param useBytes set to true if stride and offset are in bytes (optional)
  30035. */
  30036. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  30037. if (normalized === void 0) { normalized = false; }
  30038. if (useBytes === void 0) { useBytes = false; }
  30039. if (data instanceof BABYLON.Buffer) {
  30040. this._buffer = data;
  30041. this._ownsBuffer = false;
  30042. }
  30043. else {
  30044. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  30045. this._ownsBuffer = true;
  30046. }
  30047. this._kind = kind;
  30048. if (type == undefined) {
  30049. var data_1 = this.getData();
  30050. this.type = VertexBuffer.FLOAT;
  30051. if (data_1 instanceof Int8Array)
  30052. this.type = VertexBuffer.BYTE;
  30053. else if (data_1 instanceof Uint8Array)
  30054. this.type = VertexBuffer.UNSIGNED_BYTE;
  30055. else if (data_1 instanceof Int16Array)
  30056. this.type = VertexBuffer.SHORT;
  30057. else if (data_1 instanceof Uint16Array)
  30058. this.type = VertexBuffer.UNSIGNED_SHORT;
  30059. else if (data_1 instanceof Int32Array)
  30060. this.type = VertexBuffer.INT;
  30061. else if (data_1 instanceof Uint32Array)
  30062. this.type = VertexBuffer.UNSIGNED_INT;
  30063. }
  30064. else {
  30065. this.type = type;
  30066. }
  30067. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  30068. if (useBytes) {
  30069. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  30070. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  30071. this.byteOffset = offset || 0;
  30072. }
  30073. else {
  30074. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  30075. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  30076. this.byteOffset = (offset || 0) * typeByteLength;
  30077. }
  30078. this.normalized = normalized;
  30079. this._instanced = instanced !== undefined ? instanced : false;
  30080. this._instanceDivisor = instanced ? 1 : 0;
  30081. }
  30082. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  30083. /**
  30084. * Gets or sets the instance divisor when in instanced mode
  30085. */
  30086. get: function () {
  30087. return this._instanceDivisor;
  30088. },
  30089. set: function (value) {
  30090. this._instanceDivisor = value;
  30091. if (value == 0) {
  30092. this._instanced = false;
  30093. }
  30094. else {
  30095. this._instanced = true;
  30096. }
  30097. },
  30098. enumerable: true,
  30099. configurable: true
  30100. });
  30101. /** @hidden */
  30102. VertexBuffer.prototype._rebuild = function () {
  30103. if (!this._buffer) {
  30104. return;
  30105. }
  30106. this._buffer._rebuild();
  30107. };
  30108. /**
  30109. * Returns the kind of the VertexBuffer (string)
  30110. * @returns a string
  30111. */
  30112. VertexBuffer.prototype.getKind = function () {
  30113. return this._kind;
  30114. };
  30115. // Properties
  30116. /**
  30117. * Gets a boolean indicating if the VertexBuffer is updatable?
  30118. * @returns true if the buffer is updatable
  30119. */
  30120. VertexBuffer.prototype.isUpdatable = function () {
  30121. return this._buffer.isUpdatable();
  30122. };
  30123. /**
  30124. * Gets current buffer's data
  30125. * @returns a DataArray or null
  30126. */
  30127. VertexBuffer.prototype.getData = function () {
  30128. return this._buffer.getData();
  30129. };
  30130. /**
  30131. * Gets underlying native buffer
  30132. * @returns underlying native buffer
  30133. */
  30134. VertexBuffer.prototype.getBuffer = function () {
  30135. return this._buffer.getBuffer();
  30136. };
  30137. /**
  30138. * Gets the stride in float32 units (i.e. byte stride / 4).
  30139. * May not be an integer if the byte stride is not divisible by 4.
  30140. * DEPRECATED. Use byteStride instead.
  30141. * @returns the stride in float32 units
  30142. */
  30143. VertexBuffer.prototype.getStrideSize = function () {
  30144. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  30145. };
  30146. /**
  30147. * Returns the offset as a multiple of the type byte length.
  30148. * DEPRECATED. Use byteOffset instead.
  30149. * @returns the offset in bytes
  30150. */
  30151. VertexBuffer.prototype.getOffset = function () {
  30152. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  30153. };
  30154. /**
  30155. * Returns the number of components per vertex attribute (integer)
  30156. * @returns the size in float
  30157. */
  30158. VertexBuffer.prototype.getSize = function () {
  30159. return this._size;
  30160. };
  30161. /**
  30162. * Gets a boolean indicating is the internal buffer of the VertexBuffer is instanced
  30163. * @returns true if this buffer is instanced
  30164. */
  30165. VertexBuffer.prototype.getIsInstanced = function () {
  30166. return this._instanced;
  30167. };
  30168. /**
  30169. * Returns the instancing divisor, zero for non-instanced (integer).
  30170. * @returns a number
  30171. */
  30172. VertexBuffer.prototype.getInstanceDivisor = function () {
  30173. return this._instanceDivisor;
  30174. };
  30175. // Methods
  30176. /**
  30177. * Store data into the buffer. If the buffer was already used it will be either recreated or updated depending on isUpdatable property
  30178. * @param data defines the data to store
  30179. */
  30180. VertexBuffer.prototype.create = function (data) {
  30181. this._buffer.create(data);
  30182. };
  30183. /**
  30184. * Updates the underlying buffer according to the passed numeric array or Float32Array.
  30185. * This function will create a new buffer if the current one is not updatable
  30186. * @param data defines the data to store
  30187. */
  30188. VertexBuffer.prototype.update = function (data) {
  30189. this._buffer.update(data);
  30190. };
  30191. /**
  30192. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30193. * Returns the directly updated WebGLBuffer.
  30194. * @param data the new data
  30195. * @param offset the new offset
  30196. * @param useBytes set to true if the offset is in bytes
  30197. */
  30198. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30199. if (useBytes === void 0) { useBytes = false; }
  30200. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30201. };
  30202. /**
  30203. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30204. */
  30205. VertexBuffer.prototype.dispose = function () {
  30206. if (this._ownsBuffer) {
  30207. this._buffer.dispose();
  30208. }
  30209. };
  30210. /**
  30211. * Enumerates each value of this vertex buffer as numbers.
  30212. * @param count the number of values to enumerate
  30213. * @param callback the callback function called for each value
  30214. */
  30215. VertexBuffer.prototype.forEach = function (count, callback) {
  30216. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30217. };
  30218. /**
  30219. * Deduces the stride given a kind.
  30220. * @param kind The kind string to deduce
  30221. * @returns The deduced stride
  30222. */
  30223. VertexBuffer.DeduceStride = function (kind) {
  30224. switch (kind) {
  30225. case VertexBuffer.UVKind:
  30226. case VertexBuffer.UV2Kind:
  30227. case VertexBuffer.UV3Kind:
  30228. case VertexBuffer.UV4Kind:
  30229. case VertexBuffer.UV5Kind:
  30230. case VertexBuffer.UV6Kind:
  30231. return 2;
  30232. case VertexBuffer.NormalKind:
  30233. case VertexBuffer.PositionKind:
  30234. return 3;
  30235. case VertexBuffer.ColorKind:
  30236. case VertexBuffer.MatricesIndicesKind:
  30237. case VertexBuffer.MatricesIndicesExtraKind:
  30238. case VertexBuffer.MatricesWeightsKind:
  30239. case VertexBuffer.MatricesWeightsExtraKind:
  30240. case VertexBuffer.TangentKind:
  30241. return 4;
  30242. default:
  30243. throw new Error("Invalid kind '" + kind + "'");
  30244. }
  30245. };
  30246. /**
  30247. * Gets the byte length of the given type.
  30248. * @param type the type
  30249. * @returns the number of bytes
  30250. */
  30251. VertexBuffer.GetTypeByteLength = function (type) {
  30252. switch (type) {
  30253. case VertexBuffer.BYTE:
  30254. case VertexBuffer.UNSIGNED_BYTE:
  30255. return 1;
  30256. case VertexBuffer.SHORT:
  30257. case VertexBuffer.UNSIGNED_SHORT:
  30258. return 2;
  30259. case VertexBuffer.INT:
  30260. case VertexBuffer.FLOAT:
  30261. return 4;
  30262. default:
  30263. throw new Error("Invalid type '" + type + "'");
  30264. }
  30265. };
  30266. /**
  30267. * Enumerates each value of the given parameters as numbers.
  30268. * @param data the data to enumerate
  30269. * @param byteOffset the byte offset of the data
  30270. * @param byteStride the byte stride of the data
  30271. * @param componentCount the number of components per element
  30272. * @param componentType the type of the component
  30273. * @param count the total number of components
  30274. * @param normalized whether the data is normalized
  30275. * @param callback the callback function called for each value
  30276. */
  30277. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30278. if (data instanceof Array) {
  30279. var offset = byteOffset / 4;
  30280. var stride = byteStride / 4;
  30281. for (var index = 0; index < count; index += componentCount) {
  30282. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30283. callback(data[offset + componentIndex], index + componentIndex);
  30284. }
  30285. offset += stride;
  30286. }
  30287. }
  30288. else {
  30289. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30290. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30291. for (var index = 0; index < count; index += componentCount) {
  30292. var componentByteOffset = byteOffset;
  30293. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30294. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30295. callback(value, index + componentIndex);
  30296. componentByteOffset += componentByteLength;
  30297. }
  30298. byteOffset += byteStride;
  30299. }
  30300. }
  30301. };
  30302. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30303. switch (type) {
  30304. case VertexBuffer.BYTE: {
  30305. var value = dataView.getInt8(byteOffset);
  30306. if (normalized) {
  30307. value = Math.max(value / 127, -1);
  30308. }
  30309. return value;
  30310. }
  30311. case VertexBuffer.UNSIGNED_BYTE: {
  30312. var value = dataView.getUint8(byteOffset);
  30313. if (normalized) {
  30314. value = value / 255;
  30315. }
  30316. return value;
  30317. }
  30318. case VertexBuffer.SHORT: {
  30319. var value = dataView.getInt16(byteOffset, true);
  30320. if (normalized) {
  30321. value = Math.max(value / 16383, -1);
  30322. }
  30323. return value;
  30324. }
  30325. case VertexBuffer.UNSIGNED_SHORT: {
  30326. var value = dataView.getUint16(byteOffset, true);
  30327. if (normalized) {
  30328. value = value / 65535;
  30329. }
  30330. return value;
  30331. }
  30332. case VertexBuffer.FLOAT: {
  30333. return dataView.getFloat32(byteOffset, true);
  30334. }
  30335. default: {
  30336. throw new Error("Invalid component type " + type);
  30337. }
  30338. }
  30339. };
  30340. /**
  30341. * The byte type.
  30342. */
  30343. VertexBuffer.BYTE = 5120;
  30344. /**
  30345. * The unsigned byte type.
  30346. */
  30347. VertexBuffer.UNSIGNED_BYTE = 5121;
  30348. /**
  30349. * The short type.
  30350. */
  30351. VertexBuffer.SHORT = 5122;
  30352. /**
  30353. * The unsigned short type.
  30354. */
  30355. VertexBuffer.UNSIGNED_SHORT = 5123;
  30356. /**
  30357. * The integer type.
  30358. */
  30359. VertexBuffer.INT = 5124;
  30360. /**
  30361. * The unsigned integer type.
  30362. */
  30363. VertexBuffer.UNSIGNED_INT = 5125;
  30364. /**
  30365. * The float type.
  30366. */
  30367. VertexBuffer.FLOAT = 5126;
  30368. // Enums
  30369. /**
  30370. * Positions
  30371. */
  30372. VertexBuffer.PositionKind = "position";
  30373. /**
  30374. * Normals
  30375. */
  30376. VertexBuffer.NormalKind = "normal";
  30377. /**
  30378. * Tangents
  30379. */
  30380. VertexBuffer.TangentKind = "tangent";
  30381. /**
  30382. * Texture coordinates
  30383. */
  30384. VertexBuffer.UVKind = "uv";
  30385. /**
  30386. * Texture coordinates 2
  30387. */
  30388. VertexBuffer.UV2Kind = "uv2";
  30389. /**
  30390. * Texture coordinates 3
  30391. */
  30392. VertexBuffer.UV3Kind = "uv3";
  30393. /**
  30394. * Texture coordinates 4
  30395. */
  30396. VertexBuffer.UV4Kind = "uv4";
  30397. /**
  30398. * Texture coordinates 5
  30399. */
  30400. VertexBuffer.UV5Kind = "uv5";
  30401. /**
  30402. * Texture coordinates 6
  30403. */
  30404. VertexBuffer.UV6Kind = "uv6";
  30405. /**
  30406. * Colors
  30407. */
  30408. VertexBuffer.ColorKind = "color";
  30409. /**
  30410. * Matrix indices (for bones)
  30411. */
  30412. VertexBuffer.MatricesIndicesKind = "matricesIndices";
  30413. /**
  30414. * Matrix weights (for bones)
  30415. */
  30416. VertexBuffer.MatricesWeightsKind = "matricesWeights";
  30417. /**
  30418. * Additional matrix indices (for bones)
  30419. */
  30420. VertexBuffer.MatricesIndicesExtraKind = "matricesIndicesExtra";
  30421. /**
  30422. * Additional matrix weights (for bones)
  30423. */
  30424. VertexBuffer.MatricesWeightsExtraKind = "matricesWeightsExtra";
  30425. return VertexBuffer;
  30426. }());
  30427. BABYLON.VertexBuffer = VertexBuffer;
  30428. })(BABYLON || (BABYLON = {}));
  30429. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30430. //# sourceMappingURL=babylon.internalTextureLoader.js.map
  30431. var BABYLON;
  30432. (function (BABYLON) {
  30433. /**
  30434. * Internal class used by the engine to get list of InternalTexture already bound to the GL context
  30435. */
  30436. var DummyInternalTextureTracker = /** @class */ (function () {
  30437. function DummyInternalTextureTracker() {
  30438. /**
  30439. * Gets or set the previous tracker in the list
  30440. */
  30441. this.previous = null;
  30442. /**
  30443. * Gets or set the next tracker in the list
  30444. */
  30445. this.next = null;
  30446. }
  30447. return DummyInternalTextureTracker;
  30448. }());
  30449. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30450. })(BABYLON || (BABYLON = {}));
  30451. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30452. var BABYLON;
  30453. (function (BABYLON) {
  30454. /**
  30455. * Class used to store data associated with WebGL texture data for the engine
  30456. * This class should not be used directly
  30457. */
  30458. var InternalTexture = /** @class */ (function () {
  30459. /**
  30460. * Creates a new InternalTexture
  30461. * @param engine defines the engine to use
  30462. * @param dataSource defines the type of data that will be used
  30463. */
  30464. function InternalTexture(engine, dataSource) {
  30465. /**
  30466. * Observable called when the texture is loaded
  30467. */
  30468. this.onLoadedObservable = new BABYLON.Observable();
  30469. /**
  30470. * Gets or set the previous tracker in the list
  30471. */
  30472. this.previous = null;
  30473. /**
  30474. * Gets or set the next tracker in the list
  30475. */
  30476. this.next = null;
  30477. // Private
  30478. /** @hidden */
  30479. this._initialSlot = -1;
  30480. /** @hidden */
  30481. this._designatedSlot = -1;
  30482. /** @hidden */
  30483. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30484. /** @hidden */
  30485. this._comparisonFunction = 0;
  30486. /** @hidden */
  30487. this._sphericalPolynomial = null;
  30488. /** @hidden */
  30489. this._lodGenerationScale = 0;
  30490. /** @hidden */
  30491. this._lodGenerationOffset = 0;
  30492. /** @hidden */
  30493. this._isRGBD = false;
  30494. /** @hidden */
  30495. this._references = 1;
  30496. this._engine = engine;
  30497. this._dataSource = dataSource;
  30498. this._webGLTexture = engine._createTexture();
  30499. }
  30500. /**
  30501. * Gets the Engine the texture belongs to.
  30502. * @returns The babylon engine
  30503. */
  30504. InternalTexture.prototype.getEngine = function () {
  30505. return this._engine;
  30506. };
  30507. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30508. /**
  30509. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30510. */
  30511. get: function () {
  30512. return this._dataSource;
  30513. },
  30514. enumerable: true,
  30515. configurable: true
  30516. });
  30517. /**
  30518. * Increments the number of references (ie. the number of Texture that point to it)
  30519. */
  30520. InternalTexture.prototype.incrementReferences = function () {
  30521. this._references++;
  30522. };
  30523. /**
  30524. * Change the size of the texture (not the size of the content)
  30525. * @param width defines the new width
  30526. * @param height defines the new height
  30527. * @param depth defines the new depth (1 by default)
  30528. */
  30529. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30530. if (depth === void 0) { depth = 1; }
  30531. this.width = width;
  30532. this.height = height;
  30533. this.depth = depth;
  30534. this.baseWidth = width;
  30535. this.baseHeight = height;
  30536. this.baseDepth = depth;
  30537. this._size = width * height * depth;
  30538. };
  30539. /** @hidden */
  30540. InternalTexture.prototype._rebuild = function () {
  30541. var _this = this;
  30542. var proxy;
  30543. this.isReady = false;
  30544. this._cachedCoordinatesMode = null;
  30545. this._cachedWrapU = null;
  30546. this._cachedWrapV = null;
  30547. this._cachedAnisotropicFilteringLevel = null;
  30548. switch (this._dataSource) {
  30549. case InternalTexture.DATASOURCE_TEMP:
  30550. return;
  30551. case InternalTexture.DATASOURCE_URL:
  30552. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30553. _this.isReady = true;
  30554. }, null, this._buffer, undefined, this.format);
  30555. proxy._swapAndDie(this);
  30556. return;
  30557. case InternalTexture.DATASOURCE_RAW:
  30558. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30559. proxy._swapAndDie(this);
  30560. this.isReady = true;
  30561. return;
  30562. case InternalTexture.DATASOURCE_RAW3D:
  30563. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30564. proxy._swapAndDie(this);
  30565. this.isReady = true;
  30566. return;
  30567. case InternalTexture.DATASOURCE_DYNAMIC:
  30568. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30569. proxy._swapAndDie(this);
  30570. // The engine will make sure to update content so no need to flag it as isReady = true
  30571. return;
  30572. case InternalTexture.DATASOURCE_RENDERTARGET:
  30573. var options = new BABYLON.RenderTargetCreationOptions();
  30574. options.generateDepthBuffer = this._generateDepthBuffer;
  30575. options.generateMipMaps = this.generateMipMaps;
  30576. options.generateStencilBuffer = this._generateStencilBuffer;
  30577. options.samplingMode = this.samplingMode;
  30578. options.type = this.type;
  30579. if (this.isCube) {
  30580. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30581. }
  30582. else {
  30583. var size = {
  30584. width: this.width,
  30585. height: this.height
  30586. };
  30587. proxy = this._engine.createRenderTargetTexture(size, options);
  30588. }
  30589. proxy._swapAndDie(this);
  30590. this.isReady = true;
  30591. return;
  30592. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30593. var depthTextureOptions = {
  30594. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30595. comparisonFunction: this._comparisonFunction,
  30596. generateStencil: this._generateStencilBuffer,
  30597. isCube: this.isCube
  30598. };
  30599. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30600. proxy._swapAndDie(this);
  30601. this.isReady = true;
  30602. return;
  30603. case InternalTexture.DATASOURCE_CUBE:
  30604. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30605. _this.isReady = true;
  30606. }, null, this.format, this._extension);
  30607. proxy._swapAndDie(this);
  30608. return;
  30609. case InternalTexture.DATASOURCE_CUBERAW:
  30610. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30611. proxy._swapAndDie(this);
  30612. this.isReady = true;
  30613. return;
  30614. case InternalTexture.DATASOURCE_CUBERAW_RGBD:
  30615. proxy = this._engine.createRawCubeTexture(null, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30616. BABYLON.RawCubeTexture._UpdateRGBDAsync(proxy, this._bufferViewArrayArray, this._sphericalPolynomial, this._lodGenerationScale, this._lodGenerationOffset).then(function () {
  30617. _this.isReady = true;
  30618. });
  30619. proxy._swapAndDie(this);
  30620. return;
  30621. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30622. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30623. if (proxy) {
  30624. proxy._swapAndDie(_this);
  30625. }
  30626. _this.isReady = true;
  30627. }, null, this.format, this._extension);
  30628. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30629. return;
  30630. }
  30631. };
  30632. /** @hidden */
  30633. InternalTexture.prototype._swapAndDie = function (target) {
  30634. target._webGLTexture = this._webGLTexture;
  30635. if (this._framebuffer) {
  30636. target._framebuffer = this._framebuffer;
  30637. }
  30638. if (this._depthStencilBuffer) {
  30639. target._depthStencilBuffer = this._depthStencilBuffer;
  30640. }
  30641. if (this._lodTextureHigh) {
  30642. if (target._lodTextureHigh) {
  30643. target._lodTextureHigh.dispose();
  30644. }
  30645. target._lodTextureHigh = this._lodTextureHigh;
  30646. }
  30647. if (this._lodTextureMid) {
  30648. if (target._lodTextureMid) {
  30649. target._lodTextureMid.dispose();
  30650. }
  30651. target._lodTextureMid = this._lodTextureMid;
  30652. }
  30653. if (this._lodTextureLow) {
  30654. if (target._lodTextureLow) {
  30655. target._lodTextureLow.dispose();
  30656. }
  30657. target._lodTextureLow = this._lodTextureLow;
  30658. }
  30659. var cache = this._engine.getLoadedTexturesCache();
  30660. var index = cache.indexOf(this);
  30661. if (index !== -1) {
  30662. cache.splice(index, 1);
  30663. }
  30664. };
  30665. /**
  30666. * Dispose the current allocated resources
  30667. */
  30668. InternalTexture.prototype.dispose = function () {
  30669. if (!this._webGLTexture) {
  30670. return;
  30671. }
  30672. this._references--;
  30673. if (this._references === 0) {
  30674. this._engine._releaseTexture(this);
  30675. this._webGLTexture = null;
  30676. this.previous = null;
  30677. this.next = null;
  30678. }
  30679. };
  30680. /**
  30681. * The source of the texture data is unknown
  30682. */
  30683. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30684. /**
  30685. * Texture data comes from an URL
  30686. */
  30687. InternalTexture.DATASOURCE_URL = 1;
  30688. /**
  30689. * Texture data is only used for temporary storage
  30690. */
  30691. InternalTexture.DATASOURCE_TEMP = 2;
  30692. /**
  30693. * Texture data comes from raw data (ArrayBuffer)
  30694. */
  30695. InternalTexture.DATASOURCE_RAW = 3;
  30696. /**
  30697. * Texture content is dynamic (video or dynamic texture)
  30698. */
  30699. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30700. /**
  30701. * Texture content is generated by rendering to it
  30702. */
  30703. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30704. /**
  30705. * Texture content is part of a multi render target process
  30706. */
  30707. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30708. /**
  30709. * Texture data comes from a cube data file
  30710. */
  30711. InternalTexture.DATASOURCE_CUBE = 7;
  30712. /**
  30713. * Texture data comes from a raw cube data
  30714. */
  30715. InternalTexture.DATASOURCE_CUBERAW = 8;
  30716. /**
  30717. * Texture data come from a prefiltered cube data file
  30718. */
  30719. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30720. /**
  30721. * Texture content is raw 3D data
  30722. */
  30723. InternalTexture.DATASOURCE_RAW3D = 10;
  30724. /**
  30725. * Texture content is a depth texture
  30726. */
  30727. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30728. /**
  30729. * Texture data comes from a raw cube data encoded with RGBD
  30730. */
  30731. InternalTexture.DATASOURCE_CUBERAW_RGBD = 12;
  30732. return InternalTexture;
  30733. }());
  30734. BABYLON.InternalTexture = InternalTexture;
  30735. })(BABYLON || (BABYLON = {}));
  30736. //# sourceMappingURL=babylon.internalTexture.js.map
  30737. var BABYLON;
  30738. (function (BABYLON) {
  30739. /**
  30740. * Base class of all the textures in babylon.
  30741. * It groups all the common properties the materials, post process, lights... might need
  30742. * in order to make a correct use of the texture.
  30743. */
  30744. var BaseTexture = /** @class */ (function () {
  30745. /**
  30746. * Instantiates a new BaseTexture.
  30747. * Base class of all the textures in babylon.
  30748. * It groups all the common properties the materials, post process, lights... might need
  30749. * in order to make a correct use of the texture.
  30750. * @param scene Define the scene the texture blongs to
  30751. */
  30752. function BaseTexture(scene) {
  30753. this._hasAlpha = false;
  30754. /**
  30755. * Defines if the alpha value should be determined via the rgb values.
  30756. * If true the luminance of the pixel might be used to find the corresponding alpha value.
  30757. */
  30758. this.getAlphaFromRGB = false;
  30759. /**
  30760. * Intensity or strength of the texture.
  30761. * It is commonly used by materials to fine tune the intensity of the texture
  30762. */
  30763. this.level = 1;
  30764. /**
  30765. * Define the UV chanel to use starting from 0 and defaulting to 0.
  30766. * This is part of the texture as textures usually maps to one uv set.
  30767. */
  30768. this.coordinatesIndex = 0;
  30769. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30770. /**
  30771. * | Value | Type | Description |
  30772. * | ----- | ------------------ | ----------- |
  30773. * | 0 | CLAMP_ADDRESSMODE | |
  30774. * | 1 | WRAP_ADDRESSMODE | |
  30775. * | 2 | MIRROR_ADDRESSMODE | |
  30776. */
  30777. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30778. /**
  30779. * | Value | Type | Description |
  30780. * | ----- | ------------------ | ----------- |
  30781. * | 0 | CLAMP_ADDRESSMODE | |
  30782. * | 1 | WRAP_ADDRESSMODE | |
  30783. * | 2 | MIRROR_ADDRESSMODE | |
  30784. */
  30785. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30786. /**
  30787. * | Value | Type | Description |
  30788. * | ----- | ------------------ | ----------- |
  30789. * | 0 | CLAMP_ADDRESSMODE | |
  30790. * | 1 | WRAP_ADDRESSMODE | |
  30791. * | 2 | MIRROR_ADDRESSMODE | |
  30792. */
  30793. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30794. /**
  30795. * With compliant hardware and browser (supporting anisotropic filtering)
  30796. * this defines the level of anisotropic filtering in the texture.
  30797. * The higher the better but the slower. This defaults to 4 as it seems to be the best tradeoff.
  30798. */
  30799. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30800. /**
  30801. * Define if the texture is a cube texture or if false a 2d texture.
  30802. */
  30803. this.isCube = false;
  30804. /**
  30805. * Define if the texture is a 3d texture (webgl 2) or if false a 2d texture.
  30806. */
  30807. this.is3D = false;
  30808. /**
  30809. * Define if the texture contains data in gamma space (most of the png/jpg aside bump).
  30810. * HDR texture are usually stored in linear space.
  30811. * This only impacts the PBR and Background materials
  30812. */
  30813. this.gammaSpace = true;
  30814. /**
  30815. * Is Z inverted in the texture (useful in a cube texture).
  30816. */
  30817. this.invertZ = false;
  30818. /**
  30819. * @hidden
  30820. */
  30821. this.lodLevelInAlpha = false;
  30822. /**
  30823. * Define if the texture is a render target.
  30824. */
  30825. this.isRenderTarget = false;
  30826. /**
  30827. * Define the list of animation attached to the texture.
  30828. */
  30829. this.animations = new Array();
  30830. /**
  30831. * An event triggered when the texture is disposed.
  30832. */
  30833. this.onDisposeObservable = new BABYLON.Observable();
  30834. /**
  30835. * Define the current state of the loading sequence when in delayed load mode.
  30836. */
  30837. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30838. this._cachedSize = BABYLON.Size.Zero();
  30839. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30840. if (this._scene) {
  30841. this._scene.textures.push(this);
  30842. this._scene.onNewTextureAddedObservable.notifyObservers(this);
  30843. }
  30844. this._uid = null;
  30845. }
  30846. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30847. get: function () {
  30848. return this._hasAlpha;
  30849. },
  30850. /**
  30851. * Define if the texture is having a usable alpha value (can be use for transparency or glossiness for instance).
  30852. */
  30853. set: function (value) {
  30854. if (this._hasAlpha === value) {
  30855. return;
  30856. }
  30857. this._hasAlpha = value;
  30858. if (this._scene) {
  30859. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30860. }
  30861. },
  30862. enumerable: true,
  30863. configurable: true
  30864. });
  30865. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30866. get: function () {
  30867. return this._coordinatesMode;
  30868. },
  30869. /**
  30870. * How a texture is mapped.
  30871. *
  30872. * | Value | Type | Description |
  30873. * | ----- | ----------------------------------- | ----------- |
  30874. * | 0 | EXPLICIT_MODE | |
  30875. * | 1 | SPHERICAL_MODE | |
  30876. * | 2 | PLANAR_MODE | |
  30877. * | 3 | CUBIC_MODE | |
  30878. * | 4 | PROJECTION_MODE | |
  30879. * | 5 | SKYBOX_MODE | |
  30880. * | 6 | INVCUBIC_MODE | |
  30881. * | 7 | EQUIRECTANGULAR_MODE | |
  30882. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30883. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30884. */
  30885. set: function (value) {
  30886. if (this._coordinatesMode === value) {
  30887. return;
  30888. }
  30889. this._coordinatesMode = value;
  30890. if (this._scene) {
  30891. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30892. }
  30893. },
  30894. enumerable: true,
  30895. configurable: true
  30896. });
  30897. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30898. /**
  30899. * Gets whether or not the texture contains RGBD data.
  30900. */
  30901. get: function () {
  30902. return this._texture != null && this._texture._isRGBD;
  30903. },
  30904. enumerable: true,
  30905. configurable: true
  30906. });
  30907. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30908. /**
  30909. * With prefiltered texture, defined the offset used during the prefiltering steps.
  30910. */
  30911. get: function () {
  30912. if (this._texture)
  30913. return this._texture._lodGenerationOffset;
  30914. return 0.0;
  30915. },
  30916. set: function (value) {
  30917. if (this._texture)
  30918. this._texture._lodGenerationOffset = value;
  30919. },
  30920. enumerable: true,
  30921. configurable: true
  30922. });
  30923. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30924. /**
  30925. * With prefiltered texture, defined the scale used during the prefiltering steps.
  30926. */
  30927. get: function () {
  30928. if (this._texture)
  30929. return this._texture._lodGenerationScale;
  30930. return 0.0;
  30931. },
  30932. set: function (value) {
  30933. if (this._texture)
  30934. this._texture._lodGenerationScale = value;
  30935. },
  30936. enumerable: true,
  30937. configurable: true
  30938. });
  30939. Object.defineProperty(BaseTexture.prototype, "uid", {
  30940. /**
  30941. * Define the unique id of the texture in the scene.
  30942. */
  30943. get: function () {
  30944. if (!this._uid) {
  30945. this._uid = BABYLON.Tools.RandomId();
  30946. }
  30947. return this._uid;
  30948. },
  30949. enumerable: true,
  30950. configurable: true
  30951. });
  30952. /**
  30953. * Return a string representation of the texture.
  30954. * @returns the texture as a string
  30955. */
  30956. BaseTexture.prototype.toString = function () {
  30957. return this.name;
  30958. };
  30959. /**
  30960. * Get the class name of the texture.
  30961. * @returns "BaseTexture"
  30962. */
  30963. BaseTexture.prototype.getClassName = function () {
  30964. return "BaseTexture";
  30965. };
  30966. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30967. /**
  30968. * Callback triggered when the texture has been disposed.
  30969. * Kept for back compatibility, you can use the onDisposeObservable instead.
  30970. */
  30971. set: function (callback) {
  30972. if (this._onDisposeObserver) {
  30973. this.onDisposeObservable.remove(this._onDisposeObserver);
  30974. }
  30975. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30976. },
  30977. enumerable: true,
  30978. configurable: true
  30979. });
  30980. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30981. /**
  30982. * Define if the texture is preventinga material to render or not.
  30983. * If not and the texture is not ready, the engine will use a default black texture instead.
  30984. */
  30985. get: function () {
  30986. return true;
  30987. },
  30988. enumerable: true,
  30989. configurable: true
  30990. });
  30991. /**
  30992. * Get the scene the texture belongs to.
  30993. * @returns the scene or null if undefined
  30994. */
  30995. BaseTexture.prototype.getScene = function () {
  30996. return this._scene;
  30997. };
  30998. /**
  30999. * Get the texture transform matrix used to offset tile the texture for istance.
  31000. * @returns the transformation matrix
  31001. */
  31002. BaseTexture.prototype.getTextureMatrix = function () {
  31003. return BABYLON.Matrix.IdentityReadOnly;
  31004. };
  31005. /**
  31006. * Get the texture reflection matrix used to rotate/transform the reflection.
  31007. * @returns the reflection matrix
  31008. */
  31009. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  31010. return BABYLON.Matrix.IdentityReadOnly;
  31011. };
  31012. /**
  31013. * Get the underlying lower level texture from Babylon.
  31014. * @returns the insternal texture
  31015. */
  31016. BaseTexture.prototype.getInternalTexture = function () {
  31017. return this._texture;
  31018. };
  31019. /**
  31020. * Get if the texture is ready to be consumed (either it is ready or it is not blocking)
  31021. * @returns true if ready or not blocking
  31022. */
  31023. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  31024. return !this.isBlocking || this.isReady();
  31025. };
  31026. /**
  31027. * Get if the texture is ready to be used (downloaded, converted, mip mapped...).
  31028. * @returns true if fully ready
  31029. */
  31030. BaseTexture.prototype.isReady = function () {
  31031. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31032. this.delayLoad();
  31033. return false;
  31034. }
  31035. if (this._texture) {
  31036. return this._texture.isReady;
  31037. }
  31038. return false;
  31039. };
  31040. /**
  31041. * Get the size of the texture.
  31042. * @returns the texture size.
  31043. */
  31044. BaseTexture.prototype.getSize = function () {
  31045. if (this._texture) {
  31046. if (this._texture.width) {
  31047. this._cachedSize.width = this._texture.width;
  31048. this._cachedSize.height = this._texture.height;
  31049. return this._cachedSize;
  31050. }
  31051. if (this._texture._size) {
  31052. this._cachedSize.width = this._texture._size;
  31053. this._cachedSize.height = this._texture._size;
  31054. return this._cachedSize;
  31055. }
  31056. }
  31057. return this._cachedSize;
  31058. };
  31059. /**
  31060. * Get the base size of the texture.
  31061. * It can be different from the size if the texture has been resized for POT for instance
  31062. * @returns the base size
  31063. */
  31064. BaseTexture.prototype.getBaseSize = function () {
  31065. if (!this.isReady() || !this._texture)
  31066. return BABYLON.Size.Zero();
  31067. if (this._texture._size) {
  31068. return new BABYLON.Size(this._texture._size, this._texture._size);
  31069. }
  31070. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  31071. };
  31072. /**
  31073. * Scales the texture if is `canRescale()`
  31074. * @param ratio the resize factor we want to use to rescale
  31075. */
  31076. BaseTexture.prototype.scale = function (ratio) {
  31077. };
  31078. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  31079. /**
  31080. * Get if the texture can rescale.
  31081. */
  31082. get: function () {
  31083. return false;
  31084. },
  31085. enumerable: true,
  31086. configurable: true
  31087. });
  31088. /** @hidden */
  31089. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  31090. if (!this._scene) {
  31091. return null;
  31092. }
  31093. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  31094. for (var index = 0; index < texturesCache.length; index++) {
  31095. var texturesCacheEntry = texturesCache[index];
  31096. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  31097. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  31098. texturesCacheEntry.incrementReferences();
  31099. return texturesCacheEntry;
  31100. }
  31101. }
  31102. }
  31103. return null;
  31104. };
  31105. /** @hidden */
  31106. BaseTexture.prototype._rebuild = function () {
  31107. };
  31108. /**
  31109. * Triggers the load sequence in delayed load mode.
  31110. */
  31111. BaseTexture.prototype.delayLoad = function () {
  31112. };
  31113. /**
  31114. * Clones the texture.
  31115. * @returns the cloned texture
  31116. */
  31117. BaseTexture.prototype.clone = function () {
  31118. return null;
  31119. };
  31120. Object.defineProperty(BaseTexture.prototype, "textureType", {
  31121. /**
  31122. * Get the texture underlying type (INT, FLOAT...)
  31123. */
  31124. get: function () {
  31125. if (!this._texture) {
  31126. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31127. }
  31128. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  31129. },
  31130. enumerable: true,
  31131. configurable: true
  31132. });
  31133. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  31134. /**
  31135. * Get the texture underlying format (RGB, RGBA...)
  31136. */
  31137. get: function () {
  31138. if (!this._texture) {
  31139. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31140. }
  31141. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  31142. },
  31143. enumerable: true,
  31144. configurable: true
  31145. });
  31146. /**
  31147. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  31148. * This will returns an RGBA array buffer containing either in values (0-255) or
  31149. * float values (0-1) depending of the underlying buffer type.
  31150. * @param faceIndex defines the face of the texture to read (in case of cube texture)
  31151. * @param level defines the LOD level of the texture to read (in case of Mip Maps)
  31152. * @param buffer defines a user defined buffer to fill with data (can be null)
  31153. * @returns The Array buffer containing the pixels data.
  31154. */
  31155. BaseTexture.prototype.readPixels = function (faceIndex, level, buffer) {
  31156. if (faceIndex === void 0) { faceIndex = 0; }
  31157. if (level === void 0) { level = 0; }
  31158. if (buffer === void 0) { buffer = null; }
  31159. if (!this._texture) {
  31160. return null;
  31161. }
  31162. var size = this.getSize();
  31163. var width = size.width;
  31164. var height = size.height;
  31165. var scene = this.getScene();
  31166. if (!scene) {
  31167. return null;
  31168. }
  31169. var engine = scene.getEngine();
  31170. if (level != 0) {
  31171. width = width / Math.pow(2, level);
  31172. height = height / Math.pow(2, level);
  31173. width = Math.round(width);
  31174. height = Math.round(height);
  31175. }
  31176. if (this._texture.isCube) {
  31177. return engine._readTexturePixels(this._texture, width, height, faceIndex, level, buffer);
  31178. }
  31179. return engine._readTexturePixels(this._texture, width, height, -1, level, buffer);
  31180. };
  31181. /**
  31182. * Release and destroy the underlying lower level texture aka internalTexture.
  31183. */
  31184. BaseTexture.prototype.releaseInternalTexture = function () {
  31185. if (this._texture) {
  31186. this._texture.dispose();
  31187. this._texture = null;
  31188. }
  31189. };
  31190. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  31191. /**
  31192. * Get the polynomial representation of the texture data.
  31193. * This is mainly use as a fast way to recover IBL Diffuse irradiance data.
  31194. * @see https://learnopengl.com/PBR/IBL/Diffuse-irradiance
  31195. */
  31196. get: function () {
  31197. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  31198. return null;
  31199. }
  31200. if (!this._texture._sphericalPolynomial) {
  31201. this._texture._sphericalPolynomial =
  31202. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  31203. }
  31204. return this._texture._sphericalPolynomial;
  31205. },
  31206. set: function (value) {
  31207. if (this._texture) {
  31208. this._texture._sphericalPolynomial = value;
  31209. }
  31210. },
  31211. enumerable: true,
  31212. configurable: true
  31213. });
  31214. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  31215. /** @hidden */
  31216. get: function () {
  31217. if (this._texture) {
  31218. return this._texture._lodTextureHigh;
  31219. }
  31220. return null;
  31221. },
  31222. enumerable: true,
  31223. configurable: true
  31224. });
  31225. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  31226. /** @hidden */
  31227. get: function () {
  31228. if (this._texture) {
  31229. return this._texture._lodTextureMid;
  31230. }
  31231. return null;
  31232. },
  31233. enumerable: true,
  31234. configurable: true
  31235. });
  31236. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  31237. /** @hidden */
  31238. get: function () {
  31239. if (this._texture) {
  31240. return this._texture._lodTextureLow;
  31241. }
  31242. return null;
  31243. },
  31244. enumerable: true,
  31245. configurable: true
  31246. });
  31247. /**
  31248. * Dispose the texture and release its associated resources.
  31249. */
  31250. BaseTexture.prototype.dispose = function () {
  31251. if (!this._scene) {
  31252. return;
  31253. }
  31254. // Animations
  31255. this._scene.stopAnimation(this);
  31256. // Remove from scene
  31257. this._scene._removePendingData(this);
  31258. var index = this._scene.textures.indexOf(this);
  31259. if (index >= 0) {
  31260. this._scene.textures.splice(index, 1);
  31261. }
  31262. this._scene.onTextureRemovedObservable.notifyObservers(this);
  31263. if (this._texture === undefined) {
  31264. return;
  31265. }
  31266. // Release
  31267. this.releaseInternalTexture();
  31268. // Callback
  31269. this.onDisposeObservable.notifyObservers(this);
  31270. this.onDisposeObservable.clear();
  31271. };
  31272. /**
  31273. * Serialize the texture into a JSON representation that can be parsed later on.
  31274. * @returns the JSON representation of the texture
  31275. */
  31276. BaseTexture.prototype.serialize = function () {
  31277. if (!this.name) {
  31278. return null;
  31279. }
  31280. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  31281. // Animations
  31282. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31283. return serializationObject;
  31284. };
  31285. /**
  31286. * Helper function to be called back once a list of texture contains only ready textures.
  31287. * @param textures Define the list of textures to wait for
  31288. * @param callback Define the callback triggered once the entire list will be ready
  31289. */
  31290. BaseTexture.WhenAllReady = function (textures, callback) {
  31291. var numRemaining = textures.length;
  31292. if (numRemaining === 0) {
  31293. callback();
  31294. return;
  31295. }
  31296. var _loop_1 = function () {
  31297. texture = textures[i];
  31298. if (texture.isReady()) {
  31299. if (--numRemaining === 0) {
  31300. callback();
  31301. }
  31302. }
  31303. else {
  31304. onLoadObservable = texture.onLoadObservable;
  31305. var onLoadCallback_1 = function () {
  31306. onLoadObservable.removeCallback(onLoadCallback_1);
  31307. if (--numRemaining === 0) {
  31308. callback();
  31309. }
  31310. };
  31311. onLoadObservable.add(onLoadCallback_1);
  31312. }
  31313. };
  31314. var texture, onLoadObservable;
  31315. for (var i = 0; i < textures.length; i++) {
  31316. _loop_1();
  31317. }
  31318. };
  31319. /**
  31320. * Default anisotropic filtering level for the application.
  31321. * It is set to 4 as a good tradeoff between perf and quality.
  31322. */
  31323. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31324. __decorate([
  31325. BABYLON.serialize()
  31326. ], BaseTexture.prototype, "name", void 0);
  31327. __decorate([
  31328. BABYLON.serialize("hasAlpha")
  31329. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31330. __decorate([
  31331. BABYLON.serialize()
  31332. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31333. __decorate([
  31334. BABYLON.serialize()
  31335. ], BaseTexture.prototype, "level", void 0);
  31336. __decorate([
  31337. BABYLON.serialize()
  31338. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31339. __decorate([
  31340. BABYLON.serialize("coordinatesMode")
  31341. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31342. __decorate([
  31343. BABYLON.serialize()
  31344. ], BaseTexture.prototype, "wrapU", void 0);
  31345. __decorate([
  31346. BABYLON.serialize()
  31347. ], BaseTexture.prototype, "wrapV", void 0);
  31348. __decorate([
  31349. BABYLON.serialize()
  31350. ], BaseTexture.prototype, "wrapR", void 0);
  31351. __decorate([
  31352. BABYLON.serialize()
  31353. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31354. __decorate([
  31355. BABYLON.serialize()
  31356. ], BaseTexture.prototype, "isCube", void 0);
  31357. __decorate([
  31358. BABYLON.serialize()
  31359. ], BaseTexture.prototype, "is3D", void 0);
  31360. __decorate([
  31361. BABYLON.serialize()
  31362. ], BaseTexture.prototype, "gammaSpace", void 0);
  31363. __decorate([
  31364. BABYLON.serialize()
  31365. ], BaseTexture.prototype, "invertZ", void 0);
  31366. __decorate([
  31367. BABYLON.serialize()
  31368. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31369. __decorate([
  31370. BABYLON.serialize()
  31371. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31372. __decorate([
  31373. BABYLON.serialize()
  31374. ], BaseTexture.prototype, "lodGenerationScale", null);
  31375. __decorate([
  31376. BABYLON.serialize()
  31377. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31378. return BaseTexture;
  31379. }());
  31380. BABYLON.BaseTexture = BaseTexture;
  31381. })(BABYLON || (BABYLON = {}));
  31382. //# sourceMappingURL=babylon.baseTexture.js.map
  31383. var BABYLON;
  31384. (function (BABYLON) {
  31385. /**
  31386. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31387. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31388. */
  31389. var Texture = /** @class */ (function (_super) {
  31390. __extends(Texture, _super);
  31391. /**
  31392. * Instantiates a new texture.
  31393. * This represents a texture in babylon. It can be easily loaded from a network, base64 or html input.
  31394. * @see http://doc.babylonjs.com/babylon101/materials#texture
  31395. * @param url define the url of the picture to load as a texture
  31396. * @param scene define the scene the texture will belong to
  31397. * @param noMipmap define if the texture will require mip maps or not
  31398. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31399. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31400. * @param onLoad define a callback triggered when the texture has been loaded
  31401. * @param onError define a callback triggered when an error occurred during the loading session
  31402. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31403. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31404. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31405. */
  31406. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31407. if (noMipmap === void 0) { noMipmap = false; }
  31408. if (invertY === void 0) { invertY = true; }
  31409. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31410. if (onLoad === void 0) { onLoad = null; }
  31411. if (onError === void 0) { onError = null; }
  31412. if (buffer === void 0) { buffer = null; }
  31413. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31414. var _this = _super.call(this, scene) || this;
  31415. /**
  31416. * Define an offset on the texture to offset the u coordinates of the UVs
  31417. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31418. */
  31419. _this.uOffset = 0;
  31420. /**
  31421. * Define an offset on the texture to offset the v coordinates of the UVs
  31422. * @see http://doc.babylonjs.com/how_to/more_materials#offsetting
  31423. */
  31424. _this.vOffset = 0;
  31425. /**
  31426. * Define an offset on the texture to scale the u coordinates of the UVs
  31427. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31428. */
  31429. _this.uScale = 1.0;
  31430. /**
  31431. * Define an offset on the texture to scale the v coordinates of the UVs
  31432. * @see http://doc.babylonjs.com/how_to/more_materials#tiling
  31433. */
  31434. _this.vScale = 1.0;
  31435. /**
  31436. * Define an offset on the texture to rotate around the u coordinates of the UVs
  31437. * @see http://doc.babylonjs.com/how_to/more_materials
  31438. */
  31439. _this.uAng = 0;
  31440. /**
  31441. * Define an offset on the texture to rotate around the v coordinates of the UVs
  31442. * @see http://doc.babylonjs.com/how_to/more_materials
  31443. */
  31444. _this.vAng = 0;
  31445. /**
  31446. * Define an offset on the texture to rotate around the w coordinates of the UVs (in case of 3d texture)
  31447. * @see http://doc.babylonjs.com/how_to/more_materials
  31448. */
  31449. _this.wAng = 0;
  31450. /**
  31451. * Defines the center of rotation (U)
  31452. */
  31453. _this.uRotationCenter = 0.5;
  31454. /**
  31455. * Defines the center of rotation (V)
  31456. */
  31457. _this.vRotationCenter = 0.5;
  31458. /**
  31459. * Defines the center of rotation (W)
  31460. */
  31461. _this.wRotationCenter = 0.5;
  31462. /**
  31463. * Observable triggered once the texture has been loaded.
  31464. */
  31465. _this.onLoadObservable = new BABYLON.Observable();
  31466. _this._isBlocking = true;
  31467. _this.name = url || "";
  31468. _this.url = url;
  31469. _this._noMipmap = noMipmap;
  31470. _this._invertY = invertY;
  31471. _this._samplingMode = samplingMode;
  31472. _this._buffer = buffer;
  31473. _this._deleteBuffer = deleteBuffer;
  31474. if (format) {
  31475. _this._format = format;
  31476. }
  31477. scene = _this.getScene();
  31478. if (!scene) {
  31479. return _this;
  31480. }
  31481. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31482. var load = function () {
  31483. if (_this.onLoadObservable.hasObservers()) {
  31484. _this.onLoadObservable.notifyObservers(_this);
  31485. }
  31486. if (onLoad) {
  31487. onLoad();
  31488. }
  31489. if (!_this.isBlocking && scene) {
  31490. scene.resetCachedMaterial();
  31491. }
  31492. };
  31493. if (!_this.url) {
  31494. _this._delayedOnLoad = load;
  31495. _this._delayedOnError = onError;
  31496. return _this;
  31497. }
  31498. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31499. if (!_this._texture) {
  31500. if (!scene.useDelayedTextureLoading) {
  31501. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31502. if (deleteBuffer) {
  31503. delete _this._buffer;
  31504. }
  31505. }
  31506. else {
  31507. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31508. _this._delayedOnLoad = load;
  31509. _this._delayedOnError = onError;
  31510. }
  31511. }
  31512. else {
  31513. if (_this._texture.isReady) {
  31514. BABYLON.Tools.SetImmediate(function () { return load(); });
  31515. }
  31516. else {
  31517. _this._texture.onLoadedObservable.add(load);
  31518. }
  31519. }
  31520. return _this;
  31521. }
  31522. Object.defineProperty(Texture.prototype, "noMipmap", {
  31523. /**
  31524. * Are mip maps generated for this texture or not.
  31525. */
  31526. get: function () {
  31527. return this._noMipmap;
  31528. },
  31529. enumerable: true,
  31530. configurable: true
  31531. });
  31532. Object.defineProperty(Texture.prototype, "isBlocking", {
  31533. get: function () {
  31534. return this._isBlocking;
  31535. },
  31536. /**
  31537. * Is the texture preventing material to render while loading.
  31538. * If false, a default texture will be used instead of the loading one during the preparation step.
  31539. */
  31540. set: function (value) {
  31541. this._isBlocking = value;
  31542. },
  31543. enumerable: true,
  31544. configurable: true
  31545. });
  31546. Object.defineProperty(Texture.prototype, "samplingMode", {
  31547. /**
  31548. * Get the current sampling mode associated with the texture.
  31549. */
  31550. get: function () {
  31551. return this._samplingMode;
  31552. },
  31553. enumerable: true,
  31554. configurable: true
  31555. });
  31556. /**
  31557. * Update the url (and optional buffer) of this texture if url was null during construction.
  31558. * @param url the url of the texture
  31559. * @param buffer the buffer of the texture (defaults to null)
  31560. */
  31561. Texture.prototype.updateURL = function (url, buffer) {
  31562. if (buffer === void 0) { buffer = null; }
  31563. if (this.url) {
  31564. throw new Error("URL is already set");
  31565. }
  31566. this.url = url;
  31567. this._buffer = buffer;
  31568. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31569. this.delayLoad();
  31570. };
  31571. /**
  31572. * Finish the loading sequence of a texture flagged as delayed load.
  31573. * @hidden
  31574. */
  31575. Texture.prototype.delayLoad = function () {
  31576. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31577. return;
  31578. }
  31579. var scene = this.getScene();
  31580. if (!scene) {
  31581. return;
  31582. }
  31583. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31584. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31585. if (!this._texture) {
  31586. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31587. if (this._deleteBuffer) {
  31588. delete this._buffer;
  31589. }
  31590. }
  31591. else {
  31592. if (this._delayedOnLoad) {
  31593. if (this._texture.isReady) {
  31594. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31595. }
  31596. else {
  31597. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31598. }
  31599. }
  31600. }
  31601. this._delayedOnLoad = null;
  31602. this._delayedOnError = null;
  31603. };
  31604. /**
  31605. * Update the sampling mode of the texture.
  31606. * Default is Trilinear mode.
  31607. *
  31608. * | Value | Type | Description |
  31609. * | ----- | ------------------ | ----------- |
  31610. * | 1 | NEAREST_SAMPLINGMODE or NEAREST_NEAREST_MIPLINEAR | Nearest is: mag = nearest, min = nearest, mip = linear |
  31611. * | 2 | BILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPNEAREST | Bilinear is: mag = linear, min = linear, mip = nearest |
  31612. * | 3 | TRILINEAR_SAMPLINGMODE or LINEAR_LINEAR_MIPLINEAR | Trilinear is: mag = linear, min = linear, mip = linear |
  31613. * | 4 | NEAREST_NEAREST_MIPNEAREST | |
  31614. * | 5 | NEAREST_LINEAR_MIPNEAREST | |
  31615. * | 6 | NEAREST_LINEAR_MIPLINEAR | |
  31616. * | 7 | NEAREST_LINEAR | |
  31617. * | 8 | NEAREST_NEAREST | |
  31618. * | 9 | LINEAR_NEAREST_MIPNEAREST | |
  31619. * | 10 | LINEAR_NEAREST_MIPLINEAR | |
  31620. * | 11 | LINEAR_LINEAR | |
  31621. * | 12 | LINEAR_NEAREST | |
  31622. *
  31623. * > _mag_: magnification filter (close to the viewer)
  31624. * > _min_: minification filter (far from the viewer)
  31625. * > _mip_: filter used between mip map levels
  31626. *@param samplingMode Define the new sampling mode of the texture
  31627. */
  31628. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31629. if (!this._texture) {
  31630. return;
  31631. }
  31632. var scene = this.getScene();
  31633. if (!scene) {
  31634. return;
  31635. }
  31636. this._samplingMode = samplingMode;
  31637. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31638. };
  31639. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31640. x *= this.uScale;
  31641. y *= this.vScale;
  31642. x -= this.uRotationCenter * this.uScale;
  31643. y -= this.vRotationCenter * this.vScale;
  31644. z -= this.wRotationCenter;
  31645. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31646. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31647. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31648. t.z += this.wRotationCenter;
  31649. };
  31650. /**
  31651. * Get the current texture matrix which includes the requested offsetting, tiling and rotation components.
  31652. * @returns the transform matrix of the texture.
  31653. */
  31654. Texture.prototype.getTextureMatrix = function () {
  31655. var _this = this;
  31656. if (this.uOffset === this._cachedUOffset &&
  31657. this.vOffset === this._cachedVOffset &&
  31658. this.uScale === this._cachedUScale &&
  31659. this.vScale === this._cachedVScale &&
  31660. this.uAng === this._cachedUAng &&
  31661. this.vAng === this._cachedVAng &&
  31662. this.wAng === this._cachedWAng) {
  31663. return this._cachedTextureMatrix;
  31664. }
  31665. this._cachedUOffset = this.uOffset;
  31666. this._cachedVOffset = this.vOffset;
  31667. this._cachedUScale = this.uScale;
  31668. this._cachedVScale = this.vScale;
  31669. this._cachedUAng = this.uAng;
  31670. this._cachedVAng = this.vAng;
  31671. this._cachedWAng = this.wAng;
  31672. if (!this._cachedTextureMatrix) {
  31673. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31674. this._rowGenerationMatrix = new BABYLON.Matrix();
  31675. this._t0 = BABYLON.Vector3.Zero();
  31676. this._t1 = BABYLON.Vector3.Zero();
  31677. this._t2 = BABYLON.Vector3.Zero();
  31678. }
  31679. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31680. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31681. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31682. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31683. this._t1.subtractInPlace(this._t0);
  31684. this._t2.subtractInPlace(this._t0);
  31685. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31686. this._cachedTextureMatrix.m[0] = this._t1.x;
  31687. this._cachedTextureMatrix.m[1] = this._t1.y;
  31688. this._cachedTextureMatrix.m[2] = this._t1.z;
  31689. this._cachedTextureMatrix.m[4] = this._t2.x;
  31690. this._cachedTextureMatrix.m[5] = this._t2.y;
  31691. this._cachedTextureMatrix.m[6] = this._t2.z;
  31692. this._cachedTextureMatrix.m[8] = this._t0.x;
  31693. this._cachedTextureMatrix.m[9] = this._t0.y;
  31694. this._cachedTextureMatrix.m[10] = this._t0.z;
  31695. var scene = this.getScene();
  31696. if (!scene) {
  31697. return this._cachedTextureMatrix;
  31698. }
  31699. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31700. return mat.hasTexture(_this);
  31701. });
  31702. return this._cachedTextureMatrix;
  31703. };
  31704. /**
  31705. * Get the current matrix used to apply reflection. This is useful to rotate an environment texture for instance.
  31706. * @returns The reflection texture transform
  31707. */
  31708. Texture.prototype.getReflectionTextureMatrix = function () {
  31709. var _this = this;
  31710. var scene = this.getScene();
  31711. if (!scene) {
  31712. return this._cachedTextureMatrix;
  31713. }
  31714. if (this.uOffset === this._cachedUOffset &&
  31715. this.vOffset === this._cachedVOffset &&
  31716. this.uScale === this._cachedUScale &&
  31717. this.vScale === this._cachedVScale &&
  31718. this.coordinatesMode === this._cachedCoordinatesMode) {
  31719. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31720. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31721. return this._cachedTextureMatrix;
  31722. }
  31723. }
  31724. else {
  31725. return this._cachedTextureMatrix;
  31726. }
  31727. }
  31728. if (!this._cachedTextureMatrix) {
  31729. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31730. }
  31731. if (!this._projectionModeMatrix) {
  31732. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31733. }
  31734. this._cachedUOffset = this.uOffset;
  31735. this._cachedVOffset = this.vOffset;
  31736. this._cachedUScale = this.uScale;
  31737. this._cachedVScale = this.vScale;
  31738. this._cachedCoordinatesMode = this.coordinatesMode;
  31739. switch (this.coordinatesMode) {
  31740. case Texture.PLANAR_MODE:
  31741. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31742. this._cachedTextureMatrix[0] = this.uScale;
  31743. this._cachedTextureMatrix[5] = this.vScale;
  31744. this._cachedTextureMatrix[12] = this.uOffset;
  31745. this._cachedTextureMatrix[13] = this.vOffset;
  31746. break;
  31747. case Texture.PROJECTION_MODE:
  31748. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31749. this._projectionModeMatrix.m[0] = 0.5;
  31750. this._projectionModeMatrix.m[5] = -0.5;
  31751. this._projectionModeMatrix.m[10] = 0.0;
  31752. this._projectionModeMatrix.m[12] = 0.5;
  31753. this._projectionModeMatrix.m[13] = 0.5;
  31754. this._projectionModeMatrix.m[14] = 1.0;
  31755. this._projectionModeMatrix.m[15] = 1.0;
  31756. var projectionMatrix = scene.getProjectionMatrix();
  31757. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31758. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31759. break;
  31760. default:
  31761. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31762. break;
  31763. }
  31764. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31765. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31766. });
  31767. return this._cachedTextureMatrix;
  31768. };
  31769. /**
  31770. * Clones the texture.
  31771. * @returns the cloned texture
  31772. */
  31773. Texture.prototype.clone = function () {
  31774. var _this = this;
  31775. return BABYLON.SerializationHelper.Clone(function () {
  31776. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31777. }, this);
  31778. };
  31779. /**
  31780. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  31781. * @returns The JSON representation of the texture
  31782. */
  31783. Texture.prototype.serialize = function () {
  31784. var serializationObject = _super.prototype.serialize.call(this);
  31785. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31786. serializationObject.base64String = this._buffer;
  31787. serializationObject.name = serializationObject.name.replace("data:", "");
  31788. }
  31789. serializationObject.invertY = this._invertY;
  31790. serializationObject.samplingMode = this.samplingMode;
  31791. return serializationObject;
  31792. };
  31793. /**
  31794. * Get the current class name of the texture usefull for serialization or dynamic coding.
  31795. * @returns "Texture"
  31796. */
  31797. Texture.prototype.getClassName = function () {
  31798. return "Texture";
  31799. };
  31800. /**
  31801. * Dispose the texture and release its associated resources.
  31802. */
  31803. Texture.prototype.dispose = function () {
  31804. _super.prototype.dispose.call(this);
  31805. this.onLoadObservable.clear();
  31806. this._delayedOnLoad = null;
  31807. this._delayedOnError = null;
  31808. };
  31809. /**
  31810. * Parse the JSON representation of a texture in order to recreate the texture in the given scene.
  31811. * @param parsedTexture Define the JSON representation of the texture
  31812. * @param scene Define the scene the parsed texture should be instantiated in
  31813. * @param rootUrl Define the root url of the parsing sequence in the case of relative dependencies
  31814. * @returns The parsed texture if successful
  31815. */
  31816. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31817. if (parsedTexture.customType) {
  31818. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31819. // Update Sampling Mode
  31820. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31821. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31822. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31823. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31824. }
  31825. }
  31826. return parsedCustomTexture;
  31827. }
  31828. if (parsedTexture.isCube) {
  31829. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31830. }
  31831. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31832. return null;
  31833. }
  31834. var texture = BABYLON.SerializationHelper.Parse(function () {
  31835. var generateMipMaps = true;
  31836. if (parsedTexture.noMipmap) {
  31837. generateMipMaps = false;
  31838. }
  31839. if (parsedTexture.mirrorPlane) {
  31840. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31841. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31842. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31843. return mirrorTexture;
  31844. }
  31845. else if (parsedTexture.isRenderTarget) {
  31846. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31847. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31848. return renderTargetTexture;
  31849. }
  31850. else {
  31851. var texture;
  31852. if (parsedTexture.base64String) {
  31853. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31854. }
  31855. else {
  31856. var url = rootUrl + parsedTexture.name;
  31857. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31858. url = parsedTexture.url;
  31859. }
  31860. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31861. }
  31862. return texture;
  31863. }
  31864. }, parsedTexture, scene);
  31865. // Update Sampling Mode
  31866. if (parsedTexture.samplingMode) {
  31867. var sampling = parsedTexture.samplingMode;
  31868. if (texture._samplingMode !== sampling) {
  31869. texture.updateSamplingMode(sampling);
  31870. }
  31871. }
  31872. // Animations
  31873. if (parsedTexture.animations) {
  31874. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31875. var parsedAnimation = parsedTexture.animations[animationIndex];
  31876. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31877. }
  31878. }
  31879. return texture;
  31880. };
  31881. /**
  31882. * Creates a texture from its base 64 representation.
  31883. * @param data Define the base64 payload without the data: prefix
  31884. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31885. * @param scene Define the scene the texture should belong to
  31886. * @param noMipmap Forces the texture to not create mip map information if true
  31887. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31888. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31889. * @param onLoad define a callback triggered when the texture has been loaded
  31890. * @param onError define a callback triggered when an error occurred during the loading session
  31891. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31892. * @returns the created texture
  31893. */
  31894. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31895. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31896. if (onLoad === void 0) { onLoad = null; }
  31897. if (onError === void 0) { onError = null; }
  31898. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31899. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31900. };
  31901. /**
  31902. * Creates a texture from its data: representation. (data: will be added in case only the payload has been passed in)
  31903. * @param data Define the base64 payload without the data: prefix
  31904. * @param name Define the name of the texture in the scene useful fo caching purpose for instance
  31905. * @param buffer define the buffer to load the texture from in case the texture is loaded from a buffer representation
  31906. * @param scene Define the scene the texture should belong to
  31907. * @param deleteBuffer define if the buffer we are loading the texture from should be deleted after load
  31908. * @param noMipmap Forces the texture to not create mip map information if true
  31909. * @param invertY define if the texture needs to be inverted on the y axis during loading
  31910. * @param samplingMode define the sampling mode we want for the texture while fectching from it (Texture.NEAREST_SAMPLINGMODE...)
  31911. * @param onLoad define a callback triggered when the texture has been loaded
  31912. * @param onError define a callback triggered when an error occurred during the loading session
  31913. * @param format define the format of the texture we are trying to load (Engine.TEXTUREFORMAT_RGBA...)
  31914. * @returns the created texture
  31915. */
  31916. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31917. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31918. if (noMipmap === void 0) { noMipmap = false; }
  31919. if (invertY === void 0) { invertY = true; }
  31920. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31921. if (onLoad === void 0) { onLoad = null; }
  31922. if (onError === void 0) { onError = null; }
  31923. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31924. if (name.substr(0, 5) !== "data:") {
  31925. name = "data:" + name;
  31926. }
  31927. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31928. };
  31929. /** nearest is mag = nearest and min = nearest and mip = linear */
  31930. Texture.NEAREST_SAMPLINGMODE = BABYLON.Engine.TEXTURE_NEAREST_SAMPLINGMODE;
  31931. /** nearest is mag = nearest and min = nearest and mip = linear */
  31932. Texture.NEAREST_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPLINEAR; // nearest is mag = nearest and min = nearest and mip = linear
  31933. /** Bilinear is mag = linear and min = linear and mip = nearest */
  31934. Texture.BILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_BILINEAR_SAMPLINGMODE;
  31935. /** Bilinear is mag = linear and min = linear and mip = nearest */
  31936. Texture.LINEAR_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPNEAREST; // Bilinear is mag = linear and min = linear and mip = nearest
  31937. /** Trilinear is mag = linear and min = linear and mip = linear */
  31938. Texture.TRILINEAR_SAMPLINGMODE = BABYLON.Engine.TEXTURE_TRILINEAR_SAMPLINGMODE;
  31939. /** Trilinear is mag = linear and min = linear and mip = linear */
  31940. Texture.LINEAR_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR_MIPLINEAR; // Trilinear is mag = linear and min = linear and mip = linear
  31941. /** mag = nearest and min = nearest and mip = nearest */
  31942. Texture.NEAREST_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST_MIPNEAREST;
  31943. /** mag = nearest and min = linear and mip = nearest */
  31944. Texture.NEAREST_LINEAR_MIPNEAREST = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPNEAREST;
  31945. /** mag = nearest and min = linear and mip = linear */
  31946. Texture.NEAREST_LINEAR_MIPLINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR_MIPLINEAR;
  31947. /** mag = nearest and min = linear and mip = none */
  31948. Texture.NEAREST_LINEAR = BABYLON.Engine.TEXTURE_NEAREST_LINEAR;
  31949. /** mag = nearest and min = nearest and mip = none */
  31950. Texture.NEAREST_NEAREST = BABYLON.Engine.TEXTURE_NEAREST_NEAREST;
  31951. /** mag = linear and min = nearest and mip = nearest */
  31952. Texture.LINEAR_NEAREST_MIPNEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPNEAREST;
  31953. /** mag = linear and min = nearest and mip = linear */
  31954. Texture.LINEAR_NEAREST_MIPLINEAR = BABYLON.Engine.TEXTURE_LINEAR_NEAREST_MIPLINEAR;
  31955. /** mag = linear and min = linear and mip = none */
  31956. Texture.LINEAR_LINEAR = BABYLON.Engine.TEXTURE_LINEAR_LINEAR;
  31957. /** mag = linear and min = nearest and mip = none */
  31958. Texture.LINEAR_NEAREST = BABYLON.Engine.TEXTURE_LINEAR_NEAREST;
  31959. /** Explicit coordinates mode */
  31960. Texture.EXPLICIT_MODE = BABYLON.Engine.TEXTURE_EXPLICIT_MODE;
  31961. /** Spherical coordinates mode */
  31962. Texture.SPHERICAL_MODE = BABYLON.Engine.TEXTURE_SPHERICAL_MODE;
  31963. /** Planar coordinates mode */
  31964. Texture.PLANAR_MODE = BABYLON.Engine.TEXTURE_PLANAR_MODE;
  31965. /** Cubic coordinates mode */
  31966. Texture.CUBIC_MODE = BABYLON.Engine.TEXTURE_CUBIC_MODE;
  31967. /** Projection coordinates mode */
  31968. Texture.PROJECTION_MODE = BABYLON.Engine.TEXTURE_PROJECTION_MODE;
  31969. /** Inverse Cubic coordinates mode */
  31970. Texture.SKYBOX_MODE = BABYLON.Engine.TEXTURE_SKYBOX_MODE;
  31971. /** Inverse Cubic coordinates mode */
  31972. Texture.INVCUBIC_MODE = BABYLON.Engine.TEXTURE_INVCUBIC_MODE;
  31973. /** Equirectangular coordinates mode */
  31974. Texture.EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_EQUIRECTANGULAR_MODE;
  31975. /** Equirectangular Fixed coordinates mode */
  31976. Texture.FIXED_EQUIRECTANGULAR_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MODE;
  31977. /** Equirectangular Fixed Mirrored coordinates mode */
  31978. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = BABYLON.Engine.TEXTURE_FIXED_EQUIRECTANGULAR_MIRRORED_MODE;
  31979. /** Texture is not repeating outside of 0..1 UVs */
  31980. Texture.CLAMP_ADDRESSMODE = BABYLON.Engine.TEXTURE_CLAMP_ADDRESSMODE;
  31981. /** Texture is repeating outside of 0..1 UVs */
  31982. Texture.WRAP_ADDRESSMODE = BABYLON.Engine.TEXTURE_WRAP_ADDRESSMODE;
  31983. /** Texture is repeating and mirrored */
  31984. Texture.MIRROR_ADDRESSMODE = BABYLON.Engine.TEXTURE_MIRROR_ADDRESSMODE;
  31985. /**
  31986. * 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
  31987. */
  31988. Texture.UseSerializedUrlIfAny = false;
  31989. __decorate([
  31990. BABYLON.serialize()
  31991. ], Texture.prototype, "url", void 0);
  31992. __decorate([
  31993. BABYLON.serialize()
  31994. ], Texture.prototype, "uOffset", void 0);
  31995. __decorate([
  31996. BABYLON.serialize()
  31997. ], Texture.prototype, "vOffset", void 0);
  31998. __decorate([
  31999. BABYLON.serialize()
  32000. ], Texture.prototype, "uScale", void 0);
  32001. __decorate([
  32002. BABYLON.serialize()
  32003. ], Texture.prototype, "vScale", void 0);
  32004. __decorate([
  32005. BABYLON.serialize()
  32006. ], Texture.prototype, "uAng", void 0);
  32007. __decorate([
  32008. BABYLON.serialize()
  32009. ], Texture.prototype, "vAng", void 0);
  32010. __decorate([
  32011. BABYLON.serialize()
  32012. ], Texture.prototype, "wAng", void 0);
  32013. __decorate([
  32014. BABYLON.serialize()
  32015. ], Texture.prototype, "uRotationCenter", void 0);
  32016. __decorate([
  32017. BABYLON.serialize()
  32018. ], Texture.prototype, "vRotationCenter", void 0);
  32019. __decorate([
  32020. BABYLON.serialize()
  32021. ], Texture.prototype, "wRotationCenter", void 0);
  32022. __decorate([
  32023. BABYLON.serialize()
  32024. ], Texture.prototype, "isBlocking", null);
  32025. return Texture;
  32026. }(BABYLON.BaseTexture));
  32027. BABYLON.Texture = Texture;
  32028. })(BABYLON || (BABYLON = {}));
  32029. //# sourceMappingURL=babylon.texture.js.map
  32030. var BABYLON;
  32031. (function (BABYLON) {
  32032. /**
  32033. * @hidden
  32034. **/
  32035. var _CreationDataStorage = /** @class */ (function () {
  32036. function _CreationDataStorage() {
  32037. }
  32038. return _CreationDataStorage;
  32039. }());
  32040. BABYLON._CreationDataStorage = _CreationDataStorage;
  32041. /**
  32042. * @hidden
  32043. **/
  32044. var _InstanceDataStorage = /** @class */ (function () {
  32045. function _InstanceDataStorage() {
  32046. this.visibleInstances = {};
  32047. this.renderIdForInstances = new Array();
  32048. this.batchCache = new _InstancesBatch();
  32049. this.instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  32050. }
  32051. return _InstanceDataStorage;
  32052. }());
  32053. /**
  32054. * @hidden
  32055. **/
  32056. var _InstancesBatch = /** @class */ (function () {
  32057. function _InstancesBatch() {
  32058. this.mustReturn = false;
  32059. this.visibleInstances = new Array();
  32060. this.renderSelf = new Array();
  32061. }
  32062. return _InstancesBatch;
  32063. }());
  32064. BABYLON._InstancesBatch = _InstancesBatch;
  32065. /**
  32066. * Class used to represent renderable models
  32067. */
  32068. var Mesh = /** @class */ (function (_super) {
  32069. __extends(Mesh, _super);
  32070. /**
  32071. * @constructor
  32072. * @param name The value used by scene.getMeshByName() to do a lookup.
  32073. * @param scene The scene to add this mesh to.
  32074. * @param parent The parent of this mesh, if it has one
  32075. * @param source An optional Mesh from which geometry is shared, cloned.
  32076. * @param doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  32077. * When false, achieved by calling a clone(), also passing False.
  32078. * This will make creation of children, recursive.
  32079. * @param clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  32080. */
  32081. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  32082. if (scene === void 0) { scene = null; }
  32083. if (parent === void 0) { parent = null; }
  32084. if (source === void 0) { source = null; }
  32085. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32086. var _this = _super.call(this, name, scene) || this;
  32087. // Members
  32088. /**
  32089. * Gets the delay loading state of the mesh (when delay loading is turned on)
  32090. * @see http://doc.babylonjs.com/how_to/using_the_incremental_loading_system
  32091. */
  32092. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  32093. /**
  32094. * Gets the list of instances created from this mesh
  32095. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  32096. */
  32097. _this.instances = new Array();
  32098. _this._LODLevels = new Array();
  32099. /** @hidden */
  32100. _this._instanceDataStorage = new _InstanceDataStorage();
  32101. // Use by builder only to know what orientation were the mesh build in.
  32102. /** @hidden */
  32103. _this._originalBuilderSideOrientation = Mesh.DEFAULTSIDE;
  32104. /**
  32105. * Use this property to change the original side orientation defined at construction time
  32106. */
  32107. _this.overrideMaterialSideOrientation = null;
  32108. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  32109. // Will be used to save a source mesh reference, If any
  32110. _this._source = null;
  32111. scene = _this.getScene();
  32112. if (source) {
  32113. // Geometry
  32114. if (source._geometry) {
  32115. source._geometry.applyToMesh(_this);
  32116. }
  32117. // Deep copy
  32118. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  32119. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen",
  32120. "onBeforeDrawObservable", "onBeforeRenderObservable", "onAfterRenderObservable", "onBeforeDraw"
  32121. ], ["_poseMatrix"]);
  32122. // Source mesh
  32123. _this._source = source;
  32124. // Construction Params
  32125. // Clone parameters allowing mesh to be updated in case of parametric shapes.
  32126. _this._originalBuilderSideOrientation = source._originalBuilderSideOrientation;
  32127. _this._creationDataStorage = source._creationDataStorage;
  32128. // Animation ranges
  32129. if (_this._source._ranges) {
  32130. var ranges = _this._source._ranges;
  32131. for (var name in ranges) {
  32132. if (!ranges.hasOwnProperty(name)) {
  32133. continue;
  32134. }
  32135. if (!ranges[name]) {
  32136. continue;
  32137. }
  32138. _this.createAnimationRange(name, ranges[name].from, ranges[name].to);
  32139. }
  32140. }
  32141. // Metadata
  32142. if (source.metadata && source.metadata.clone) {
  32143. _this.metadata = source.metadata.clone();
  32144. }
  32145. else {
  32146. _this.metadata = source.metadata;
  32147. }
  32148. // Tags
  32149. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  32150. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  32151. }
  32152. // Parent
  32153. _this.parent = source.parent;
  32154. // Pivot
  32155. _this.setPivotMatrix(source.getPivotMatrix());
  32156. _this.id = name + "." + source.id;
  32157. // Material
  32158. _this.material = source.material;
  32159. var index;
  32160. if (!doNotCloneChildren) {
  32161. // Children
  32162. var directDescendants = source.getDescendants(true);
  32163. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  32164. var child = directDescendants[index_1];
  32165. if (child.clone) {
  32166. child.clone(name + "." + child.name, _this);
  32167. }
  32168. }
  32169. }
  32170. // Physics clone
  32171. var physicsEngine = _this.getScene().getPhysicsEngine();
  32172. if (clonePhysicsImpostor && physicsEngine) {
  32173. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  32174. if (impostor) {
  32175. _this.physicsImpostor = impostor.clone(_this);
  32176. }
  32177. }
  32178. // Particles
  32179. for (index = 0; index < scene.particleSystems.length; index++) {
  32180. var system = scene.particleSystems[index];
  32181. if (system.emitter === source) {
  32182. system.clone(system.name, _this);
  32183. }
  32184. }
  32185. _this.refreshBoundingInfo();
  32186. _this.computeWorldMatrix(true);
  32187. }
  32188. // Parent
  32189. if (parent !== null) {
  32190. _this.parent = parent;
  32191. }
  32192. return _this;
  32193. }
  32194. Object.defineProperty(Mesh.prototype, "onBeforeRenderObservable", {
  32195. /**
  32196. * An event triggered before rendering the mesh
  32197. */
  32198. get: function () {
  32199. if (!this._onBeforeRenderObservable) {
  32200. this._onBeforeRenderObservable = new BABYLON.Observable();
  32201. }
  32202. return this._onBeforeRenderObservable;
  32203. },
  32204. enumerable: true,
  32205. configurable: true
  32206. });
  32207. Object.defineProperty(Mesh.prototype, "onAfterRenderObservable", {
  32208. /**
  32209. * An event triggered after rendering the mesh
  32210. */
  32211. get: function () {
  32212. if (!this._onAfterRenderObservable) {
  32213. this._onAfterRenderObservable = new BABYLON.Observable();
  32214. }
  32215. return this._onAfterRenderObservable;
  32216. },
  32217. enumerable: true,
  32218. configurable: true
  32219. });
  32220. Object.defineProperty(Mesh.prototype, "onBeforeDrawObservable", {
  32221. /**
  32222. * An event triggered before drawing the mesh
  32223. */
  32224. get: function () {
  32225. if (!this._onBeforeDrawObservable) {
  32226. this._onBeforeDrawObservable = new BABYLON.Observable();
  32227. }
  32228. return this._onBeforeDrawObservable;
  32229. },
  32230. enumerable: true,
  32231. configurable: true
  32232. });
  32233. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  32234. /**
  32235. * Sets a callback to call before drawing the mesh. It is recommended to use onBeforeDrawObservable instead
  32236. */
  32237. set: function (callback) {
  32238. if (this._onBeforeDrawObserver) {
  32239. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  32240. }
  32241. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  32242. },
  32243. enumerable: true,
  32244. configurable: true
  32245. });
  32246. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  32247. /**
  32248. * Gets or sets the morph target manager
  32249. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  32250. */
  32251. get: function () {
  32252. return this._morphTargetManager;
  32253. },
  32254. set: function (value) {
  32255. if (this._morphTargetManager === value) {
  32256. return;
  32257. }
  32258. this._morphTargetManager = value;
  32259. this._syncGeometryWithMorphTargetManager();
  32260. },
  32261. enumerable: true,
  32262. configurable: true
  32263. });
  32264. Object.defineProperty(Mesh.prototype, "source", {
  32265. /**
  32266. * Gets the source mesh (the one used to clone this one from)
  32267. */
  32268. get: function () {
  32269. return this._source;
  32270. },
  32271. enumerable: true,
  32272. configurable: true
  32273. });
  32274. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  32275. /**
  32276. * Gets or sets a boolean indicating that this mesh does not use index buffer
  32277. */
  32278. get: function () {
  32279. return this._unIndexed;
  32280. },
  32281. set: function (value) {
  32282. if (this._unIndexed !== value) {
  32283. this._unIndexed = value;
  32284. this._markSubMeshesAsAttributesDirty();
  32285. }
  32286. },
  32287. enumerable: true,
  32288. configurable: true
  32289. });
  32290. // Methods
  32291. /**
  32292. * Gets the class name
  32293. * @returns the string "Mesh".
  32294. */
  32295. Mesh.prototype.getClassName = function () {
  32296. return "Mesh";
  32297. };
  32298. /**
  32299. * Returns a description of this mesh
  32300. * @param fullDetails define if full details about this mesh must be used
  32301. * @returns a descriptive string representing this mesh
  32302. */
  32303. Mesh.prototype.toString = function (fullDetails) {
  32304. var ret = _super.prototype.toString.call(this, fullDetails);
  32305. ret += ", n vertices: " + this.getTotalVertices();
  32306. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  32307. if (this.animations) {
  32308. for (var i = 0; i < this.animations.length; i++) {
  32309. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  32310. }
  32311. }
  32312. if (fullDetails) {
  32313. if (this._geometry) {
  32314. var ib = this.getIndices();
  32315. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32316. if (vb && ib) {
  32317. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  32318. }
  32319. }
  32320. else {
  32321. ret += ", flat shading: UNKNOWN";
  32322. }
  32323. }
  32324. return ret;
  32325. };
  32326. /** @hidden */
  32327. Mesh.prototype._unBindEffect = function () {
  32328. _super.prototype._unBindEffect.call(this);
  32329. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  32330. var instance = _a[_i];
  32331. instance._unBindEffect();
  32332. }
  32333. };
  32334. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  32335. /**
  32336. * Gets a boolean indicating if this mesh has LOD
  32337. */
  32338. get: function () {
  32339. return this._LODLevels.length > 0;
  32340. },
  32341. enumerable: true,
  32342. configurable: true
  32343. });
  32344. /**
  32345. * Gets the list of MeshLODLevel associated with the current mesh
  32346. * @returns an array of MeshLODLevel
  32347. */
  32348. Mesh.prototype.getLODLevels = function () {
  32349. return this._LODLevels;
  32350. };
  32351. Mesh.prototype._sortLODLevels = function () {
  32352. this._LODLevels.sort(function (a, b) {
  32353. if (a.distance < b.distance) {
  32354. return 1;
  32355. }
  32356. if (a.distance > b.distance) {
  32357. return -1;
  32358. }
  32359. return 0;
  32360. });
  32361. };
  32362. /**
  32363. * Add a mesh as LOD level triggered at the given distance.
  32364. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32365. * @param distance The distance from the center of the object to show this level
  32366. * @param mesh The mesh to be added as LOD level (can be null)
  32367. * @return This mesh (for chaining)
  32368. */
  32369. Mesh.prototype.addLODLevel = function (distance, mesh) {
  32370. if (mesh && mesh._masterMesh) {
  32371. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  32372. return this;
  32373. }
  32374. var level = new BABYLON.MeshLODLevel(distance, mesh);
  32375. this._LODLevels.push(level);
  32376. if (mesh) {
  32377. mesh._masterMesh = this;
  32378. }
  32379. this._sortLODLevels();
  32380. return this;
  32381. };
  32382. /**
  32383. * Returns the LOD level mesh at the passed distance or null if not found.
  32384. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32385. * @param distance The distance from the center of the object to show this level
  32386. * @returns a Mesh or `null`
  32387. */
  32388. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  32389. for (var index = 0; index < this._LODLevels.length; index++) {
  32390. var level = this._LODLevels[index];
  32391. if (level.distance === distance) {
  32392. return level.mesh;
  32393. }
  32394. }
  32395. return null;
  32396. };
  32397. /**
  32398. * Remove a mesh from the LOD array
  32399. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32400. * @param mesh defines the mesh to be removed
  32401. * @return This mesh (for chaining)
  32402. */
  32403. Mesh.prototype.removeLODLevel = function (mesh) {
  32404. for (var index = 0; index < this._LODLevels.length; index++) {
  32405. if (this._LODLevels[index].mesh === mesh) {
  32406. this._LODLevels.splice(index, 1);
  32407. if (mesh) {
  32408. mesh._masterMesh = null;
  32409. }
  32410. }
  32411. }
  32412. this._sortLODLevels();
  32413. return this;
  32414. };
  32415. /**
  32416. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  32417. * @see https://doc.babylonjs.com/how_to/how_to_use_lod
  32418. * @param camera defines the camera to use to compute distance
  32419. * @param boundingSphere defines a custom bounding sphere to use instead of the one from this mesh
  32420. * @return This mesh (for chaining)
  32421. */
  32422. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  32423. if (!this._LODLevels || this._LODLevels.length === 0) {
  32424. return this;
  32425. }
  32426. var bSphere;
  32427. if (boundingSphere) {
  32428. bSphere = boundingSphere;
  32429. }
  32430. else {
  32431. var boundingInfo = this.getBoundingInfo();
  32432. bSphere = boundingInfo.boundingSphere;
  32433. }
  32434. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  32435. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  32436. if (this.onLODLevelSelection) {
  32437. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  32438. }
  32439. return this;
  32440. }
  32441. for (var index = 0; index < this._LODLevels.length; index++) {
  32442. var level = this._LODLevels[index];
  32443. if (level.distance < distanceToCamera) {
  32444. if (level.mesh) {
  32445. level.mesh._preActivate();
  32446. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  32447. }
  32448. if (this.onLODLevelSelection) {
  32449. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  32450. }
  32451. return level.mesh;
  32452. }
  32453. }
  32454. if (this.onLODLevelSelection) {
  32455. this.onLODLevelSelection(distanceToCamera, this, this);
  32456. }
  32457. return this;
  32458. };
  32459. Object.defineProperty(Mesh.prototype, "geometry", {
  32460. /**
  32461. * Gets the mesh internal Geometry object
  32462. */
  32463. get: function () {
  32464. return this._geometry;
  32465. },
  32466. enumerable: true,
  32467. configurable: true
  32468. });
  32469. /**
  32470. * Returns the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32471. * @returns the total number of vertices
  32472. */
  32473. Mesh.prototype.getTotalVertices = function () {
  32474. if (this._geometry === null || this._geometry === undefined) {
  32475. return 0;
  32476. }
  32477. return this._geometry.getTotalVertices();
  32478. };
  32479. /**
  32480. * Returns the content of an associated vertex buffer
  32481. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32482. * - BABYLON.VertexBuffer.PositionKind
  32483. * - BABYLON.VertexBuffer.UVKind
  32484. * - BABYLON.VertexBuffer.UV2Kind
  32485. * - BABYLON.VertexBuffer.UV3Kind
  32486. * - BABYLON.VertexBuffer.UV4Kind
  32487. * - BABYLON.VertexBuffer.UV5Kind
  32488. * - BABYLON.VertexBuffer.UV6Kind
  32489. * - BABYLON.VertexBuffer.ColorKind
  32490. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32491. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32492. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32493. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32494. * @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
  32495. * @param forceCopy defines a boolean forcing the copy of the buffer no matter what the value of copyWhenShared is
  32496. * @returns a FloatArray or null if the mesh has no geometry or no vertex buffer for this kind.
  32497. */
  32498. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32499. if (!this._geometry) {
  32500. return null;
  32501. }
  32502. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32503. };
  32504. /**
  32505. * Returns the mesh VertexBuffer object from the requested `kind`
  32506. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32507. * - BABYLON.VertexBuffer.PositionKind
  32508. * - BABYLON.VertexBuffer.UVKind
  32509. * - BABYLON.VertexBuffer.UV2Kind
  32510. * - BABYLON.VertexBuffer.UV3Kind
  32511. * - BABYLON.VertexBuffer.UV4Kind
  32512. * - BABYLON.VertexBuffer.UV5Kind
  32513. * - BABYLON.VertexBuffer.UV6Kind
  32514. * - BABYLON.VertexBuffer.ColorKind
  32515. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32516. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32517. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32518. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32519. * @returns a FloatArray or null if the mesh has no vertex buffer for this kind.
  32520. */
  32521. Mesh.prototype.getVertexBuffer = function (kind) {
  32522. if (!this._geometry) {
  32523. return null;
  32524. }
  32525. return this._geometry.getVertexBuffer(kind);
  32526. };
  32527. /**
  32528. * Tests if a specific vertex buffer is associated with this mesh
  32529. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32530. * - BABYLON.VertexBuffer.PositionKind
  32531. * - BABYLON.VertexBuffer.UVKind
  32532. * - BABYLON.VertexBuffer.UV2Kind
  32533. * - BABYLON.VertexBuffer.UV3Kind
  32534. * - BABYLON.VertexBuffer.UV4Kind
  32535. * - BABYLON.VertexBuffer.UV5Kind
  32536. * - BABYLON.VertexBuffer.UV6Kind
  32537. * - BABYLON.VertexBuffer.ColorKind
  32538. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32539. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32540. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32541. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32542. * @returns a boolean
  32543. */
  32544. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32545. if (!this._geometry) {
  32546. if (this._delayInfo) {
  32547. return this._delayInfo.indexOf(kind) !== -1;
  32548. }
  32549. return false;
  32550. }
  32551. return this._geometry.isVerticesDataPresent(kind);
  32552. };
  32553. /**
  32554. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32555. * @param kind defines which buffer to check (positions, indices, normals, etc). Possible `kind` values :
  32556. * - BABYLON.VertexBuffer.PositionKind
  32557. * - BABYLON.VertexBuffer.UVKind
  32558. * - BABYLON.VertexBuffer.UV2Kind
  32559. * - BABYLON.VertexBuffer.UV3Kind
  32560. * - BABYLON.VertexBuffer.UV4Kind
  32561. * - BABYLON.VertexBuffer.UV5Kind
  32562. * - BABYLON.VertexBuffer.UV6Kind
  32563. * - BABYLON.VertexBuffer.ColorKind
  32564. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32565. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32566. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32567. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32568. * @returns a boolean
  32569. */
  32570. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32571. if (!this._geometry) {
  32572. if (this._delayInfo) {
  32573. return this._delayInfo.indexOf(kind) !== -1;
  32574. }
  32575. return false;
  32576. }
  32577. return this._geometry.isVertexBufferUpdatable(kind);
  32578. };
  32579. /**
  32580. * Returns a string which contains the list of existing `kinds` of Vertex Data associated with this mesh.
  32581. * @param kind defines which buffer to read from (positions, indices, normals, etc). Possible `kind` values :
  32582. * - BABYLON.VertexBuffer.PositionKind
  32583. * - BABYLON.VertexBuffer.UVKind
  32584. * - BABYLON.VertexBuffer.UV2Kind
  32585. * - BABYLON.VertexBuffer.UV3Kind
  32586. * - BABYLON.VertexBuffer.UV4Kind
  32587. * - BABYLON.VertexBuffer.UV5Kind
  32588. * - BABYLON.VertexBuffer.UV6Kind
  32589. * - BABYLON.VertexBuffer.ColorKind
  32590. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32591. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32592. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32593. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32594. * @returns an array of strings
  32595. */
  32596. Mesh.prototype.getVerticesDataKinds = function () {
  32597. if (!this._geometry) {
  32598. var result = new Array();
  32599. if (this._delayInfo) {
  32600. this._delayInfo.forEach(function (kind, index, array) {
  32601. result.push(kind);
  32602. });
  32603. }
  32604. return result;
  32605. }
  32606. return this._geometry.getVerticesDataKinds();
  32607. };
  32608. /**
  32609. * Returns a positive integer : the total number of indices in this mesh geometry.
  32610. * @returns the numner of indices or zero if the mesh has no geometry.
  32611. */
  32612. Mesh.prototype.getTotalIndices = function () {
  32613. if (!this._geometry) {
  32614. return 0;
  32615. }
  32616. return this._geometry.getTotalIndices();
  32617. };
  32618. /**
  32619. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32620. * @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.
  32621. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  32622. * @returns the indices array or an empty array if the mesh has no geometry
  32623. */
  32624. Mesh.prototype.getIndices = function (copyWhenShared, forceCopy) {
  32625. if (!this._geometry) {
  32626. return [];
  32627. }
  32628. return this._geometry.getIndices(copyWhenShared, forceCopy);
  32629. };
  32630. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32631. get: function () {
  32632. return this._masterMesh !== null && this._masterMesh !== undefined;
  32633. },
  32634. enumerable: true,
  32635. configurable: true
  32636. });
  32637. /**
  32638. * Determine if the current mesh is ready to be rendered
  32639. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32640. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32641. * @returns true if all associated assets are ready (material, textures, shaders)
  32642. */
  32643. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32644. if (completeCheck === void 0) { completeCheck = false; }
  32645. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32646. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32647. return false;
  32648. }
  32649. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32650. return false;
  32651. }
  32652. if (!this.subMeshes || this.subMeshes.length === 0) {
  32653. return true;
  32654. }
  32655. if (!completeCheck) {
  32656. return true;
  32657. }
  32658. var engine = this.getEngine();
  32659. var scene = this.getScene();
  32660. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32661. this.computeWorldMatrix();
  32662. var mat = this.material || scene.defaultMaterial;
  32663. if (mat) {
  32664. if (mat.storeEffectOnSubMeshes) {
  32665. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32666. var subMesh = _a[_i];
  32667. var effectiveMaterial = subMesh.getMaterial();
  32668. if (effectiveMaterial) {
  32669. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32670. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32671. return false;
  32672. }
  32673. }
  32674. else {
  32675. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32676. return false;
  32677. }
  32678. }
  32679. }
  32680. }
  32681. }
  32682. else {
  32683. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32684. return false;
  32685. }
  32686. }
  32687. }
  32688. // Shadows
  32689. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32690. var light = _c[_b];
  32691. var generator = light.getShadowGenerator();
  32692. if (generator) {
  32693. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32694. var subMesh = _e[_d];
  32695. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32696. return false;
  32697. }
  32698. }
  32699. }
  32700. }
  32701. // LOD
  32702. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32703. var lod = _g[_f];
  32704. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32705. return false;
  32706. }
  32707. }
  32708. return true;
  32709. };
  32710. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32711. /**
  32712. * 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.
  32713. */
  32714. get: function () {
  32715. return this._areNormalsFrozen;
  32716. },
  32717. enumerable: true,
  32718. configurable: true
  32719. });
  32720. /**
  32721. * 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.
  32722. * @returns the current mesh
  32723. */
  32724. Mesh.prototype.freezeNormals = function () {
  32725. this._areNormalsFrozen = true;
  32726. return this;
  32727. };
  32728. /**
  32729. * 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
  32730. * @returns the current mesh
  32731. */
  32732. Mesh.prototype.unfreezeNormals = function () {
  32733. this._areNormalsFrozen = false;
  32734. return this;
  32735. };
  32736. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32737. /**
  32738. * Sets a value overriding the instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32739. */
  32740. set: function (count) {
  32741. this._instanceDataStorage.overridenInstanceCount = count;
  32742. },
  32743. enumerable: true,
  32744. configurable: true
  32745. });
  32746. // Methods
  32747. /** @hidden */
  32748. Mesh.prototype._preActivate = function () {
  32749. var sceneRenderId = this.getScene().getRenderId();
  32750. if (this._preActivateId === sceneRenderId) {
  32751. return this;
  32752. }
  32753. this._preActivateId = sceneRenderId;
  32754. this._instanceDataStorage.visibleInstances = null;
  32755. return this;
  32756. };
  32757. /** @hidden */
  32758. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32759. if (this._instanceDataStorage.visibleInstances) {
  32760. this._instanceDataStorage.visibleInstances.intermediateDefaultRenderId = renderId;
  32761. }
  32762. return this;
  32763. };
  32764. /** @hidden */
  32765. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32766. if (!this._instanceDataStorage.visibleInstances) {
  32767. this._instanceDataStorage.visibleInstances = {};
  32768. this._instanceDataStorage.visibleInstances.defaultRenderId = renderId;
  32769. this._instanceDataStorage.visibleInstances.selfDefaultRenderId = this._renderId;
  32770. }
  32771. if (!this._instanceDataStorage.visibleInstances[renderId]) {
  32772. this._instanceDataStorage.visibleInstances[renderId] = new Array();
  32773. }
  32774. this._instanceDataStorage.visibleInstances[renderId].push(instance);
  32775. return this;
  32776. };
  32777. /**
  32778. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32779. * This means the mesh underlying bounding box and sphere are recomputed.
  32780. * @returns the current mesh
  32781. */
  32782. Mesh.prototype.refreshBoundingInfo = function () {
  32783. return this._refreshBoundingInfo(false);
  32784. };
  32785. /** @hidden */
  32786. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32787. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32788. return this;
  32789. }
  32790. var data = this._getPositionData(applySkeleton);
  32791. if (data) {
  32792. var bias = this.geometry ? this.geometry.boundingBias : null;
  32793. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices(), bias);
  32794. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32795. }
  32796. if (this.subMeshes) {
  32797. for (var index = 0; index < this.subMeshes.length; index++) {
  32798. this.subMeshes[index].refreshBoundingInfo();
  32799. }
  32800. }
  32801. this._updateBoundingInfo();
  32802. return this;
  32803. };
  32804. Mesh.prototype._getPositionData = function (applySkeleton) {
  32805. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32806. if (data && applySkeleton && this.skeleton) {
  32807. data = BABYLON.Tools.Slice(data);
  32808. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32809. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32810. if (matricesWeightsData && matricesIndicesData) {
  32811. var needExtras = this.numBoneInfluencers > 4;
  32812. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32813. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32814. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32815. var tempVector = BABYLON.Tmp.Vector3[0];
  32816. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32817. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32818. var matWeightIdx = 0;
  32819. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32820. finalMatrix.reset();
  32821. var inf;
  32822. var weight;
  32823. for (inf = 0; inf < 4; inf++) {
  32824. weight = matricesWeightsData[matWeightIdx + inf];
  32825. if (weight > 0) {
  32826. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32827. finalMatrix.addToSelf(tempMatrix);
  32828. }
  32829. }
  32830. if (needExtras) {
  32831. for (inf = 0; inf < 4; inf++) {
  32832. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32833. if (weight > 0) {
  32834. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32835. finalMatrix.addToSelf(tempMatrix);
  32836. }
  32837. }
  32838. }
  32839. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32840. tempVector.toArray(data, index);
  32841. }
  32842. }
  32843. }
  32844. return data;
  32845. };
  32846. /** @hidden */
  32847. Mesh.prototype._createGlobalSubMesh = function (force) {
  32848. var totalVertices = this.getTotalVertices();
  32849. if (!totalVertices || !this.getIndices()) {
  32850. return null;
  32851. }
  32852. // Check if we need to recreate the submeshes
  32853. if (this.subMeshes && this.subMeshes.length > 0) {
  32854. var ib = this.getIndices();
  32855. if (!ib) {
  32856. return null;
  32857. }
  32858. var totalIndices = ib.length;
  32859. var needToRecreate = false;
  32860. if (force) {
  32861. needToRecreate = true;
  32862. }
  32863. else {
  32864. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32865. var submesh = _a[_i];
  32866. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32867. needToRecreate = true;
  32868. break;
  32869. }
  32870. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32871. needToRecreate = true;
  32872. break;
  32873. }
  32874. }
  32875. }
  32876. if (!needToRecreate) {
  32877. return this.subMeshes[0];
  32878. }
  32879. }
  32880. this.releaseSubMeshes();
  32881. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32882. };
  32883. /**
  32884. * This function will subdivide the mesh into multiple submeshes
  32885. * @param count defines the expected number of submeshes
  32886. */
  32887. Mesh.prototype.subdivide = function (count) {
  32888. if (count < 1) {
  32889. return;
  32890. }
  32891. var totalIndices = this.getTotalIndices();
  32892. var subdivisionSize = (totalIndices / count) | 0;
  32893. var offset = 0;
  32894. // Ensure that subdivisionSize is a multiple of 3
  32895. while (subdivisionSize % 3 !== 0) {
  32896. subdivisionSize++;
  32897. }
  32898. this.releaseSubMeshes();
  32899. for (var index = 0; index < count; index++) {
  32900. if (offset >= totalIndices) {
  32901. break;
  32902. }
  32903. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32904. offset += subdivisionSize;
  32905. }
  32906. this.synchronizeInstances();
  32907. };
  32908. /**
  32909. * Copy a FloatArray into a specific associated vertex buffer
  32910. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32911. * - BABYLON.VertexBuffer.PositionKind
  32912. * - BABYLON.VertexBuffer.UVKind
  32913. * - BABYLON.VertexBuffer.UV2Kind
  32914. * - BABYLON.VertexBuffer.UV3Kind
  32915. * - BABYLON.VertexBuffer.UV4Kind
  32916. * - BABYLON.VertexBuffer.UV5Kind
  32917. * - BABYLON.VertexBuffer.UV6Kind
  32918. * - BABYLON.VertexBuffer.ColorKind
  32919. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32920. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32921. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32922. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32923. * @param data defines the data source
  32924. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32925. * @param stride defines the data stride size (can be null)
  32926. * @returns the current mesh
  32927. */
  32928. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32929. if (updatable === void 0) { updatable = false; }
  32930. if (!this._geometry) {
  32931. var vertexData = new BABYLON.VertexData();
  32932. vertexData.set(data, kind);
  32933. var scene = this.getScene();
  32934. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32935. }
  32936. else {
  32937. this._geometry.setVerticesData(kind, data, updatable, stride);
  32938. }
  32939. return this;
  32940. };
  32941. /**
  32942. * Flags an associated vertex buffer as updatable
  32943. * @param kind defines which buffer to use (positions, indices, normals, etc). Possible `kind` values :
  32944. * - BABYLON.VertexBuffer.PositionKind
  32945. * - BABYLON.VertexBuffer.UVKind
  32946. * - BABYLON.VertexBuffer.UV2Kind
  32947. * - BABYLON.VertexBuffer.UV3Kind
  32948. * - BABYLON.VertexBuffer.UV4Kind
  32949. * - BABYLON.VertexBuffer.UV5Kind
  32950. * - BABYLON.VertexBuffer.UV6Kind
  32951. * - BABYLON.VertexBuffer.ColorKind
  32952. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32953. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32954. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32955. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32956. * @param updatable defines if the updated vertex buffer must be flagged as updatable
  32957. */
  32958. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32959. if (updatable === void 0) { updatable = true; }
  32960. var vb = this.getVertexBuffer(kind);
  32961. if (!vb || vb.isUpdatable() === updatable) {
  32962. return;
  32963. }
  32964. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32965. };
  32966. /**
  32967. * Sets the mesh global Vertex Buffer
  32968. * @param buffer defines the buffer to use
  32969. * @returns the current mesh
  32970. */
  32971. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32972. if (!this._geometry) {
  32973. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32974. }
  32975. this._geometry.setVerticesBuffer(buffer);
  32976. return this;
  32977. };
  32978. /**
  32979. * Update a specific associated vertex buffer
  32980. * @param kind defines which buffer to write to (positions, indices, normals, etc). Possible `kind` values :
  32981. * - BABYLON.VertexBuffer.PositionKind
  32982. * - BABYLON.VertexBuffer.UVKind
  32983. * - BABYLON.VertexBuffer.UV2Kind
  32984. * - BABYLON.VertexBuffer.UV3Kind
  32985. * - BABYLON.VertexBuffer.UV4Kind
  32986. * - BABYLON.VertexBuffer.UV5Kind
  32987. * - BABYLON.VertexBuffer.UV6Kind
  32988. * - BABYLON.VertexBuffer.ColorKind
  32989. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32990. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32991. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32992. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32993. * @param data defines the data source
  32994. * @param updateExtends defines if extends info of the mesh must be updated (can be null). This is mostly useful for "position" kind
  32995. * @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)
  32996. * @returns the current mesh
  32997. */
  32998. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32999. if (!this._geometry) {
  33000. return this;
  33001. }
  33002. if (!makeItUnique) {
  33003. this._geometry.updateVerticesData(kind, data, updateExtends);
  33004. }
  33005. else {
  33006. this.makeGeometryUnique();
  33007. this.updateVerticesData(kind, data, updateExtends, false);
  33008. }
  33009. return this;
  33010. };
  33011. /**
  33012. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  33013. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  33014. * @param positionFunction is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything
  33015. * @param computeNormals is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update
  33016. * @returns the current mesh
  33017. */
  33018. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  33019. if (computeNormals === void 0) { computeNormals = true; }
  33020. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33021. if (!positions) {
  33022. return this;
  33023. }
  33024. positionFunction(positions);
  33025. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  33026. if (computeNormals) {
  33027. var indices = this.getIndices();
  33028. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33029. if (!normals) {
  33030. return this;
  33031. }
  33032. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  33033. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  33034. }
  33035. return this;
  33036. };
  33037. /**
  33038. * Creates a un-shared specific occurence of the geometry for the mesh.
  33039. * @returns the current mesh
  33040. */
  33041. Mesh.prototype.makeGeometryUnique = function () {
  33042. if (!this._geometry) {
  33043. return this;
  33044. }
  33045. var oldGeometry = this._geometry;
  33046. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  33047. oldGeometry.releaseForMesh(this, true);
  33048. geometry.applyToMesh(this);
  33049. return this;
  33050. };
  33051. /**
  33052. * Set the index buffer of this mesh
  33053. * @param indices defines the source data
  33054. * @param totalVertices defines the total number of vertices referenced by this index data (can be null)
  33055. * @param updatable defines if the updated index buffer must be flagged as updatable (default is false)
  33056. * @returns the current mesh
  33057. */
  33058. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  33059. if (totalVertices === void 0) { totalVertices = null; }
  33060. if (updatable === void 0) { updatable = false; }
  33061. if (!this._geometry) {
  33062. var vertexData = new BABYLON.VertexData();
  33063. vertexData.indices = indices;
  33064. var scene = this.getScene();
  33065. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  33066. }
  33067. else {
  33068. this._geometry.setIndices(indices, totalVertices, updatable);
  33069. }
  33070. return this;
  33071. };
  33072. /**
  33073. * Update the current index buffer
  33074. * @param indices defines the source data
  33075. * @param offset defines the offset in the index buffer where to store the new data (can be null)
  33076. * @returns the current mesh
  33077. */
  33078. Mesh.prototype.updateIndices = function (indices, offset) {
  33079. if (!this._geometry) {
  33080. return this;
  33081. }
  33082. this._geometry.updateIndices(indices, offset);
  33083. return this;
  33084. };
  33085. /**
  33086. * Invert the geometry to move from a right handed system to a left handed one.
  33087. * @returns the current mesh
  33088. */
  33089. Mesh.prototype.toLeftHanded = function () {
  33090. if (!this._geometry) {
  33091. return this;
  33092. }
  33093. this._geometry.toLeftHanded();
  33094. return this;
  33095. };
  33096. /** @hidden */
  33097. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  33098. if (!this._geometry) {
  33099. return this;
  33100. }
  33101. var engine = this.getScene().getEngine();
  33102. // Wireframe
  33103. var indexToBind;
  33104. if (this._unIndexed) {
  33105. indexToBind = null;
  33106. }
  33107. else {
  33108. switch (fillMode) {
  33109. case BABYLON.Material.PointFillMode:
  33110. indexToBind = null;
  33111. break;
  33112. case BABYLON.Material.WireFrameFillMode:
  33113. indexToBind = subMesh._getLinesIndexBuffer(this.getIndices(), engine);
  33114. break;
  33115. default:
  33116. case BABYLON.Material.TriangleFillMode:
  33117. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  33118. break;
  33119. }
  33120. }
  33121. // VBOs
  33122. this._geometry._bind(effect, indexToBind);
  33123. return this;
  33124. };
  33125. /** @hidden */
  33126. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  33127. if (alternate === void 0) { alternate = false; }
  33128. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33129. return this;
  33130. }
  33131. if (this._onBeforeDrawObservable) {
  33132. this._onBeforeDrawObservable.notifyObservers(this);
  33133. }
  33134. var scene = this.getScene();
  33135. var engine = scene.getEngine();
  33136. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  33137. // or triangles as points
  33138. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  33139. }
  33140. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  33141. // Triangles as wireframe
  33142. engine.drawElementsType(fillMode, 0, subMesh._linesIndexCount, instancesCount);
  33143. }
  33144. else {
  33145. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  33146. }
  33147. if (scene._isAlternateRenderingEnabled && !alternate) {
  33148. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  33149. if (!effect || !scene.activeCamera) {
  33150. return this;
  33151. }
  33152. scene._switchToAlternateCameraConfiguration(true);
  33153. this._effectiveMaterial.bindView(effect);
  33154. this._effectiveMaterial.bindViewProjection(effect);
  33155. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  33156. this._draw(subMesh, fillMode, instancesCount, true);
  33157. engine.setViewport(scene.activeCamera.viewport);
  33158. scene._switchToAlternateCameraConfiguration(false);
  33159. this._effectiveMaterial.bindView(effect);
  33160. this._effectiveMaterial.bindViewProjection(effect);
  33161. }
  33162. return this;
  33163. };
  33164. /**
  33165. * Registers for this mesh a javascript function called just before the rendering process
  33166. * @param func defines the function to call before rendering this mesh
  33167. * @returns the current mesh
  33168. */
  33169. Mesh.prototype.registerBeforeRender = function (func) {
  33170. this.onBeforeRenderObservable.add(func);
  33171. return this;
  33172. };
  33173. /**
  33174. * Disposes a previously registered javascript function called before the rendering
  33175. * @param func defines the function to remove
  33176. * @returns the current mesh
  33177. */
  33178. Mesh.prototype.unregisterBeforeRender = function (func) {
  33179. this.onBeforeRenderObservable.removeCallback(func);
  33180. return this;
  33181. };
  33182. /**
  33183. * Registers for this mesh a javascript function called just after the rendering is complete
  33184. * @param func defines the function to call after rendering this mesh
  33185. * @returns the current mesh
  33186. */
  33187. Mesh.prototype.registerAfterRender = function (func) {
  33188. this.onAfterRenderObservable.add(func);
  33189. return this;
  33190. };
  33191. /**
  33192. * Disposes a previously registered javascript function called after the rendering.
  33193. * @param func defines the function to remove
  33194. * @returns the current mesh
  33195. */
  33196. Mesh.prototype.unregisterAfterRender = function (func) {
  33197. this.onAfterRenderObservable.removeCallback(func);
  33198. return this;
  33199. };
  33200. /** @hidden */
  33201. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  33202. var scene = this.getScene();
  33203. var batchCache = this._instanceDataStorage.batchCache;
  33204. batchCache.mustReturn = false;
  33205. batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  33206. batchCache.visibleInstances[subMeshId] = null;
  33207. if (this._instanceDataStorage.visibleInstances) {
  33208. var visibleInstances = this._instanceDataStorage.visibleInstances;
  33209. var currentRenderId = scene.getRenderId();
  33210. var defaultRenderId = (scene._isInIntermediateRendering() ? visibleInstances.intermediateDefaultRenderId : visibleInstances.defaultRenderId);
  33211. batchCache.visibleInstances[subMeshId] = visibleInstances[currentRenderId];
  33212. var selfRenderId = this._renderId;
  33213. if (!batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  33214. batchCache.visibleInstances[subMeshId] = visibleInstances[defaultRenderId];
  33215. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  33216. selfRenderId = Math.max(visibleInstances.selfDefaultRenderId, currentRenderId);
  33217. }
  33218. var visibleInstancesForSubMesh = batchCache.visibleInstances[subMeshId];
  33219. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  33220. if (this._instanceDataStorage.renderIdForInstances[subMeshId] === currentRenderId) {
  33221. batchCache.mustReturn = true;
  33222. return batchCache;
  33223. }
  33224. if (currentRenderId !== selfRenderId) {
  33225. batchCache.renderSelf[subMeshId] = false;
  33226. }
  33227. }
  33228. this._instanceDataStorage.renderIdForInstances[subMeshId] = currentRenderId;
  33229. }
  33230. return batchCache;
  33231. };
  33232. /** @hidden */
  33233. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  33234. var visibleInstances = batch.visibleInstances[subMesh._id];
  33235. if (!visibleInstances) {
  33236. return this;
  33237. }
  33238. var matricesCount = visibleInstances.length + 1;
  33239. var bufferSize = matricesCount * 16 * 4;
  33240. var instanceStorage = this._instanceDataStorage;
  33241. var currentInstancesBufferSize = instanceStorage.instancesBufferSize;
  33242. var instancesBuffer = instanceStorage.instancesBuffer;
  33243. while (instanceStorage.instancesBufferSize < bufferSize) {
  33244. instanceStorage.instancesBufferSize *= 2;
  33245. }
  33246. if (!instanceStorage.instancesData || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33247. instanceStorage.instancesData = new Float32Array(instanceStorage.instancesBufferSize / 4);
  33248. }
  33249. var offset = 0;
  33250. var instancesCount = 0;
  33251. var world = this.getWorldMatrix();
  33252. if (batch.renderSelf[subMesh._id]) {
  33253. world.copyToArray(instanceStorage.instancesData, offset);
  33254. offset += 16;
  33255. instancesCount++;
  33256. }
  33257. if (visibleInstances) {
  33258. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  33259. var instance = visibleInstances[instanceIndex];
  33260. instance.getWorldMatrix().copyToArray(instanceStorage.instancesData, offset);
  33261. offset += 16;
  33262. instancesCount++;
  33263. }
  33264. }
  33265. if (!instancesBuffer || currentInstancesBufferSize != instanceStorage.instancesBufferSize) {
  33266. if (instancesBuffer) {
  33267. instancesBuffer.dispose();
  33268. }
  33269. instancesBuffer = new BABYLON.Buffer(engine, instanceStorage.instancesData, true, 16, false, true);
  33270. instanceStorage.instancesBuffer = instancesBuffer;
  33271. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  33272. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  33273. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  33274. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  33275. }
  33276. else {
  33277. instancesBuffer.updateDirectly(instanceStorage.instancesData, 0, instancesCount);
  33278. }
  33279. this._bind(subMesh, effect, fillMode);
  33280. this._draw(subMesh, fillMode, instancesCount);
  33281. engine.unbindInstanceAttributes();
  33282. return this;
  33283. };
  33284. /** @hidden */
  33285. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  33286. var scene = this.getScene();
  33287. var engine = scene.getEngine();
  33288. if (hardwareInstancedRendering) {
  33289. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  33290. }
  33291. else {
  33292. if (batch.renderSelf[subMesh._id]) {
  33293. // Draw
  33294. if (onBeforeDraw) {
  33295. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  33296. }
  33297. this._draw(subMesh, fillMode, this._instanceDataStorage.overridenInstanceCount);
  33298. }
  33299. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  33300. if (visibleInstancesForSubMesh) {
  33301. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  33302. var instance = visibleInstancesForSubMesh[instanceIndex];
  33303. // World
  33304. var world = instance.getWorldMatrix();
  33305. if (onBeforeDraw) {
  33306. onBeforeDraw(true, world, effectiveMaterial);
  33307. }
  33308. // Draw
  33309. this._draw(subMesh, fillMode);
  33310. }
  33311. }
  33312. }
  33313. return this;
  33314. };
  33315. /**
  33316. * 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
  33317. * @param subMesh defines the subMesh to render
  33318. * @param enableAlphaMode defines if alpha mode can be changed
  33319. * @returns the current mesh
  33320. */
  33321. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  33322. if (this._checkOcclusionQuery()) {
  33323. return this;
  33324. }
  33325. var scene = this.getScene();
  33326. // Managing instances
  33327. var batch = this._getInstancesRenderList(subMesh._id);
  33328. if (batch.mustReturn) {
  33329. return this;
  33330. }
  33331. // Checking geometry state
  33332. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  33333. return this;
  33334. }
  33335. if (this._onBeforeRenderObservable) {
  33336. this._onBeforeRenderObservable.notifyObservers(this);
  33337. }
  33338. var engine = scene.getEngine();
  33339. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  33340. // Material
  33341. var material = subMesh.getMaterial();
  33342. if (!material) {
  33343. return this;
  33344. }
  33345. this._effectiveMaterial = material;
  33346. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33347. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  33348. return this;
  33349. }
  33350. }
  33351. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  33352. return this;
  33353. }
  33354. // Alpha mode
  33355. if (enableAlphaMode) {
  33356. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  33357. }
  33358. for (var _i = 0, _a = scene._beforeRenderingMeshStage; _i < _a.length; _i++) {
  33359. var step = _a[_i];
  33360. step.action(this, subMesh, batch);
  33361. }
  33362. var effect;
  33363. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33364. effect = subMesh.effect;
  33365. }
  33366. else {
  33367. effect = this._effectiveMaterial.getEffect();
  33368. }
  33369. if (!effect) {
  33370. return this;
  33371. }
  33372. var sideOrientation = this.overrideMaterialSideOrientation;
  33373. if (sideOrientation == null) {
  33374. sideOrientation = this._effectiveMaterial.sideOrientation;
  33375. if (this._getWorldMatrixDeterminant() < 0) {
  33376. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  33377. }
  33378. }
  33379. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  33380. if (this._effectiveMaterial.forceDepthWrite) {
  33381. engine.setDepthWrite(true);
  33382. }
  33383. // Bind
  33384. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  33385. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  33386. this._bind(subMesh, effect, fillMode);
  33387. }
  33388. var world = this.getWorldMatrix();
  33389. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  33390. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  33391. }
  33392. else {
  33393. this._effectiveMaterial.bind(world, this);
  33394. }
  33395. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  33396. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  33397. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33398. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  33399. }
  33400. // Draw
  33401. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  33402. // Unbind
  33403. this._effectiveMaterial.unbind();
  33404. for (var _b = 0, _c = scene._afterRenderingMeshStage; _b < _c.length; _b++) {
  33405. var step = _c[_b];
  33406. step.action(this, subMesh, batch);
  33407. }
  33408. if (this._onAfterRenderObservable) {
  33409. this._onAfterRenderObservable.notifyObservers(this);
  33410. }
  33411. return this;
  33412. };
  33413. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  33414. if (isInstance && effectiveMaterial) {
  33415. effectiveMaterial.bindOnlyWorldMatrix(world);
  33416. }
  33417. };
  33418. /**
  33419. * Renormalize the mesh and patch it up if there are no weights
  33420. * Similar to normalization by adding the weights compute the reciprocal and multiply all elements, this wil ensure that everything adds to 1.
  33421. * However in the case of zero weights then we set just a single influence to 1.
  33422. * We check in the function for extra's present and if so we use the normalizeSkinWeightsWithExtras rather than the FourWeights version.
  33423. */
  33424. Mesh.prototype.cleanMatrixWeights = function () {
  33425. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33426. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  33427. this.normalizeSkinWeightsAndExtra();
  33428. }
  33429. else {
  33430. this.normalizeSkinFourWeights();
  33431. }
  33432. }
  33433. };
  33434. // faster 4 weight version.
  33435. Mesh.prototype.normalizeSkinFourWeights = function () {
  33436. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33437. var numWeights = matricesWeights.length;
  33438. for (var a = 0; a < numWeights; a += 4) {
  33439. // accumulate weights
  33440. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33441. // check for invalid weight and just set it to 1.
  33442. if (t === 0)
  33443. matricesWeights[a] = 1;
  33444. else {
  33445. // renormalize so everything adds to 1 use reciprical
  33446. var recip = 1 / t;
  33447. matricesWeights[a] *= recip;
  33448. matricesWeights[a + 1] *= recip;
  33449. matricesWeights[a + 2] *= recip;
  33450. matricesWeights[a + 3] *= recip;
  33451. }
  33452. }
  33453. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33454. };
  33455. // handle special case of extra verts. (in theory gltf can handle 12 influences)
  33456. Mesh.prototype.normalizeSkinWeightsAndExtra = function () {
  33457. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33458. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33459. var numWeights = matricesWeights.length;
  33460. for (var a = 0; a < numWeights; a += 4) {
  33461. // accumulate weights
  33462. var t = matricesWeights[a] + matricesWeights[a + 1] + matricesWeights[a + 2] + matricesWeights[a + 3];
  33463. t += matricesWeightsExtra[a] + matricesWeightsExtra[a + 1] + matricesWeightsExtra[a + 2] + matricesWeightsExtra[a + 3];
  33464. // check for invalid weight and just set it to 1.
  33465. if (t === 0)
  33466. matricesWeights[a] = 1;
  33467. else {
  33468. // renormalize so everything adds to 1 use reciprical
  33469. var recip = 1 / t;
  33470. matricesWeights[a] *= recip;
  33471. matricesWeights[a + 1] *= recip;
  33472. matricesWeights[a + 2] *= recip;
  33473. matricesWeights[a + 3] *= recip;
  33474. // same goes for extras
  33475. matricesWeightsExtra[a] *= recip;
  33476. matricesWeightsExtra[a + 1] *= recip;
  33477. matricesWeightsExtra[a + 2] *= recip;
  33478. matricesWeightsExtra[a + 3] *= recip;
  33479. }
  33480. }
  33481. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  33482. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsExtra);
  33483. };
  33484. /**
  33485. * ValidateSkinning is used to determine that a mesh has valid skinning data along with skin metrics, if missing weights,
  33486. * or not normalized it is returned as invalid mesh the string can be used for console logs, or on screen messages to let
  33487. * the user know there was an issue with importing the mesh
  33488. * @returns a validation object with skinned, valid and report string
  33489. */
  33490. Mesh.prototype.validateSkinning = function () {
  33491. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  33492. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33493. if (matricesWeights === null || this.skeleton == null) {
  33494. return { skinned: false, valid: true, report: "not skinned" };
  33495. }
  33496. var numWeights = matricesWeights.length;
  33497. var numberNotSorted = 0;
  33498. var missingWeights = 0;
  33499. var maxUsedWeights = 0;
  33500. var numberNotNormalized = 0;
  33501. var numInfluences = matricesWeightsExtra === null ? 4 : 8;
  33502. var usedWeightCounts = new Array();
  33503. for (var a = 0; a <= numInfluences; a++) {
  33504. usedWeightCounts[a] = 0;
  33505. }
  33506. var toleranceEpsilon = 0.001;
  33507. for (var a = 0; a < numWeights; a += 4) {
  33508. var lastWeight = matricesWeights[a];
  33509. var t = lastWeight;
  33510. var usedWeights = t === 0 ? 0 : 1;
  33511. for (var b = 1; b < numInfluences; b++) {
  33512. var d = b < 4 ? matricesWeights[a + b] : matricesWeightsExtra[a + b - 4];
  33513. if (d > lastWeight)
  33514. numberNotSorted++;
  33515. if (d !== 0)
  33516. usedWeights++;
  33517. t += d;
  33518. lastWeight = d;
  33519. }
  33520. // count the buffer weights usage
  33521. usedWeightCounts[usedWeights]++;
  33522. // max influences
  33523. if (usedWeights > maxUsedWeights)
  33524. maxUsedWeights = usedWeights;
  33525. // check for invalid weight and just set it to 1.
  33526. if (t === 0) {
  33527. missingWeights++;
  33528. }
  33529. else {
  33530. // renormalize so everything adds to 1 use reciprical
  33531. var recip = 1 / t;
  33532. var tolerance = 0;
  33533. for (b = 0; b < numInfluences; b++) {
  33534. if (b < 4)
  33535. tolerance += Math.abs(matricesWeights[a + b] - (matricesWeights[a + b] * recip));
  33536. else
  33537. tolerance += Math.abs(matricesWeightsExtra[a + b - 4] - (matricesWeightsExtra[a + b - 4] * recip));
  33538. }
  33539. // arbitary epsilon value for dicdating not normalized
  33540. if (tolerance > toleranceEpsilon)
  33541. numberNotNormalized++;
  33542. }
  33543. }
  33544. // validate bone indices are in range of the skeleton
  33545. var numBones = this.skeleton.bones.length;
  33546. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33547. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  33548. var numBadBoneIndices = 0;
  33549. for (var a = 0; a < numWeights; a++) {
  33550. for (var b = 0; b < numInfluences; b++) {
  33551. var index = b < 4 ? matricesIndices[b] : matricesIndicesExtra[b - 4];
  33552. if (index >= numBones || index < 0)
  33553. numBadBoneIndices++;
  33554. }
  33555. }
  33556. // log mesh stats
  33557. var output = "Number of Weights = " + numWeights / 4 + "\nMaximum influences = " + maxUsedWeights +
  33558. "\nMissing Weights = " + missingWeights + "\nNot Sorted = " + numberNotSorted +
  33559. "\nNot Normalized = " + numberNotNormalized + "\nWeightCounts = [" + usedWeightCounts + "]" +
  33560. "\nNumber of bones = " + numBones + "\nBad Bone Indices = " + numBadBoneIndices;
  33561. return { skinned: true, valid: missingWeights === 0 && numberNotNormalized === 0 && numBadBoneIndices === 0, report: output };
  33562. };
  33563. /** @hidden */
  33564. Mesh.prototype._checkDelayState = function () {
  33565. var scene = this.getScene();
  33566. if (this._geometry) {
  33567. this._geometry.load(scene);
  33568. }
  33569. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  33570. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  33571. this._queueLoad(scene);
  33572. }
  33573. return this;
  33574. };
  33575. Mesh.prototype._queueLoad = function (scene) {
  33576. var _this = this;
  33577. scene._addPendingData(this);
  33578. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  33579. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  33580. if (data instanceof ArrayBuffer) {
  33581. _this._delayLoadingFunction(data, _this);
  33582. }
  33583. else {
  33584. _this._delayLoadingFunction(JSON.parse(data), _this);
  33585. }
  33586. _this.instances.forEach(function (instance) {
  33587. instance._syncSubMeshes();
  33588. });
  33589. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  33590. scene._removePendingData(_this);
  33591. }, function () { }, scene.database, getBinaryData);
  33592. return this;
  33593. };
  33594. /**
  33595. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  33596. * A mesh is in the frustum if its bounding box intersects the frustum
  33597. * @param frustumPlanes defines the frustum to test
  33598. * @returns true if the mesh is in the frustum planes
  33599. */
  33600. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  33601. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  33602. return false;
  33603. }
  33604. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  33605. return false;
  33606. }
  33607. this._checkDelayState();
  33608. return true;
  33609. };
  33610. /**
  33611. * Sets the mesh material by the material or multiMaterial `id` property
  33612. * @param id is a string identifying the material or the multiMaterial
  33613. * @returns the current mesh
  33614. */
  33615. Mesh.prototype.setMaterialByID = function (id) {
  33616. var materials = this.getScene().materials;
  33617. var index;
  33618. for (index = materials.length - 1; index > -1; index--) {
  33619. if (materials[index].id === id) {
  33620. this.material = materials[index];
  33621. return this;
  33622. }
  33623. }
  33624. // Multi
  33625. var multiMaterials = this.getScene().multiMaterials;
  33626. for (index = multiMaterials.length - 1; index > -1; index--) {
  33627. if (multiMaterials[index].id === id) {
  33628. this.material = multiMaterials[index];
  33629. return this;
  33630. }
  33631. }
  33632. return this;
  33633. };
  33634. /**
  33635. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33636. * @returns an array of IAnimatable
  33637. */
  33638. Mesh.prototype.getAnimatables = function () {
  33639. var results = new Array();
  33640. if (this.material) {
  33641. results.push(this.material);
  33642. }
  33643. if (this.skeleton) {
  33644. results.push(this.skeleton);
  33645. }
  33646. return results;
  33647. };
  33648. /**
  33649. * Modifies the mesh geometry according to the passed transformation matrix.
  33650. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33651. * The mesh normals are modified using the same transformation.
  33652. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33653. * @param transform defines the transform matrix to use
  33654. * @see http://doc.babylonjs.com/resources/baking_transformations
  33655. * @returns the current mesh
  33656. */
  33657. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33658. // Position
  33659. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33660. return this;
  33661. }
  33662. var submeshes = this.subMeshes.splice(0);
  33663. this._resetPointsArrayCache();
  33664. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33665. var temp = new Array();
  33666. var index;
  33667. for (index = 0; index < data.length; index += 3) {
  33668. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33669. }
  33670. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33671. // Normals
  33672. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33673. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33674. temp = [];
  33675. for (index = 0; index < data.length; index += 3) {
  33676. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33677. }
  33678. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33679. }
  33680. // flip faces?
  33681. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33682. this.flipFaces();
  33683. }
  33684. // Restore submeshes
  33685. this.releaseSubMeshes();
  33686. this.subMeshes = submeshes;
  33687. return this;
  33688. };
  33689. /**
  33690. * Modifies the mesh geometry according to its own current World Matrix.
  33691. * The mesh World Matrix is then reset.
  33692. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33693. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33694. * @see http://doc.babylonjs.com/resources/baking_transformations
  33695. * @returns the current mesh
  33696. */
  33697. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33698. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33699. this.scaling.copyFromFloats(1, 1, 1);
  33700. this.position.copyFromFloats(0, 0, 0);
  33701. this.rotation.copyFromFloats(0, 0, 0);
  33702. //only if quaternion is already set
  33703. if (this.rotationQuaternion) {
  33704. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33705. }
  33706. this._worldMatrix = BABYLON.Matrix.Identity();
  33707. return this;
  33708. };
  33709. Object.defineProperty(Mesh.prototype, "_positions", {
  33710. // Cache
  33711. /** @hidden */
  33712. get: function () {
  33713. if (this._geometry) {
  33714. return this._geometry._positions;
  33715. }
  33716. return null;
  33717. },
  33718. enumerable: true,
  33719. configurable: true
  33720. });
  33721. /** @hidden */
  33722. Mesh.prototype._resetPointsArrayCache = function () {
  33723. if (this._geometry) {
  33724. this._geometry._resetPointsArrayCache();
  33725. }
  33726. return this;
  33727. };
  33728. /** @hidden */
  33729. Mesh.prototype._generatePointsArray = function () {
  33730. if (this._geometry) {
  33731. return this._geometry._generatePointsArray();
  33732. }
  33733. return false;
  33734. };
  33735. /**
  33736. * Returns a new Mesh object generated from the current mesh properties.
  33737. * This method must not get confused with createInstance()
  33738. * @param name is a string, the name given to the new mesh
  33739. * @param newParent can be any Node object (default `null`)
  33740. * @param doNotCloneChildren allows/denies the recursive cloning of the original mesh children if any (default `false`)
  33741. * @param clonePhysicsImpostor allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any (default `true`)
  33742. * @returns a new mesh
  33743. */
  33744. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33745. if (name === void 0) { name = ""; }
  33746. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33747. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33748. };
  33749. /**
  33750. * Releases resources associated with this mesh.
  33751. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33752. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33753. */
  33754. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33755. var _this = this;
  33756. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33757. this.morphTargetManager = null;
  33758. if (this._geometry) {
  33759. this._geometry.releaseForMesh(this, true);
  33760. }
  33761. if (this._onBeforeDrawObservable) {
  33762. this._onBeforeDrawObservable.clear();
  33763. }
  33764. if (this._onBeforeRenderObservable) {
  33765. this._onBeforeRenderObservable.clear();
  33766. }
  33767. if (this._onAfterRenderObservable) {
  33768. this._onAfterRenderObservable.clear();
  33769. }
  33770. // Sources
  33771. var meshes = this.getScene().meshes;
  33772. meshes.forEach(function (abstractMesh) {
  33773. var mesh = abstractMesh;
  33774. if (mesh._source && mesh._source === _this) {
  33775. mesh._source = null;
  33776. }
  33777. });
  33778. this._source = null;
  33779. // Instances
  33780. if (this._instanceDataStorage.instancesBuffer) {
  33781. this._instanceDataStorage.instancesBuffer.dispose();
  33782. this._instanceDataStorage.instancesBuffer = null;
  33783. }
  33784. while (this.instances.length) {
  33785. this.instances[0].dispose();
  33786. }
  33787. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33788. };
  33789. /**
  33790. * Modifies the mesh geometry according to a displacement map.
  33791. * 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.
  33792. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33793. * @param url is a string, the URL from the image file is to be downloaded.
  33794. * @param minHeight is the lower limit of the displacement.
  33795. * @param maxHeight is the upper limit of the displacement.
  33796. * @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.
  33797. * @param uvOffset is an optional vector2 used to offset UV.
  33798. * @param uvScale is an optional vector2 used to scale UV.
  33799. * @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.
  33800. * @returns the Mesh.
  33801. */
  33802. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale, forceUpdate) {
  33803. var _this = this;
  33804. if (forceUpdate === void 0) { forceUpdate = false; }
  33805. var scene = this.getScene();
  33806. var onload = function (img) {
  33807. // Getting height map data
  33808. var canvas = document.createElement("canvas");
  33809. var context = canvas.getContext("2d");
  33810. var heightMapWidth = img.width;
  33811. var heightMapHeight = img.height;
  33812. canvas.width = heightMapWidth;
  33813. canvas.height = heightMapHeight;
  33814. context.drawImage(img, 0, 0);
  33815. // Create VertexData from map data
  33816. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33817. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33818. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate);
  33819. //execute success callback, if set
  33820. if (onSuccess) {
  33821. onSuccess(_this);
  33822. }
  33823. };
  33824. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33825. return this;
  33826. };
  33827. /**
  33828. * Modifies the mesh geometry according to a displacementMap buffer.
  33829. * 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.
  33830. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33831. * @param buffer is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  33832. * @param heightMapWidth is the width of the buffer image.
  33833. * @param heightMapHeight is the height of the buffer image.
  33834. * @param minHeight is the lower limit of the displacement.
  33835. * @param maxHeight is the upper limit of the displacement.
  33836. * @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.
  33837. * @param uvOffset is an optional vector2 used to offset UV.
  33838. * @param uvScale is an optional vector2 used to scale UV.
  33839. * @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.
  33840. * @returns the Mesh.
  33841. */
  33842. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale, forceUpdate) {
  33843. if (forceUpdate === void 0) { forceUpdate = false; }
  33844. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33845. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33846. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33847. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33848. return this;
  33849. }
  33850. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, true, true);
  33851. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33852. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33853. var position = BABYLON.Vector3.Zero();
  33854. var normal = BABYLON.Vector3.Zero();
  33855. var uv = BABYLON.Vector2.Zero();
  33856. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33857. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33858. for (var index = 0; index < positions.length; index += 3) {
  33859. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33860. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33861. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33862. // Compute height
  33863. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33864. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33865. var pos = (u + v * heightMapWidth) * 4;
  33866. var r = buffer[pos] / 255.0;
  33867. var g = buffer[pos + 1] / 255.0;
  33868. var b = buffer[pos + 2] / 255.0;
  33869. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33870. normal.normalize();
  33871. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33872. position = position.add(normal);
  33873. position.toArray(positions, index);
  33874. }
  33875. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33876. if (forceUpdate) {
  33877. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33878. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33879. }
  33880. else {
  33881. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33882. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33883. }
  33884. return this;
  33885. };
  33886. /**
  33887. * Modify the mesh to get a flat shading rendering.
  33888. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33889. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33890. * @returns current mesh
  33891. */
  33892. Mesh.prototype.convertToFlatShadedMesh = function () {
  33893. var kinds = this.getVerticesDataKinds();
  33894. var vbs = {};
  33895. var data = {};
  33896. var newdata = {};
  33897. var updatableNormals = false;
  33898. var kindIndex;
  33899. var kind;
  33900. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33901. kind = kinds[kindIndex];
  33902. var vertexBuffer = this.getVertexBuffer(kind);
  33903. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33904. updatableNormals = vertexBuffer.isUpdatable();
  33905. kinds.splice(kindIndex, 1);
  33906. kindIndex--;
  33907. continue;
  33908. }
  33909. vbs[kind] = vertexBuffer;
  33910. data[kind] = vbs[kind].getData();
  33911. newdata[kind] = [];
  33912. }
  33913. // Save previous submeshes
  33914. var previousSubmeshes = this.subMeshes.slice(0);
  33915. var indices = this.getIndices();
  33916. var totalIndices = this.getTotalIndices();
  33917. // Generating unique vertices per face
  33918. var index;
  33919. for (index = 0; index < totalIndices; index++) {
  33920. var vertexIndex = indices[index];
  33921. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33922. kind = kinds[kindIndex];
  33923. var stride = vbs[kind].getStrideSize();
  33924. for (var offset = 0; offset < stride; offset++) {
  33925. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33926. }
  33927. }
  33928. }
  33929. // Updating faces & normal
  33930. var normals = [];
  33931. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33932. for (index = 0; index < totalIndices; index += 3) {
  33933. indices[index] = index;
  33934. indices[index + 1] = index + 1;
  33935. indices[index + 2] = index + 2;
  33936. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33937. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33938. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33939. var p1p2 = p1.subtract(p2);
  33940. var p3p2 = p3.subtract(p2);
  33941. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33942. // Store same normals for every vertex
  33943. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33944. normals.push(normal.x);
  33945. normals.push(normal.y);
  33946. normals.push(normal.z);
  33947. }
  33948. }
  33949. this.setIndices(indices);
  33950. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33951. // Updating vertex buffers
  33952. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33953. kind = kinds[kindIndex];
  33954. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33955. }
  33956. // Updating submeshes
  33957. this.releaseSubMeshes();
  33958. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33959. var previousOne = previousSubmeshes[submeshIndex];
  33960. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33961. }
  33962. this.synchronizeInstances();
  33963. return this;
  33964. };
  33965. /**
  33966. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33967. * In other words, more vertices, no more indices and a single bigger VBO.
  33968. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33969. * @returns current mesh
  33970. */
  33971. Mesh.prototype.convertToUnIndexedMesh = function () {
  33972. var kinds = this.getVerticesDataKinds();
  33973. var vbs = {};
  33974. var data = {};
  33975. var newdata = {};
  33976. var kindIndex;
  33977. var kind;
  33978. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33979. kind = kinds[kindIndex];
  33980. var vertexBuffer = this.getVertexBuffer(kind);
  33981. vbs[kind] = vertexBuffer;
  33982. data[kind] = vbs[kind].getData();
  33983. newdata[kind] = [];
  33984. }
  33985. // Save previous submeshes
  33986. var previousSubmeshes = this.subMeshes.slice(0);
  33987. var indices = this.getIndices();
  33988. var totalIndices = this.getTotalIndices();
  33989. // Generating unique vertices per face
  33990. var index;
  33991. for (index = 0; index < totalIndices; index++) {
  33992. var vertexIndex = indices[index];
  33993. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33994. kind = kinds[kindIndex];
  33995. var stride = vbs[kind].getStrideSize();
  33996. for (var offset = 0; offset < stride; offset++) {
  33997. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33998. }
  33999. }
  34000. }
  34001. // Updating indices
  34002. for (index = 0; index < totalIndices; index += 3) {
  34003. indices[index] = index;
  34004. indices[index + 1] = index + 1;
  34005. indices[index + 2] = index + 2;
  34006. }
  34007. this.setIndices(indices);
  34008. // Updating vertex buffers
  34009. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  34010. kind = kinds[kindIndex];
  34011. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  34012. }
  34013. // Updating submeshes
  34014. this.releaseSubMeshes();
  34015. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  34016. var previousOne = previousSubmeshes[submeshIndex];
  34017. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  34018. }
  34019. this._unIndexed = true;
  34020. this.synchronizeInstances();
  34021. return this;
  34022. };
  34023. /**
  34024. * Inverses facet orientations.
  34025. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  34026. * @param flipNormals will also inverts the normals
  34027. * @returns current mesh
  34028. */
  34029. Mesh.prototype.flipFaces = function (flipNormals) {
  34030. if (flipNormals === void 0) { flipNormals = false; }
  34031. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  34032. var i;
  34033. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  34034. for (i = 0; i < vertex_data.normals.length; i++) {
  34035. vertex_data.normals[i] *= -1;
  34036. }
  34037. }
  34038. if (vertex_data.indices) {
  34039. var temp;
  34040. for (i = 0; i < vertex_data.indices.length; i += 3) {
  34041. // reassign indices
  34042. temp = vertex_data.indices[i + 1];
  34043. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  34044. vertex_data.indices[i + 2] = temp;
  34045. }
  34046. }
  34047. vertex_data.applyToMesh(this);
  34048. return this;
  34049. };
  34050. // Instances
  34051. /**
  34052. * Creates a new InstancedMesh object from the mesh model.
  34053. * Warning : this method is not supported for Line mesh and LineSystem
  34054. * @see http://doc.babylonjs.com/how_to/how_to_use_instances
  34055. * @param name defines the name of the new instance
  34056. * @returns a new InstancedMesh
  34057. */
  34058. Mesh.prototype.createInstance = function (name) {
  34059. return new BABYLON.InstancedMesh(name, this);
  34060. };
  34061. /**
  34062. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  34063. * After this call, all the mesh instances have the same submeshes than the current mesh.
  34064. * @returns the current mesh
  34065. */
  34066. Mesh.prototype.synchronizeInstances = function () {
  34067. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  34068. var instance = this.instances[instanceIndex];
  34069. instance._syncSubMeshes();
  34070. }
  34071. return this;
  34072. };
  34073. /**
  34074. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  34075. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  34076. * This should be used together with the simplification to avoid disappearing triangles.
  34077. * @param successCallback an optional success callback to be called after the optimization finished.
  34078. * @returns the current mesh
  34079. */
  34080. Mesh.prototype.optimizeIndices = function (successCallback) {
  34081. var _this = this;
  34082. var indices = this.getIndices();
  34083. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34084. if (!positions || !indices) {
  34085. return this;
  34086. }
  34087. var vectorPositions = new Array();
  34088. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  34089. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  34090. }
  34091. var dupes = new Array();
  34092. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  34093. var realPos = vectorPositions.length - 1 - iteration;
  34094. var testedPosition = vectorPositions[realPos];
  34095. for (var j = 0; j < realPos; ++j) {
  34096. var againstPosition = vectorPositions[j];
  34097. if (testedPosition.equals(againstPosition)) {
  34098. dupes[realPos] = j;
  34099. break;
  34100. }
  34101. }
  34102. }, function () {
  34103. for (var i = 0; i < indices.length; ++i) {
  34104. indices[i] = dupes[indices[i]] || indices[i];
  34105. }
  34106. //indices are now reordered
  34107. var originalSubMeshes = _this.subMeshes.slice(0);
  34108. _this.setIndices(indices);
  34109. _this.subMeshes = originalSubMeshes;
  34110. if (successCallback) {
  34111. successCallback(_this);
  34112. }
  34113. });
  34114. return this;
  34115. };
  34116. /**
  34117. * Serialize current mesh
  34118. * @param serializationObject defines the object which will receive the serialization data
  34119. */
  34120. Mesh.prototype.serialize = function (serializationObject) {
  34121. serializationObject.name = this.name;
  34122. serializationObject.id = this.id;
  34123. serializationObject.type = this.getClassName();
  34124. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  34125. serializationObject.tags = BABYLON.Tags.GetTags(this);
  34126. }
  34127. serializationObject.position = this.position.asArray();
  34128. if (this.rotationQuaternion) {
  34129. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  34130. }
  34131. else if (this.rotation) {
  34132. serializationObject.rotation = this.rotation.asArray();
  34133. }
  34134. serializationObject.scaling = this.scaling.asArray();
  34135. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  34136. serializationObject.isEnabled = this.isEnabled(false);
  34137. serializationObject.isVisible = this.isVisible;
  34138. serializationObject.infiniteDistance = this.infiniteDistance;
  34139. serializationObject.pickable = this.isPickable;
  34140. serializationObject.receiveShadows = this.receiveShadows;
  34141. serializationObject.billboardMode = this.billboardMode;
  34142. serializationObject.visibility = this.visibility;
  34143. serializationObject.checkCollisions = this.checkCollisions;
  34144. serializationObject.isBlocker = this.isBlocker;
  34145. // Parent
  34146. if (this.parent) {
  34147. serializationObject.parentId = this.parent.id;
  34148. }
  34149. // Geometry
  34150. serializationObject.isUnIndexed = this.isUnIndexed;
  34151. var geometry = this._geometry;
  34152. if (geometry) {
  34153. var geometryId = geometry.id;
  34154. serializationObject.geometryId = geometryId;
  34155. // SubMeshes
  34156. serializationObject.subMeshes = [];
  34157. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  34158. var subMesh = this.subMeshes[subIndex];
  34159. serializationObject.subMeshes.push({
  34160. materialIndex: subMesh.materialIndex,
  34161. verticesStart: subMesh.verticesStart,
  34162. verticesCount: subMesh.verticesCount,
  34163. indexStart: subMesh.indexStart,
  34164. indexCount: subMesh.indexCount
  34165. });
  34166. }
  34167. }
  34168. // Material
  34169. if (this.material) {
  34170. serializationObject.materialId = this.material.id;
  34171. }
  34172. else {
  34173. this.material = null;
  34174. }
  34175. // Morph targets
  34176. if (this.morphTargetManager) {
  34177. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  34178. }
  34179. // Skeleton
  34180. if (this.skeleton) {
  34181. serializationObject.skeletonId = this.skeleton.id;
  34182. }
  34183. // Physics
  34184. //TODO implement correct serialization for physics impostors.
  34185. var impostor = this.getPhysicsImpostor();
  34186. if (impostor) {
  34187. serializationObject.physicsMass = impostor.getParam("mass");
  34188. serializationObject.physicsFriction = impostor.getParam("friction");
  34189. serializationObject.physicsRestitution = impostor.getParam("mass");
  34190. serializationObject.physicsImpostor = impostor.type;
  34191. }
  34192. // Metadata
  34193. if (this.metadata) {
  34194. serializationObject.metadata = this.metadata;
  34195. }
  34196. // Instances
  34197. serializationObject.instances = [];
  34198. for (var index = 0; index < this.instances.length; index++) {
  34199. var instance = this.instances[index];
  34200. if (instance.doNotSerialize) {
  34201. continue;
  34202. }
  34203. var serializationInstance = {
  34204. name: instance.name,
  34205. id: instance.id,
  34206. position: instance.position.asArray(),
  34207. scaling: instance.scaling.asArray()
  34208. };
  34209. if (instance.parent) {
  34210. serializationInstance.parentId = instance.parent.id;
  34211. }
  34212. if (instance.rotationQuaternion) {
  34213. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  34214. }
  34215. else if (instance.rotation) {
  34216. serializationInstance.rotation = instance.rotation.asArray();
  34217. }
  34218. serializationObject.instances.push(serializationInstance);
  34219. // Animations
  34220. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  34221. serializationInstance.ranges = instance.serializeAnimationRanges();
  34222. }
  34223. //
  34224. // Animations
  34225. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  34226. serializationObject.ranges = this.serializeAnimationRanges();
  34227. // Layer mask
  34228. serializationObject.layerMask = this.layerMask;
  34229. // Alpha
  34230. serializationObject.alphaIndex = this.alphaIndex;
  34231. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  34232. // Overlay
  34233. serializationObject.overlayAlpha = this.overlayAlpha;
  34234. serializationObject.overlayColor = this.overlayColor.asArray();
  34235. serializationObject.renderOverlay = this.renderOverlay;
  34236. // Fog
  34237. serializationObject.applyFog = this.applyFog;
  34238. // Action Manager
  34239. if (this.actionManager) {
  34240. serializationObject.actions = this.actionManager.serialize(this.name);
  34241. }
  34242. };
  34243. /** @hidden */
  34244. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  34245. if (!this.geometry) {
  34246. return;
  34247. }
  34248. this._markSubMeshesAsAttributesDirty();
  34249. var morphTargetManager = this._morphTargetManager;
  34250. if (morphTargetManager && morphTargetManager.vertexCount) {
  34251. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  34252. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  34253. this.morphTargetManager = null;
  34254. return;
  34255. }
  34256. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  34257. var morphTarget = morphTargetManager.getActiveTarget(index);
  34258. var positions = morphTarget.getPositions();
  34259. if (!positions) {
  34260. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  34261. return;
  34262. }
  34263. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  34264. var normals = morphTarget.getNormals();
  34265. if (normals) {
  34266. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  34267. }
  34268. var tangents = morphTarget.getTangents();
  34269. if (tangents) {
  34270. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  34271. }
  34272. }
  34273. }
  34274. else {
  34275. var index = 0;
  34276. // Positions
  34277. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  34278. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  34279. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  34280. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  34281. }
  34282. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  34283. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  34284. }
  34285. index++;
  34286. }
  34287. }
  34288. };
  34289. // Statics
  34290. /**
  34291. * Returns a new Mesh object parsed from the source provided.
  34292. * @param parsedMesh is the source
  34293. * @param scene defines the hosting scene
  34294. * @param rootUrl is the root URL to prefix the `delayLoadingFile` property with
  34295. * @returns a new Mesh
  34296. */
  34297. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  34298. var mesh;
  34299. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  34300. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  34301. }
  34302. else {
  34303. mesh = new Mesh(parsedMesh.name, scene);
  34304. }
  34305. mesh.id = parsedMesh.id;
  34306. if (BABYLON.Tags) {
  34307. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  34308. }
  34309. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  34310. if (parsedMesh.metadata !== undefined) {
  34311. mesh.metadata = parsedMesh.metadata;
  34312. }
  34313. if (parsedMesh.rotationQuaternion) {
  34314. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  34315. }
  34316. else if (parsedMesh.rotation) {
  34317. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  34318. }
  34319. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  34320. if (parsedMesh.localMatrix) {
  34321. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  34322. }
  34323. else if (parsedMesh.pivotMatrix) {
  34324. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  34325. }
  34326. mesh.setEnabled(parsedMesh.isEnabled);
  34327. mesh.isVisible = parsedMesh.isVisible;
  34328. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  34329. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  34330. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  34331. if (parsedMesh.applyFog !== undefined) {
  34332. mesh.applyFog = parsedMesh.applyFog;
  34333. }
  34334. if (parsedMesh.pickable !== undefined) {
  34335. mesh.isPickable = parsedMesh.pickable;
  34336. }
  34337. if (parsedMesh.alphaIndex !== undefined) {
  34338. mesh.alphaIndex = parsedMesh.alphaIndex;
  34339. }
  34340. mesh.receiveShadows = parsedMesh.receiveShadows;
  34341. mesh.billboardMode = parsedMesh.billboardMode;
  34342. if (parsedMesh.visibility !== undefined) {
  34343. mesh.visibility = parsedMesh.visibility;
  34344. }
  34345. mesh.checkCollisions = parsedMesh.checkCollisions;
  34346. if (parsedMesh.isBlocker !== undefined) {
  34347. mesh.isBlocker = parsedMesh.isBlocker;
  34348. }
  34349. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  34350. // freezeWorldMatrix
  34351. if (parsedMesh.freezeWorldMatrix) {
  34352. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  34353. }
  34354. // Parent
  34355. if (parsedMesh.parentId) {
  34356. mesh._waitingParentId = parsedMesh.parentId;
  34357. }
  34358. // Actions
  34359. if (parsedMesh.actions !== undefined) {
  34360. mesh._waitingActions = parsedMesh.actions;
  34361. }
  34362. // Overlay
  34363. if (parsedMesh.overlayAlpha !== undefined) {
  34364. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  34365. }
  34366. if (parsedMesh.overlayColor !== undefined) {
  34367. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  34368. }
  34369. if (parsedMesh.renderOverlay !== undefined) {
  34370. mesh.renderOverlay = parsedMesh.renderOverlay;
  34371. }
  34372. // Geometry
  34373. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  34374. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  34375. if (parsedMesh.delayLoadingFile) {
  34376. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  34377. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  34378. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  34379. if (parsedMesh._binaryInfo) {
  34380. mesh._binaryInfo = parsedMesh._binaryInfo;
  34381. }
  34382. mesh._delayInfo = [];
  34383. if (parsedMesh.hasUVs) {
  34384. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  34385. }
  34386. if (parsedMesh.hasUVs2) {
  34387. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  34388. }
  34389. if (parsedMesh.hasUVs3) {
  34390. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  34391. }
  34392. if (parsedMesh.hasUVs4) {
  34393. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  34394. }
  34395. if (parsedMesh.hasUVs5) {
  34396. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  34397. }
  34398. if (parsedMesh.hasUVs6) {
  34399. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  34400. }
  34401. if (parsedMesh.hasColors) {
  34402. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  34403. }
  34404. if (parsedMesh.hasMatricesIndices) {
  34405. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  34406. }
  34407. if (parsedMesh.hasMatricesWeights) {
  34408. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  34409. }
  34410. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  34411. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  34412. mesh._checkDelayState();
  34413. }
  34414. }
  34415. else {
  34416. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  34417. }
  34418. // Material
  34419. if (parsedMesh.materialId) {
  34420. mesh.setMaterialByID(parsedMesh.materialId);
  34421. }
  34422. else {
  34423. mesh.material = null;
  34424. }
  34425. // Morph targets
  34426. if (parsedMesh.morphTargetManagerId > -1) {
  34427. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  34428. }
  34429. // Skeleton
  34430. if (parsedMesh.skeletonId > -1) {
  34431. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  34432. if (parsedMesh.numBoneInfluencers) {
  34433. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  34434. }
  34435. }
  34436. // Animations
  34437. if (parsedMesh.animations) {
  34438. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  34439. var parsedAnimation = parsedMesh.animations[animationIndex];
  34440. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34441. }
  34442. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  34443. }
  34444. if (parsedMesh.autoAnimate) {
  34445. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  34446. }
  34447. // Layer Mask
  34448. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  34449. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  34450. }
  34451. else {
  34452. mesh.layerMask = 0x0FFFFFFF;
  34453. }
  34454. // Physics
  34455. if (parsedMesh.physicsImpostor) {
  34456. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  34457. mass: parsedMesh.physicsMass,
  34458. friction: parsedMesh.physicsFriction,
  34459. restitution: parsedMesh.physicsRestitution
  34460. }, scene);
  34461. }
  34462. // Instances
  34463. if (parsedMesh.instances) {
  34464. for (var index = 0; index < parsedMesh.instances.length; index++) {
  34465. var parsedInstance = parsedMesh.instances[index];
  34466. var instance = mesh.createInstance(parsedInstance.name);
  34467. if (parsedInstance.id) {
  34468. instance.id = parsedInstance.id;
  34469. }
  34470. if (BABYLON.Tags) {
  34471. if (parsedInstance.tags) {
  34472. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  34473. }
  34474. else {
  34475. BABYLON.Tags.AddTagsTo(instance, parsedMesh.tags);
  34476. }
  34477. }
  34478. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  34479. if (parsedInstance.parentId) {
  34480. instance._waitingParentId = parsedInstance.parentId;
  34481. }
  34482. if (parsedInstance.rotationQuaternion) {
  34483. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  34484. }
  34485. else if (parsedInstance.rotation) {
  34486. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  34487. }
  34488. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  34489. if (parsedInstance.checkCollisions != undefined && parsedInstance.checkCollisions != null) {
  34490. instance.checkCollisions = parsedInstance.checkCollisions;
  34491. }
  34492. if (parsedInstance.pickable != undefined && parsedInstance.pickable != null) {
  34493. instance.isPickable = parsedInstance.pickable;
  34494. }
  34495. if (parsedInstance.showBoundingBox != undefined && parsedInstance.showBoundingBox != null) {
  34496. instance.showBoundingBox = parsedInstance.showBoundingBox;
  34497. }
  34498. if (parsedInstance.showSubMeshesBoundingBox != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34499. instance.showSubMeshesBoundingBox = parsedInstance.showSubMeshesBoundingBox;
  34500. }
  34501. if (parsedInstance.alphaIndex != undefined && parsedInstance.showSubMeshesBoundingBox != null) {
  34502. instance.alphaIndex = parsedInstance.alphaIndex;
  34503. }
  34504. // Physics
  34505. if (parsedInstance.physicsImpostor) {
  34506. instance.physicsImpostor = new BABYLON.PhysicsImpostor(instance, parsedInstance.physicsImpostor, {
  34507. mass: parsedInstance.physicsMass,
  34508. friction: parsedInstance.physicsFriction,
  34509. restitution: parsedInstance.physicsRestitution
  34510. }, scene);
  34511. }
  34512. // Animation
  34513. if (parsedInstance.animations) {
  34514. for (animationIndex = 0; animationIndex < parsedInstance.animations.length; animationIndex++) {
  34515. parsedAnimation = parsedInstance.animations[animationIndex];
  34516. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  34517. }
  34518. BABYLON.Node.ParseAnimationRanges(instance, parsedInstance, scene);
  34519. if (parsedInstance.autoAnimate) {
  34520. scene.beginAnimation(instance, parsedInstance.autoAnimateFrom, parsedInstance.autoAnimateTo, parsedInstance.autoAnimateLoop, parsedInstance.autoAnimateSpeed || 1.0);
  34521. }
  34522. }
  34523. }
  34524. }
  34525. return mesh;
  34526. };
  34527. /**
  34528. * Creates a ribbon mesh. Please consider using the same method from the MeshBuilder class instead
  34529. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34530. * @param name defines the name of the mesh to create
  34531. * @param pathArray is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  34532. * @param closeArray creates a seam between the first and the last paths of the path array (default is false)
  34533. * @param closePath creates a seam between the first and the last points of each path of the path array
  34534. * @param offset is taken in account only if the `pathArray` is containing a single path
  34535. * @param scene defines the hosting scene
  34536. * @param updatable defines if the mesh must be flagged as updatable
  34537. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34538. * @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)
  34539. * @returns a new Mesh
  34540. */
  34541. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  34542. if (closeArray === void 0) { closeArray = false; }
  34543. if (updatable === void 0) { updatable = false; }
  34544. return BABYLON.MeshBuilder.CreateRibbon(name, {
  34545. pathArray: pathArray,
  34546. closeArray: closeArray,
  34547. closePath: closePath,
  34548. offset: offset,
  34549. updatable: updatable,
  34550. sideOrientation: sideOrientation,
  34551. instance: instance
  34552. }, scene);
  34553. };
  34554. /**
  34555. * Creates a plane polygonal mesh. By default, this is a disc. Please consider using the same method from the MeshBuilder class instead
  34556. * @param name defines the name of the mesh to create
  34557. * @param radius sets the radius size (float) of the polygon (default 0.5)
  34558. * @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
  34559. * @param scene defines the hosting scene
  34560. * @param updatable defines if the mesh must be flagged as updatable
  34561. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34562. * @returns a new Mesh
  34563. */
  34564. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  34565. if (scene === void 0) { scene = null; }
  34566. var options = {
  34567. radius: radius,
  34568. tessellation: tessellation,
  34569. sideOrientation: sideOrientation,
  34570. updatable: updatable
  34571. };
  34572. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  34573. };
  34574. /**
  34575. * Creates a box mesh. Please consider using the same method from the MeshBuilder class instead
  34576. * @param name defines the name of the mesh to create
  34577. * @param size sets the size (float) of each box side (default 1)
  34578. * @param scene defines the hosting scene
  34579. * @param updatable defines if the mesh must be flagged as updatable
  34580. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34581. * @returns a new Mesh
  34582. */
  34583. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  34584. if (scene === void 0) { scene = null; }
  34585. var options = {
  34586. size: size,
  34587. sideOrientation: sideOrientation,
  34588. updatable: updatable
  34589. };
  34590. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  34591. };
  34592. /**
  34593. * Creates a sphere mesh. Please consider using the same method from the MeshBuilder class instead
  34594. * @param name defines the name of the mesh to create
  34595. * @param segments sets the sphere number of horizontal stripes (positive integer, default 32)
  34596. * @param diameter sets the diameter size (float) of the sphere (default 1)
  34597. * @param scene defines the hosting scene
  34598. * @param updatable defines if the mesh must be flagged as updatable
  34599. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34600. * @returns a new Mesh
  34601. */
  34602. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  34603. var options = {
  34604. segments: segments,
  34605. diameterX: diameter,
  34606. diameterY: diameter,
  34607. diameterZ: diameter,
  34608. sideOrientation: sideOrientation,
  34609. updatable: updatable
  34610. };
  34611. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  34612. };
  34613. /**
  34614. * Creates a cylinder or a cone mesh. Please consider using the same method from the MeshBuilder class instead
  34615. * @param name defines the name of the mesh to create
  34616. * @param height sets the height size (float) of the cylinder/cone (float, default 2)
  34617. * @param diameterTop set the top cap diameter (floats, default 1)
  34618. * @param diameterBottom set the bottom cap diameter (floats, default 1). This value can't be zero
  34619. * @param tessellation sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance
  34620. * @param subdivisions sets the number of rings along the cylinder height (positive integer, default 1)
  34621. * @param scene defines the hosting scene
  34622. * @param updatable defines if the mesh must be flagged as updatable
  34623. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34624. * @returns a new Mesh
  34625. */
  34626. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  34627. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  34628. if (scene !== undefined) {
  34629. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  34630. updatable = scene;
  34631. }
  34632. scene = subdivisions;
  34633. subdivisions = 1;
  34634. }
  34635. var options = {
  34636. height: height,
  34637. diameterTop: diameterTop,
  34638. diameterBottom: diameterBottom,
  34639. tessellation: tessellation,
  34640. subdivisions: subdivisions,
  34641. sideOrientation: sideOrientation,
  34642. updatable: updatable
  34643. };
  34644. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34645. };
  34646. // Torus (Code from SharpDX.org)
  34647. /**
  34648. * Creates a torus mesh. Please consider using the same method from the MeshBuilder class instead
  34649. * @param name defines the name of the mesh to create
  34650. * @param diameter sets the diameter size (float) of the torus (default 1)
  34651. * @param thickness sets the diameter size of the tube of the torus (float, default 0.5)
  34652. * @param tessellation sets the number of torus sides (postive integer, default 16)
  34653. * @param scene defines the hosting scene
  34654. * @param updatable defines if the mesh must be flagged as updatable
  34655. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34656. * @returns a new Mesh
  34657. */
  34658. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34659. var options = {
  34660. diameter: diameter,
  34661. thickness: thickness,
  34662. tessellation: tessellation,
  34663. sideOrientation: sideOrientation,
  34664. updatable: updatable
  34665. };
  34666. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34667. };
  34668. /**
  34669. * Creates a torus knot mesh. Please consider using the same method from the MeshBuilder class instead
  34670. * @param name defines the name of the mesh to create
  34671. * @param radius sets the global radius size (float) of the torus knot (default 2)
  34672. * @param tube sets the diameter size of the tube of the torus (float, default 0.5)
  34673. * @param radialSegments sets the number of sides on each tube segments (positive integer, default 32)
  34674. * @param tubularSegments sets the number of tubes to decompose the knot into (positive integer, default 32)
  34675. * @param p the number of windings on X axis (positive integers, default 2)
  34676. * @param q the number of windings on Y axis (positive integers, default 3)
  34677. * @param scene defines the hosting scene
  34678. * @param updatable defines if the mesh must be flagged as updatable
  34679. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34680. * @returns a new Mesh
  34681. */
  34682. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34683. var options = {
  34684. radius: radius,
  34685. tube: tube,
  34686. radialSegments: radialSegments,
  34687. tubularSegments: tubularSegments,
  34688. p: p,
  34689. q: q,
  34690. sideOrientation: sideOrientation,
  34691. updatable: updatable
  34692. };
  34693. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34694. };
  34695. /**
  34696. * Creates a line mesh. Please consider using the same method from the MeshBuilder class instead.
  34697. * @param name defines the name of the mesh to create
  34698. * @param points is an array successive Vector3
  34699. * @param scene defines the hosting scene
  34700. * @param updatable defines if the mesh must be flagged as updatable
  34701. * @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).
  34702. * @returns a new Mesh
  34703. */
  34704. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34705. if (scene === void 0) { scene = null; }
  34706. if (updatable === void 0) { updatable = false; }
  34707. if (instance === void 0) { instance = null; }
  34708. var options = {
  34709. points: points,
  34710. updatable: updatable,
  34711. instance: instance
  34712. };
  34713. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34714. };
  34715. /**
  34716. * Creates a dashed line mesh. Please consider using the same method from the MeshBuilder class instead
  34717. * @param name defines the name of the mesh to create
  34718. * @param points is an array successive Vector3
  34719. * @param dashSize is the size of the dashes relatively the dash number (positive float, default 3)
  34720. * @param gapSize is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  34721. * @param dashNb is the intended total number of dashes (positive integer, default 200)
  34722. * @param scene defines the hosting scene
  34723. * @param updatable defines if the mesh must be flagged as updatable
  34724. * @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)
  34725. * @returns a new Mesh
  34726. */
  34727. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34728. if (scene === void 0) { scene = null; }
  34729. var options = {
  34730. points: points,
  34731. dashSize: dashSize,
  34732. gapSize: gapSize,
  34733. dashNb: dashNb,
  34734. updatable: updatable,
  34735. instance: instance
  34736. };
  34737. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34738. };
  34739. /**
  34740. * Creates a polygon mesh.
  34741. * Please consider using the same method from the MeshBuilder class instead.
  34742. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34743. * 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.
  34744. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34745. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34746. * Remember you can only change the shape positions, not their number when updating a polygon.
  34747. */
  34748. /**
  34749. * Creates a polygon mesh.Please consider using the same method from the MeshBuilder class instead
  34750. * @see http://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  34751. * @param name defines the name of the mesh to create
  34752. * @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
  34753. * @param scene defines the hosting scene
  34754. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34755. * @param updatable defines if the mesh must be flagged as updatable
  34756. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34757. * @returns a new Mesh
  34758. */
  34759. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34760. var options = {
  34761. shape: shape,
  34762. holes: holes,
  34763. updatable: updatable,
  34764. sideOrientation: sideOrientation
  34765. };
  34766. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34767. };
  34768. /**
  34769. * Creates an extruded polygon mesh, with depth in the Y direction. Please consider using the same method from the MeshBuilder class instead.
  34770. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-non-regular-polygon
  34771. * @param name defines the name of the mesh to create
  34772. * @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
  34773. * @param depth defines the height of extrusion
  34774. * @param scene defines the hosting scene
  34775. * @param holes is a required array of arrays of successive Vector3 used to defines holes in the polygon
  34776. * @param updatable defines if the mesh must be flagged as updatable
  34777. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34778. * @returns a new Mesh
  34779. */
  34780. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34781. var options = {
  34782. shape: shape,
  34783. holes: holes,
  34784. depth: depth,
  34785. updatable: updatable,
  34786. sideOrientation: sideOrientation
  34787. };
  34788. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34789. };
  34790. /**
  34791. * Creates an extruded shape mesh.
  34792. * 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
  34793. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34794. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34795. * @param name defines the name of the mesh to create
  34796. * @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
  34797. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34798. * @param scale is the value to scale the shape
  34799. * @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
  34800. * @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
  34801. * @param scene defines the hosting scene
  34802. * @param updatable defines if the mesh must be flagged as updatable
  34803. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34804. * @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)
  34805. * @returns a new Mesh
  34806. */
  34807. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34808. if (scene === void 0) { scene = null; }
  34809. var options = {
  34810. shape: shape,
  34811. path: path,
  34812. scale: scale,
  34813. rotation: rotation,
  34814. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34815. sideOrientation: sideOrientation,
  34816. instance: instance,
  34817. updatable: updatable
  34818. };
  34819. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34820. };
  34821. /**
  34822. * Creates an custom extruded shape mesh.
  34823. * The custom extrusion is a parametric shape.
  34824. * It has no predefined shape. Its final shape will depend on the input parameters.
  34825. * Please consider using the same method from the MeshBuilder class instead
  34826. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34827. * @param name defines the name of the mesh to create
  34828. * @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
  34829. * @param path is a required array of successive Vector3. This is the axis curve the shape is extruded along
  34830. * @param scaleFunction is a custom Javascript function called on each path point
  34831. * @param rotationFunction is a custom Javascript function called on each path point
  34832. * @param ribbonCloseArray forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  34833. * @param ribbonClosePath forces the extrusion underlying ribbon to close its `pathArray`
  34834. * @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
  34835. * @param scene defines the hosting scene
  34836. * @param updatable defines if the mesh must be flagged as updatable
  34837. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34838. * @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)
  34839. * @returns a new Mesh
  34840. */
  34841. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34842. var options = {
  34843. shape: shape,
  34844. path: path,
  34845. scaleFunction: scaleFunction,
  34846. rotationFunction: rotationFunction,
  34847. ribbonCloseArray: ribbonCloseArray,
  34848. ribbonClosePath: ribbonClosePath,
  34849. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34850. sideOrientation: sideOrientation,
  34851. instance: instance,
  34852. updatable: updatable
  34853. };
  34854. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34855. };
  34856. /**
  34857. * Creates lathe mesh.
  34858. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34859. * Please consider using the same method from the MeshBuilder class instead
  34860. * @param name defines the name of the mesh to create
  34861. * @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
  34862. * @param radius is the radius value of the lathe
  34863. * @param tessellation is the side number of the lathe.
  34864. * @param scene defines the hosting scene
  34865. * @param updatable defines if the mesh must be flagged as updatable
  34866. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34867. * @returns a new Mesh
  34868. */
  34869. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34870. var options = {
  34871. shape: shape,
  34872. radius: radius,
  34873. tessellation: tessellation,
  34874. sideOrientation: sideOrientation,
  34875. updatable: updatable
  34876. };
  34877. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34878. };
  34879. /**
  34880. * Creates a plane mesh. Please consider using the same method from the MeshBuilder class instead
  34881. * @param name defines the name of the mesh to create
  34882. * @param size sets the size (float) of both sides of the plane at once (default 1)
  34883. * @param scene defines the hosting scene
  34884. * @param updatable defines if the mesh must be flagged as updatable
  34885. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34886. * @returns a new Mesh
  34887. */
  34888. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34889. var options = {
  34890. size: size,
  34891. width: size,
  34892. height: size,
  34893. sideOrientation: sideOrientation,
  34894. updatable: updatable
  34895. };
  34896. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34897. };
  34898. /**
  34899. * Creates a ground mesh.
  34900. * Please consider using the same method from the MeshBuilder class instead
  34901. * @param name defines the name of the mesh to create
  34902. * @param width set the width of the ground
  34903. * @param height set the height of the ground
  34904. * @param subdivisions sets the number of subdivisions per side
  34905. * @param scene defines the hosting scene
  34906. * @param updatable defines if the mesh must be flagged as updatable
  34907. * @returns a new Mesh
  34908. */
  34909. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34910. var options = {
  34911. width: width,
  34912. height: height,
  34913. subdivisions: subdivisions,
  34914. updatable: updatable
  34915. };
  34916. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34917. };
  34918. /**
  34919. * Creates a tiled ground mesh.
  34920. * Please consider using the same method from the MeshBuilder class instead
  34921. * @param name defines the name of the mesh to create
  34922. * @param xmin set the ground minimum X coordinate
  34923. * @param zmin set the ground minimum Y coordinate
  34924. * @param xmax set the ground maximum X coordinate
  34925. * @param zmax set the ground maximum Z coordinate
  34926. * @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
  34927. * @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
  34928. * @param scene defines the hosting scene
  34929. * @param updatable defines if the mesh must be flagged as updatable
  34930. * @returns a new Mesh
  34931. */
  34932. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34933. var options = {
  34934. xmin: xmin,
  34935. zmin: zmin,
  34936. xmax: xmax,
  34937. zmax: zmax,
  34938. subdivisions: subdivisions,
  34939. precision: precision,
  34940. updatable: updatable
  34941. };
  34942. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34943. };
  34944. /**
  34945. * Creates a ground mesh from a height map.
  34946. * Please consider using the same method from the MeshBuilder class instead
  34947. * @see http://doc.babylonjs.com/babylon101/height_map
  34948. * @param name defines the name of the mesh to create
  34949. * @param url sets the URL of the height map image resource
  34950. * @param width set the ground width size
  34951. * @param height set the ground height size
  34952. * @param subdivisions sets the number of subdivision per side
  34953. * @param minHeight is the minimum altitude on the ground
  34954. * @param maxHeight is the maximum altitude on the ground
  34955. * @param scene defines the hosting scene
  34956. * @param updatable defines if the mesh must be flagged as updatable
  34957. * @param onReady is a callback function that will be called once the mesh is built (the height map download can last some time)
  34958. * @param alphaFilter will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  34959. * @returns a new Mesh
  34960. */
  34961. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady, alphaFilter) {
  34962. var options = {
  34963. width: width,
  34964. height: height,
  34965. subdivisions: subdivisions,
  34966. minHeight: minHeight,
  34967. maxHeight: maxHeight,
  34968. updatable: updatable,
  34969. onReady: onReady,
  34970. alphaFilter: alphaFilter
  34971. };
  34972. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34973. };
  34974. /**
  34975. * Creates a tube mesh.
  34976. * The tube is a parametric shape.
  34977. * It has no predefined shape. Its final shape will depend on the input parameters.
  34978. * Please consider using the same method from the MeshBuilder class instead
  34979. * @see http://doc.babylonjs.com/how_to/parametric_shapes
  34980. * @param name defines the name of the mesh to create
  34981. * @param path is a required array of successive Vector3. It is the curve used as the axis of the tube
  34982. * @param radius sets the tube radius size
  34983. * @param tessellation is the number of sides on the tubular surface
  34984. * @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
  34985. * @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
  34986. * @param scene defines the hosting scene
  34987. * @param updatable defines if the mesh must be flagged as updatable
  34988. * @param sideOrientation defines the mesh side orientation (http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation)
  34989. * @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)
  34990. * @returns a new Mesh
  34991. */
  34992. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34993. var options = {
  34994. path: path,
  34995. radius: radius,
  34996. tessellation: tessellation,
  34997. radiusFunction: radiusFunction,
  34998. arc: 1,
  34999. cap: cap,
  35000. updatable: updatable,
  35001. sideOrientation: sideOrientation,
  35002. instance: instance
  35003. };
  35004. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  35005. };
  35006. /**
  35007. * Creates a polyhedron mesh.
  35008. * Please consider using the same method from the MeshBuilder class instead.
  35009. * * 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
  35010. * * The parameter `size` (positive float, default 1) sets the polygon size
  35011. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  35012. * * 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`
  35013. * * 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
  35014. * * 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)`)
  35015. * * 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
  35016. * * 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
  35017. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35018. * * 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
  35019. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35020. * @param name defines the name of the mesh to create
  35021. * @param options defines the options used to create the mesh
  35022. * @param scene defines the hosting scene
  35023. * @returns a new Mesh
  35024. */
  35025. Mesh.CreatePolyhedron = function (name, options, scene) {
  35026. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  35027. };
  35028. /**
  35029. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  35030. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  35031. * * 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`)
  35032. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  35033. * * 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
  35034. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  35035. * * 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
  35036. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  35037. * @param name defines the name of the mesh
  35038. * @param options defines the options used to create the mesh
  35039. * @param scene defines the hosting scene
  35040. * @returns a new Mesh
  35041. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  35042. */
  35043. Mesh.CreateIcoSphere = function (name, options, scene) {
  35044. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  35045. };
  35046. /**
  35047. * Creates a decal mesh.
  35048. * Please consider using the same method from the MeshBuilder class instead.
  35049. * A decal is a mesh usually applied as a model onto the surface of another mesh
  35050. * @param name defines the name of the mesh
  35051. * @param sourceMesh defines the mesh receiving the decal
  35052. * @param position sets the position of the decal in world coordinates
  35053. * @param normal sets the normal of the mesh where the decal is applied onto in world coordinates
  35054. * @param size sets the decal scaling
  35055. * @param angle sets the angle to rotate the decal
  35056. * @returns a new Mesh
  35057. */
  35058. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  35059. var options = {
  35060. position: position,
  35061. normal: normal,
  35062. size: size,
  35063. angle: angle
  35064. };
  35065. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  35066. };
  35067. // Skeletons
  35068. /**
  35069. * Prepare internal position array for software CPU skinning
  35070. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh
  35071. */
  35072. Mesh.prototype.setPositionsForCPUSkinning = function () {
  35073. if (!this._sourcePositions) {
  35074. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35075. if (!source) {
  35076. return this._sourcePositions;
  35077. }
  35078. this._sourcePositions = new Float32Array(source);
  35079. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  35080. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  35081. }
  35082. }
  35083. return this._sourcePositions;
  35084. };
  35085. /**
  35086. * Prepare internal normal array for software CPU skinning
  35087. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  35088. */
  35089. Mesh.prototype.setNormalsForCPUSkinning = function () {
  35090. if (!this._sourceNormals) {
  35091. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35092. if (!source) {
  35093. return this._sourceNormals;
  35094. }
  35095. this._sourceNormals = new Float32Array(source);
  35096. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  35097. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  35098. }
  35099. }
  35100. return this._sourceNormals;
  35101. };
  35102. /**
  35103. * Updates the vertex buffer by applying transformation from the bones
  35104. * @param skeleton defines the skeleton to apply to current mesh
  35105. * @returns the current mesh
  35106. */
  35107. Mesh.prototype.applySkeleton = function (skeleton) {
  35108. if (!this.geometry) {
  35109. return this;
  35110. }
  35111. if (this.geometry._softwareSkinningFrameId == this.getScene().getFrameId()) {
  35112. return this;
  35113. }
  35114. this.geometry._softwareSkinningFrameId = this.getScene().getFrameId();
  35115. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  35116. return this;
  35117. }
  35118. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  35119. return this;
  35120. }
  35121. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  35122. return this;
  35123. }
  35124. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  35125. return this;
  35126. }
  35127. if (!this._sourcePositions) {
  35128. var submeshes = this.subMeshes.slice();
  35129. this.setPositionsForCPUSkinning();
  35130. this.subMeshes = submeshes;
  35131. }
  35132. if (!this._sourceNormals) {
  35133. this.setNormalsForCPUSkinning();
  35134. }
  35135. // positionsData checks for not being Float32Array will only pass at most once
  35136. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35137. if (!positionsData) {
  35138. return this;
  35139. }
  35140. if (!(positionsData instanceof Float32Array)) {
  35141. positionsData = new Float32Array(positionsData);
  35142. }
  35143. // normalsData checks for not being Float32Array will only pass at most once
  35144. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  35145. if (!normalsData) {
  35146. return this;
  35147. }
  35148. if (!(normalsData instanceof Float32Array)) {
  35149. normalsData = new Float32Array(normalsData);
  35150. }
  35151. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  35152. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  35153. if (!matricesWeightsData || !matricesIndicesData) {
  35154. return this;
  35155. }
  35156. var needExtras = this.numBoneInfluencers > 4;
  35157. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  35158. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  35159. var skeletonMatrices = skeleton.getTransformMatrices(this);
  35160. var tempVector3 = BABYLON.Vector3.Zero();
  35161. var finalMatrix = new BABYLON.Matrix();
  35162. var tempMatrix = new BABYLON.Matrix();
  35163. var matWeightIdx = 0;
  35164. var inf;
  35165. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  35166. var weight;
  35167. for (inf = 0; inf < 4; inf++) {
  35168. weight = matricesWeightsData[matWeightIdx + inf];
  35169. if (weight > 0) {
  35170. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35171. finalMatrix.addToSelf(tempMatrix);
  35172. }
  35173. }
  35174. if (needExtras) {
  35175. for (inf = 0; inf < 4; inf++) {
  35176. weight = matricesWeightsExtraData[matWeightIdx + inf];
  35177. if (weight > 0) {
  35178. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  35179. finalMatrix.addToSelf(tempMatrix);
  35180. }
  35181. }
  35182. }
  35183. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  35184. tempVector3.toArray(positionsData, index);
  35185. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  35186. tempVector3.toArray(normalsData, index);
  35187. finalMatrix.reset();
  35188. }
  35189. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  35190. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  35191. return this;
  35192. };
  35193. // Tools
  35194. /**
  35195. * 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
  35196. * @param meshes defines the list of meshes to scan
  35197. * @returns an object `{min:` Vector3`, max:` Vector3`}`
  35198. */
  35199. Mesh.MinMax = function (meshes) {
  35200. var minVector = null;
  35201. var maxVector = null;
  35202. meshes.forEach(function (mesh, index, array) {
  35203. var boundingInfo = mesh.getBoundingInfo();
  35204. var boundingBox = boundingInfo.boundingBox;
  35205. if (!minVector || !maxVector) {
  35206. minVector = boundingBox.minimumWorld;
  35207. maxVector = boundingBox.maximumWorld;
  35208. }
  35209. else {
  35210. minVector.minimizeInPlace(boundingBox.minimumWorld);
  35211. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  35212. }
  35213. });
  35214. if (!minVector || !maxVector) {
  35215. return {
  35216. min: BABYLON.Vector3.Zero(),
  35217. max: BABYLON.Vector3.Zero()
  35218. };
  35219. }
  35220. return {
  35221. min: minVector,
  35222. max: maxVector
  35223. };
  35224. };
  35225. /**
  35226. * Returns the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array
  35227. * @param meshesOrMinMaxVector could be an array of meshes or a `{min:` Vector3`, max:` Vector3`}` object
  35228. * @returns a vector3
  35229. */
  35230. Mesh.Center = function (meshesOrMinMaxVector) {
  35231. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  35232. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  35233. };
  35234. /**
  35235. * Merge the array of meshes into a single mesh for performance reasons.
  35236. * @param meshes defines he vertices source. They should all be of the same material. Entries can empty
  35237. * @param disposeSource when true (default), dispose of the vertices from the source meshes
  35238. * @param allow32BitsIndices when the sum of the vertices > 64k, this must be set to true
  35239. * @param meshSubclass when set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  35240. * @param subdivideWithSubMeshes when true (false default), subdivide mesh to his subMesh array with meshes source.
  35241. * @returns a new mesh
  35242. */
  35243. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  35244. if (disposeSource === void 0) { disposeSource = true; }
  35245. var index;
  35246. if (!allow32BitsIndices) {
  35247. var totalVertices = 0;
  35248. // Counting vertices
  35249. for (index = 0; index < meshes.length; index++) {
  35250. if (meshes[index]) {
  35251. totalVertices += meshes[index].getTotalVertices();
  35252. if (totalVertices > 65536) {
  35253. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  35254. return null;
  35255. }
  35256. }
  35257. }
  35258. }
  35259. // Merge
  35260. var vertexData = null;
  35261. var otherVertexData;
  35262. var indiceArray = new Array();
  35263. var source = null;
  35264. for (index = 0; index < meshes.length; index++) {
  35265. if (meshes[index]) {
  35266. var wm = meshes[index].computeWorldMatrix(true);
  35267. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  35268. otherVertexData.transform(wm);
  35269. if (vertexData) {
  35270. vertexData.merge(otherVertexData, allow32BitsIndices);
  35271. }
  35272. else {
  35273. vertexData = otherVertexData;
  35274. source = meshes[index];
  35275. }
  35276. if (subdivideWithSubMeshes) {
  35277. indiceArray.push(meshes[index].getTotalIndices());
  35278. }
  35279. }
  35280. }
  35281. source = source;
  35282. if (!meshSubclass) {
  35283. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  35284. }
  35285. vertexData.applyToMesh(meshSubclass);
  35286. // Setting properties
  35287. meshSubclass.material = source.material;
  35288. meshSubclass.checkCollisions = source.checkCollisions;
  35289. // Cleaning
  35290. if (disposeSource) {
  35291. for (index = 0; index < meshes.length; index++) {
  35292. if (meshes[index]) {
  35293. meshes[index].dispose();
  35294. }
  35295. }
  35296. }
  35297. // Subdivide
  35298. if (subdivideWithSubMeshes) {
  35299. //-- removal of global submesh
  35300. meshSubclass.releaseSubMeshes();
  35301. index = 0;
  35302. var offset = 0;
  35303. //-- apply subdivision according to index table
  35304. while (index < indiceArray.length) {
  35305. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  35306. offset += indiceArray[index];
  35307. index++;
  35308. }
  35309. }
  35310. return meshSubclass;
  35311. };
  35312. // Consts
  35313. /**
  35314. * Mesh side orientation : usually the external or front surface
  35315. */
  35316. Mesh.FRONTSIDE = 0;
  35317. /**
  35318. * Mesh side orientation : usually the internal or back surface
  35319. */
  35320. Mesh.BACKSIDE = 1;
  35321. /**
  35322. * Mesh side orientation : both internal and external or front and back surfaces
  35323. */
  35324. Mesh.DOUBLESIDE = 2;
  35325. /**
  35326. * Mesh side orientation : by default, `FRONTSIDE`
  35327. */
  35328. Mesh.DEFAULTSIDE = 0;
  35329. /**
  35330. * Mesh cap setting : no cap
  35331. */
  35332. Mesh.NO_CAP = 0;
  35333. /**
  35334. * Mesh cap setting : one cap at the beginning of the mesh
  35335. */
  35336. Mesh.CAP_START = 1;
  35337. /**
  35338. * Mesh cap setting : one cap at the end of the mesh
  35339. */
  35340. Mesh.CAP_END = 2;
  35341. /**
  35342. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  35343. */
  35344. Mesh.CAP_ALL = 3;
  35345. return Mesh;
  35346. }(BABYLON.AbstractMesh));
  35347. BABYLON.Mesh = Mesh;
  35348. })(BABYLON || (BABYLON = {}));
  35349. //# sourceMappingURL=babylon.mesh.js.map
  35350. var BABYLON;
  35351. (function (BABYLON) {
  35352. /**
  35353. * Base class for submeshes
  35354. */
  35355. var BaseSubMesh = /** @class */ (function () {
  35356. function BaseSubMesh() {
  35357. }
  35358. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  35359. /**
  35360. * Gets associated effect
  35361. */
  35362. get: function () {
  35363. return this._materialEffect;
  35364. },
  35365. enumerable: true,
  35366. configurable: true
  35367. });
  35368. /**
  35369. * Sets associated effect (effect used to render this submesh)
  35370. * @param effect defines the effect to associate with
  35371. * @param defines defines the set of defines used to compile this effect
  35372. */
  35373. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  35374. if (defines === void 0) { defines = null; }
  35375. if (this._materialEffect === effect) {
  35376. if (!effect) {
  35377. this._materialDefines = null;
  35378. }
  35379. return;
  35380. }
  35381. this._materialDefines = defines;
  35382. this._materialEffect = effect;
  35383. };
  35384. return BaseSubMesh;
  35385. }());
  35386. BABYLON.BaseSubMesh = BaseSubMesh;
  35387. /**
  35388. * Defines a subdivision inside a mesh
  35389. */
  35390. var SubMesh = /** @class */ (function (_super) {
  35391. __extends(SubMesh, _super);
  35392. /**
  35393. * Creates a new submesh
  35394. * @param materialIndex defines the material index to use
  35395. * @param verticesStart defines vertex index start
  35396. * @param verticesCount defines vertices count
  35397. * @param indexStart defines index start
  35398. * @param indexCount defines indices count
  35399. * @param mesh defines the parent mesh
  35400. * @param renderingMesh defines an optional rendering mesh
  35401. * @param createBoundingBox defines if bounding box should be created for this submesh
  35402. */
  35403. function SubMesh(
  35404. /** the material index to use */
  35405. materialIndex,
  35406. /** vertex index start */
  35407. verticesStart,
  35408. /** vertices count */
  35409. verticesCount,
  35410. /** index start */
  35411. indexStart,
  35412. /** indices count */
  35413. indexCount, mesh, renderingMesh, createBoundingBox) {
  35414. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35415. var _this = _super.call(this) || this;
  35416. _this.materialIndex = materialIndex;
  35417. _this.verticesStart = verticesStart;
  35418. _this.verticesCount = verticesCount;
  35419. _this.indexStart = indexStart;
  35420. _this.indexCount = indexCount;
  35421. /** @hidden */
  35422. _this._renderId = 0;
  35423. _this._mesh = mesh;
  35424. _this._renderingMesh = renderingMesh || mesh;
  35425. mesh.subMeshes.push(_this);
  35426. _this._trianglePlanes = [];
  35427. _this._id = mesh.subMeshes.length - 1;
  35428. if (createBoundingBox) {
  35429. _this.refreshBoundingInfo();
  35430. mesh.computeWorldMatrix(true);
  35431. }
  35432. return _this;
  35433. }
  35434. /**
  35435. * Add a new submesh to a mesh
  35436. * @param materialIndex defines the material index to use
  35437. * @param verticesStart defines vertex index start
  35438. * @param verticesCount defines vertices count
  35439. * @param indexStart defines index start
  35440. * @param indexCount defines indices count
  35441. * @param mesh defines the parent mesh
  35442. * @param renderingMesh defines an optional rendering mesh
  35443. * @param createBoundingBox defines if bounding box should be created for this submesh
  35444. * @returns the new submesh
  35445. */
  35446. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  35447. if (createBoundingBox === void 0) { createBoundingBox = true; }
  35448. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  35449. };
  35450. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  35451. /**
  35452. * Returns true if this submesh covers the entire parent mesh
  35453. * @ignorenaming
  35454. */
  35455. get: function () {
  35456. return (this.verticesStart === 0 && this.verticesCount === this._mesh.getTotalVertices());
  35457. },
  35458. enumerable: true,
  35459. configurable: true
  35460. });
  35461. /**
  35462. * Returns the submesh BoudingInfo object
  35463. * @returns current bounding info (or mesh's one if the submesh is global)
  35464. */
  35465. SubMesh.prototype.getBoundingInfo = function () {
  35466. if (this.IsGlobal) {
  35467. return this._mesh.getBoundingInfo();
  35468. }
  35469. return this._boundingInfo;
  35470. };
  35471. /**
  35472. * Sets the submesh BoundingInfo
  35473. * @param boundingInfo defines the new bounding info to use
  35474. * @returns the SubMesh
  35475. */
  35476. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  35477. this._boundingInfo = boundingInfo;
  35478. return this;
  35479. };
  35480. /**
  35481. * Returns the mesh of the current submesh
  35482. * @return the parent mesh
  35483. */
  35484. SubMesh.prototype.getMesh = function () {
  35485. return this._mesh;
  35486. };
  35487. /**
  35488. * Returns the rendering mesh of the submesh
  35489. * @returns the rendering mesh (could be different from parent mesh)
  35490. */
  35491. SubMesh.prototype.getRenderingMesh = function () {
  35492. return this._renderingMesh;
  35493. };
  35494. /**
  35495. * Returns the submesh material
  35496. * @returns null or the current material
  35497. */
  35498. SubMesh.prototype.getMaterial = function () {
  35499. var rootMaterial = this._renderingMesh.material;
  35500. if (rootMaterial === null || rootMaterial === undefined) {
  35501. return this._mesh.getScene().defaultMaterial;
  35502. }
  35503. else if (rootMaterial.getSubMaterial) {
  35504. var multiMaterial = rootMaterial;
  35505. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  35506. if (this._currentMaterial !== effectiveMaterial) {
  35507. this._currentMaterial = effectiveMaterial;
  35508. this._materialDefines = null;
  35509. }
  35510. return effectiveMaterial;
  35511. }
  35512. return rootMaterial;
  35513. };
  35514. // Methods
  35515. /**
  35516. * Sets a new updated BoundingInfo object to the submesh
  35517. * @returns the SubMesh
  35518. */
  35519. SubMesh.prototype.refreshBoundingInfo = function () {
  35520. this._lastColliderWorldVertices = null;
  35521. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  35522. return this;
  35523. }
  35524. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  35525. if (!data) {
  35526. this._boundingInfo = this._mesh.getBoundingInfo();
  35527. return this;
  35528. }
  35529. var indices = this._renderingMesh.getIndices();
  35530. var extend;
  35531. //is this the only submesh?
  35532. if (this.indexStart === 0 && this.indexCount === indices.length) {
  35533. var boundingInfo = this._renderingMesh.getBoundingInfo();
  35534. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  35535. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  35536. }
  35537. else {
  35538. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  35539. }
  35540. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  35541. return this;
  35542. };
  35543. /** @hidden */
  35544. SubMesh.prototype._checkCollision = function (collider) {
  35545. var boundingInfo = this.getBoundingInfo();
  35546. return boundingInfo._checkCollision(collider);
  35547. };
  35548. /**
  35549. * Updates the submesh BoundingInfo
  35550. * @param world defines the world matrix to use to update the bounding info
  35551. * @returns the submesh
  35552. */
  35553. SubMesh.prototype.updateBoundingInfo = function (world) {
  35554. var boundingInfo = this.getBoundingInfo();
  35555. if (!boundingInfo) {
  35556. this.refreshBoundingInfo();
  35557. boundingInfo = this.getBoundingInfo();
  35558. }
  35559. boundingInfo.update(world);
  35560. return this;
  35561. };
  35562. /**
  35563. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  35564. * @param frustumPlanes defines the frustum planes
  35565. * @returns true if the submesh is intersecting with the frustum
  35566. */
  35567. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  35568. var boundingInfo = this.getBoundingInfo();
  35569. if (!boundingInfo) {
  35570. return false;
  35571. }
  35572. return boundingInfo.isInFrustum(frustumPlanes, this._mesh.cullingStrategy);
  35573. };
  35574. /**
  35575. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes
  35576. * @param frustumPlanes defines the frustum planes
  35577. * @returns true if the submesh is inside the frustum
  35578. */
  35579. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  35580. var boundingInfo = this.getBoundingInfo();
  35581. if (!boundingInfo) {
  35582. return false;
  35583. }
  35584. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  35585. };
  35586. /**
  35587. * Renders the submesh
  35588. * @param enableAlphaMode defines if alpha needs to be used
  35589. * @returns the submesh
  35590. */
  35591. SubMesh.prototype.render = function (enableAlphaMode) {
  35592. this._renderingMesh.render(this, enableAlphaMode);
  35593. return this;
  35594. };
  35595. /**
  35596. * @hidden
  35597. */
  35598. SubMesh.prototype._getLinesIndexBuffer = function (indices, engine) {
  35599. if (!this._linesIndexBuffer) {
  35600. var linesIndices = [];
  35601. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35602. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  35603. }
  35604. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  35605. this._linesIndexCount = linesIndices.length;
  35606. }
  35607. return this._linesIndexBuffer;
  35608. };
  35609. /**
  35610. * Checks if the submesh intersects with a ray
  35611. * @param ray defines the ray to test
  35612. * @returns true is the passed ray intersects the submesh bounding box
  35613. */
  35614. SubMesh.prototype.canIntersects = function (ray) {
  35615. var boundingInfo = this.getBoundingInfo();
  35616. if (!boundingInfo) {
  35617. return false;
  35618. }
  35619. return ray.intersectsBox(boundingInfo.boundingBox);
  35620. };
  35621. /**
  35622. * Intersects current submesh with a ray
  35623. * @param ray defines the ray to test
  35624. * @param positions defines mesh's positions array
  35625. * @param indices defines mesh's indices array
  35626. * @param fastCheck defines if only bounding info should be used
  35627. * @returns intersection info or null if no intersection
  35628. */
  35629. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  35630. var material = this.getMaterial();
  35631. if (!material) {
  35632. return null;
  35633. }
  35634. switch (material.fillMode) {
  35635. case BABYLON.Material.PointListDrawMode:
  35636. case BABYLON.Material.LineListDrawMode:
  35637. case BABYLON.Material.LineLoopDrawMode:
  35638. case BABYLON.Material.LineStripDrawMode:
  35639. case BABYLON.Material.TriangleFanDrawMode:
  35640. case BABYLON.Material.TriangleStripDrawMode:
  35641. return null;
  35642. }
  35643. // LineMesh first as it's also a Mesh...
  35644. if (BABYLON.LinesMesh) {
  35645. var mesh = this._mesh instanceof BABYLON.InstancedMesh ? this._mesh.sourceMesh : this._mesh;
  35646. if (mesh instanceof BABYLON.LinesMesh) {
  35647. var linesMesh = mesh;
  35648. return this._intersectLines(ray, positions, indices, linesMesh.intersectionThreshold, fastCheck);
  35649. }
  35650. }
  35651. return this._intersectTriangles(ray, positions, indices, fastCheck);
  35652. };
  35653. /** @hidden */
  35654. SubMesh.prototype._intersectLines = function (ray, positions, indices, intersectionThreshold, fastCheck) {
  35655. var intersectInfo = null;
  35656. // Line test
  35657. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  35658. var p0 = positions[indices[index]];
  35659. var p1 = positions[indices[index + 1]];
  35660. var length = ray.intersectionSegment(p0, p1, intersectionThreshold);
  35661. if (length < 0) {
  35662. continue;
  35663. }
  35664. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  35665. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  35666. if (fastCheck) {
  35667. break;
  35668. }
  35669. }
  35670. }
  35671. return intersectInfo;
  35672. };
  35673. /** @hidden */
  35674. SubMesh.prototype._intersectTriangles = function (ray, positions, indices, fastCheck) {
  35675. var intersectInfo = null;
  35676. // Triangles test
  35677. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  35678. var p0 = positions[indices[index]];
  35679. var p1 = positions[indices[index + 1]];
  35680. var p2 = positions[indices[index + 2]];
  35681. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  35682. if (currentIntersectInfo) {
  35683. if (currentIntersectInfo.distance < 0) {
  35684. continue;
  35685. }
  35686. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  35687. intersectInfo = currentIntersectInfo;
  35688. intersectInfo.faceId = index / 3;
  35689. if (fastCheck) {
  35690. break;
  35691. }
  35692. }
  35693. }
  35694. }
  35695. return intersectInfo;
  35696. };
  35697. /** @hidden */
  35698. SubMesh.prototype._rebuild = function () {
  35699. if (this._linesIndexBuffer) {
  35700. this._linesIndexBuffer = null;
  35701. }
  35702. };
  35703. // Clone
  35704. /**
  35705. * Creates a new submesh from the passed mesh
  35706. * @param newMesh defines the new hosting mesh
  35707. * @param newRenderingMesh defines an optional rendering mesh
  35708. * @returns the new submesh
  35709. */
  35710. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  35711. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  35712. if (!this.IsGlobal) {
  35713. var boundingInfo = this.getBoundingInfo();
  35714. if (!boundingInfo) {
  35715. return result;
  35716. }
  35717. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  35718. }
  35719. return result;
  35720. };
  35721. // Dispose
  35722. /**
  35723. * Release associated resources
  35724. */
  35725. SubMesh.prototype.dispose = function () {
  35726. if (this._linesIndexBuffer) {
  35727. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  35728. this._linesIndexBuffer = null;
  35729. }
  35730. // Remove from mesh
  35731. var index = this._mesh.subMeshes.indexOf(this);
  35732. this._mesh.subMeshes.splice(index, 1);
  35733. };
  35734. // Statics
  35735. /**
  35736. * Creates a new submesh from indices data
  35737. * @param materialIndex the index of the main mesh material
  35738. * @param startIndex the index where to start the copy in the mesh indices array
  35739. * @param indexCount the number of indices to copy then from the startIndex
  35740. * @param mesh the main mesh to create the submesh from
  35741. * @param renderingMesh the optional rendering mesh
  35742. * @returns a new submesh
  35743. */
  35744. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  35745. var minVertexIndex = Number.MAX_VALUE;
  35746. var maxVertexIndex = -Number.MAX_VALUE;
  35747. renderingMesh = (renderingMesh || mesh);
  35748. var indices = renderingMesh.getIndices();
  35749. for (var index = startIndex; index < startIndex + indexCount; index++) {
  35750. var vertexIndex = indices[index];
  35751. if (vertexIndex < minVertexIndex)
  35752. minVertexIndex = vertexIndex;
  35753. if (vertexIndex > maxVertexIndex)
  35754. maxVertexIndex = vertexIndex;
  35755. }
  35756. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  35757. };
  35758. return SubMesh;
  35759. }(BaseSubMesh));
  35760. BABYLON.SubMesh = SubMesh;
  35761. })(BABYLON || (BABYLON = {}));
  35762. //# sourceMappingURL=babylon.subMesh.js.map
  35763. var __assign = (this && this.__assign) || function () {
  35764. __assign = Object.assign || function(t) {
  35765. for (var s, i = 1, n = arguments.length; i < n; i++) {
  35766. s = arguments[i];
  35767. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  35768. t[p] = s[p];
  35769. }
  35770. return t;
  35771. };
  35772. return __assign.apply(this, arguments);
  35773. };
  35774. var BABYLON;
  35775. (function (BABYLON) {
  35776. /**
  35777. * Manages the defines for the Material
  35778. */
  35779. var MaterialDefines = /** @class */ (function () {
  35780. function MaterialDefines() {
  35781. this._isDirty = true;
  35782. /** @hidden */
  35783. this._areLightsDirty = true;
  35784. /** @hidden */
  35785. this._areAttributesDirty = true;
  35786. /** @hidden */
  35787. this._areTexturesDirty = true;
  35788. /** @hidden */
  35789. this._areFresnelDirty = true;
  35790. /** @hidden */
  35791. this._areMiscDirty = true;
  35792. /** @hidden */
  35793. this._areImageProcessingDirty = true;
  35794. /** @hidden */
  35795. this._normals = false;
  35796. /** @hidden */
  35797. this._uvs = false;
  35798. /** @hidden */
  35799. this._needNormals = false;
  35800. /** @hidden */
  35801. this._needUVs = false;
  35802. }
  35803. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35804. /**
  35805. * Specifies if the material needs to be re-calculated
  35806. */
  35807. get: function () {
  35808. return this._isDirty;
  35809. },
  35810. enumerable: true,
  35811. configurable: true
  35812. });
  35813. /**
  35814. * Marks the material to indicate that it has been re-calculated
  35815. */
  35816. MaterialDefines.prototype.markAsProcessed = function () {
  35817. this._isDirty = false;
  35818. this._areAttributesDirty = false;
  35819. this._areTexturesDirty = false;
  35820. this._areFresnelDirty = false;
  35821. this._areLightsDirty = false;
  35822. this._areMiscDirty = false;
  35823. this._areImageProcessingDirty = false;
  35824. };
  35825. /**
  35826. * Marks the material to indicate that it needs to be re-calculated
  35827. */
  35828. MaterialDefines.prototype.markAsUnprocessed = function () {
  35829. this._isDirty = true;
  35830. };
  35831. /**
  35832. * Marks the material to indicate all of its defines need to be re-calculated
  35833. */
  35834. MaterialDefines.prototype.markAllAsDirty = function () {
  35835. this._areTexturesDirty = true;
  35836. this._areAttributesDirty = true;
  35837. this._areLightsDirty = true;
  35838. this._areFresnelDirty = true;
  35839. this._areMiscDirty = true;
  35840. this._areImageProcessingDirty = true;
  35841. this._isDirty = true;
  35842. };
  35843. /**
  35844. * Marks the material to indicate that image processing needs to be re-calculated
  35845. */
  35846. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35847. this._areImageProcessingDirty = true;
  35848. this._isDirty = true;
  35849. };
  35850. /**
  35851. * Marks the material to indicate the lights need to be re-calculated
  35852. */
  35853. MaterialDefines.prototype.markAsLightDirty = function () {
  35854. this._areLightsDirty = true;
  35855. this._isDirty = true;
  35856. };
  35857. /**
  35858. * Marks the attribute state as changed
  35859. */
  35860. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35861. this._areAttributesDirty = true;
  35862. this._isDirty = true;
  35863. };
  35864. /**
  35865. * Marks the texture state as changed
  35866. */
  35867. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35868. this._areTexturesDirty = true;
  35869. this._isDirty = true;
  35870. };
  35871. /**
  35872. * Marks the fresnel state as changed
  35873. */
  35874. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35875. this._areFresnelDirty = true;
  35876. this._isDirty = true;
  35877. };
  35878. /**
  35879. * Marks the misc state as changed
  35880. */
  35881. MaterialDefines.prototype.markAsMiscDirty = function () {
  35882. this._areMiscDirty = true;
  35883. this._isDirty = true;
  35884. };
  35885. /**
  35886. * Rebuilds the material defines
  35887. */
  35888. MaterialDefines.prototype.rebuild = function () {
  35889. if (this._keys) {
  35890. delete this._keys;
  35891. }
  35892. this._keys = [];
  35893. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35894. var key = _a[_i];
  35895. if (key[0] === "_") {
  35896. continue;
  35897. }
  35898. this._keys.push(key);
  35899. }
  35900. };
  35901. /**
  35902. * Specifies if two material defines are equal
  35903. * @param other - A material define instance to compare to
  35904. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35905. */
  35906. MaterialDefines.prototype.isEqual = function (other) {
  35907. if (this._keys.length !== other._keys.length) {
  35908. return false;
  35909. }
  35910. for (var index = 0; index < this._keys.length; index++) {
  35911. var prop = this._keys[index];
  35912. if (this[prop] !== other[prop]) {
  35913. return false;
  35914. }
  35915. }
  35916. return true;
  35917. };
  35918. /**
  35919. * Clones this instance's defines to another instance
  35920. * @param other - material defines to clone values to
  35921. */
  35922. MaterialDefines.prototype.cloneTo = function (other) {
  35923. if (this._keys.length !== other._keys.length) {
  35924. other._keys = this._keys.slice(0);
  35925. }
  35926. for (var index = 0; index < this._keys.length; index++) {
  35927. var prop = this._keys[index];
  35928. other[prop] = this[prop];
  35929. }
  35930. };
  35931. /**
  35932. * Resets the material define values
  35933. */
  35934. MaterialDefines.prototype.reset = function () {
  35935. for (var index = 0; index < this._keys.length; index++) {
  35936. var prop = this._keys[index];
  35937. var type = typeof this[prop];
  35938. switch (type) {
  35939. case "number":
  35940. this[prop] = 0;
  35941. break;
  35942. case "string":
  35943. this[prop] = "";
  35944. break;
  35945. default:
  35946. this[prop] = false;
  35947. break;
  35948. }
  35949. }
  35950. };
  35951. /**
  35952. * Converts the material define values to a string
  35953. * @returns - String of material define information
  35954. */
  35955. MaterialDefines.prototype.toString = function () {
  35956. var result = "";
  35957. for (var index = 0; index < this._keys.length; index++) {
  35958. var prop = this._keys[index];
  35959. var value = this[prop];
  35960. var type = typeof value;
  35961. switch (type) {
  35962. case "number":
  35963. case "string":
  35964. result += "#define " + prop + " " + value + "\n";
  35965. break;
  35966. default:
  35967. if (value) {
  35968. result += "#define " + prop + "\n";
  35969. }
  35970. break;
  35971. }
  35972. }
  35973. return result;
  35974. };
  35975. return MaterialDefines;
  35976. }());
  35977. BABYLON.MaterialDefines = MaterialDefines;
  35978. /**
  35979. * Base class for the main features of a material in Babylon.js
  35980. */
  35981. var Material = /** @class */ (function () {
  35982. /**
  35983. * Creates a material instance
  35984. * @param name defines the name of the material
  35985. * @param scene defines the scene to reference
  35986. * @param doNotAdd specifies if the material should be added to the scene
  35987. */
  35988. function Material(name, scene, doNotAdd) {
  35989. /**
  35990. * Specifies if the ready state should be checked on each call
  35991. */
  35992. this.checkReadyOnEveryCall = false;
  35993. /**
  35994. * Specifies if the ready state should be checked once
  35995. */
  35996. this.checkReadyOnlyOnce = false;
  35997. /**
  35998. * The state of the material
  35999. */
  36000. this.state = "";
  36001. /**
  36002. * The alpha value of the material
  36003. */
  36004. this._alpha = 1.0;
  36005. /**
  36006. * Specifies if back face culling is enabled
  36007. */
  36008. this._backFaceCulling = true;
  36009. /**
  36010. * Specifies if the material should be serialized
  36011. */
  36012. this.doNotSerialize = false;
  36013. /**
  36014. * Specifies if the effect should be stored on sub meshes
  36015. */
  36016. this.storeEffectOnSubMeshes = false;
  36017. /**
  36018. * An event triggered when the material is disposed
  36019. */
  36020. this.onDisposeObservable = new BABYLON.Observable();
  36021. /**
  36022. * Stores the value of the alpha mode
  36023. */
  36024. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  36025. /**
  36026. * Stores the state of the need depth pre-pass value
  36027. */
  36028. this._needDepthPrePass = false;
  36029. /**
  36030. * Specifies if depth writing should be disabled
  36031. */
  36032. this.disableDepthWrite = false;
  36033. /**
  36034. * Specifies if depth writing should be forced
  36035. */
  36036. this.forceDepthWrite = false;
  36037. /**
  36038. * Specifies if there should be a separate pass for culling
  36039. */
  36040. this.separateCullingPass = false;
  36041. /**
  36042. * Stores the state specifing if fog should be enabled
  36043. */
  36044. this._fogEnabled = true;
  36045. /**
  36046. * Stores the size of points
  36047. */
  36048. this.pointSize = 1.0;
  36049. /**
  36050. * Stores the z offset value
  36051. */
  36052. this.zOffset = 0;
  36053. /**
  36054. * @hidden
  36055. * Specifies if the material was previously ready
  36056. */
  36057. this._wasPreviouslyReady = false;
  36058. /**
  36059. * Stores the fill mode state
  36060. */
  36061. this._fillMode = Material.TriangleFillMode;
  36062. this.name = name;
  36063. this.id = name || BABYLON.Tools.RandomId();
  36064. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  36065. this.uniqueId = this._scene.getUniqueId();
  36066. if (this._scene.useRightHandedSystem) {
  36067. this.sideOrientation = Material.ClockWiseSideOrientation;
  36068. }
  36069. else {
  36070. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  36071. }
  36072. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  36073. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  36074. if (!doNotAdd) {
  36075. this._scene.materials.push(this);
  36076. this._scene.onNewMaterialAddedObservable.notifyObservers(this);
  36077. }
  36078. }
  36079. Object.defineProperty(Material, "TriangleFillMode", {
  36080. /**
  36081. * Returns the triangle fill mode
  36082. */
  36083. get: function () {
  36084. return Material._TriangleFillMode;
  36085. },
  36086. enumerable: true,
  36087. configurable: true
  36088. });
  36089. Object.defineProperty(Material, "WireFrameFillMode", {
  36090. /**
  36091. * Returns the wireframe mode
  36092. */
  36093. get: function () {
  36094. return Material._WireFrameFillMode;
  36095. },
  36096. enumerable: true,
  36097. configurable: true
  36098. });
  36099. Object.defineProperty(Material, "PointFillMode", {
  36100. /**
  36101. * Returns the point fill mode
  36102. */
  36103. get: function () {
  36104. return Material._PointFillMode;
  36105. },
  36106. enumerable: true,
  36107. configurable: true
  36108. });
  36109. Object.defineProperty(Material, "PointListDrawMode", {
  36110. /**
  36111. * Returns the point list draw mode
  36112. */
  36113. get: function () {
  36114. return Material._PointListDrawMode;
  36115. },
  36116. enumerable: true,
  36117. configurable: true
  36118. });
  36119. Object.defineProperty(Material, "LineListDrawMode", {
  36120. /**
  36121. * Returns the line list draw mode
  36122. */
  36123. get: function () {
  36124. return Material._LineListDrawMode;
  36125. },
  36126. enumerable: true,
  36127. configurable: true
  36128. });
  36129. Object.defineProperty(Material, "LineLoopDrawMode", {
  36130. /**
  36131. * Returns the line loop draw mode
  36132. */
  36133. get: function () {
  36134. return Material._LineLoopDrawMode;
  36135. },
  36136. enumerable: true,
  36137. configurable: true
  36138. });
  36139. Object.defineProperty(Material, "LineStripDrawMode", {
  36140. /**
  36141. * Returns the line strip draw mode
  36142. */
  36143. get: function () {
  36144. return Material._LineStripDrawMode;
  36145. },
  36146. enumerable: true,
  36147. configurable: true
  36148. });
  36149. Object.defineProperty(Material, "TriangleStripDrawMode", {
  36150. /**
  36151. * Returns the triangle strip draw mode
  36152. */
  36153. get: function () {
  36154. return Material._TriangleStripDrawMode;
  36155. },
  36156. enumerable: true,
  36157. configurable: true
  36158. });
  36159. Object.defineProperty(Material, "TriangleFanDrawMode", {
  36160. /**
  36161. * Returns the triangle fan draw mode
  36162. */
  36163. get: function () {
  36164. return Material._TriangleFanDrawMode;
  36165. },
  36166. enumerable: true,
  36167. configurable: true
  36168. });
  36169. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  36170. /**
  36171. * Returns the clock-wise side orientation
  36172. */
  36173. get: function () {
  36174. return Material._ClockWiseSideOrientation;
  36175. },
  36176. enumerable: true,
  36177. configurable: true
  36178. });
  36179. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  36180. /**
  36181. * Returns the counter clock-wise side orientation
  36182. */
  36183. get: function () {
  36184. return Material._CounterClockWiseSideOrientation;
  36185. },
  36186. enumerable: true,
  36187. configurable: true
  36188. });
  36189. Object.defineProperty(Material.prototype, "alpha", {
  36190. /**
  36191. * Gets the alpha value of the material
  36192. */
  36193. get: function () {
  36194. return this._alpha;
  36195. },
  36196. /**
  36197. * Sets the alpha value of the material
  36198. */
  36199. set: function (value) {
  36200. if (this._alpha === value) {
  36201. return;
  36202. }
  36203. this._alpha = value;
  36204. this.markAsDirty(Material.MiscDirtyFlag);
  36205. },
  36206. enumerable: true,
  36207. configurable: true
  36208. });
  36209. Object.defineProperty(Material.prototype, "backFaceCulling", {
  36210. /**
  36211. * Gets the back-face culling state
  36212. */
  36213. get: function () {
  36214. return this._backFaceCulling;
  36215. },
  36216. /**
  36217. * Sets the back-face culling state
  36218. */
  36219. set: function (value) {
  36220. if (this._backFaceCulling === value) {
  36221. return;
  36222. }
  36223. this._backFaceCulling = value;
  36224. this.markAsDirty(Material.TextureDirtyFlag);
  36225. },
  36226. enumerable: true,
  36227. configurable: true
  36228. });
  36229. Object.defineProperty(Material.prototype, "hasRenderTargetTextures", {
  36230. /**
  36231. * Gets a boolean indicating that current material needs to register RTT
  36232. */
  36233. get: function () {
  36234. return false;
  36235. },
  36236. enumerable: true,
  36237. configurable: true
  36238. });
  36239. Object.defineProperty(Material.prototype, "onDispose", {
  36240. /**
  36241. * Called during a dispose event
  36242. */
  36243. set: function (callback) {
  36244. if (this._onDisposeObserver) {
  36245. this.onDisposeObservable.remove(this._onDisposeObserver);
  36246. }
  36247. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  36248. },
  36249. enumerable: true,
  36250. configurable: true
  36251. });
  36252. Object.defineProperty(Material.prototype, "onBindObservable", {
  36253. /**
  36254. * An event triggered when the material is bound
  36255. */
  36256. get: function () {
  36257. if (!this._onBindObservable) {
  36258. this._onBindObservable = new BABYLON.Observable();
  36259. }
  36260. return this._onBindObservable;
  36261. },
  36262. enumerable: true,
  36263. configurable: true
  36264. });
  36265. Object.defineProperty(Material.prototype, "onBind", {
  36266. /**
  36267. * Called during a bind event
  36268. */
  36269. set: function (callback) {
  36270. if (this._onBindObserver) {
  36271. this.onBindObservable.remove(this._onBindObserver);
  36272. }
  36273. this._onBindObserver = this.onBindObservable.add(callback);
  36274. },
  36275. enumerable: true,
  36276. configurable: true
  36277. });
  36278. Object.defineProperty(Material.prototype, "onUnBindObservable", {
  36279. /**
  36280. * An event triggered when the material is unbound
  36281. */
  36282. get: function () {
  36283. if (!this._onUnBindObservable) {
  36284. this._onUnBindObservable = new BABYLON.Observable();
  36285. }
  36286. return this._onUnBindObservable;
  36287. },
  36288. enumerable: true,
  36289. configurable: true
  36290. });
  36291. Object.defineProperty(Material.prototype, "alphaMode", {
  36292. /**
  36293. * Gets the value of the alpha mode
  36294. */
  36295. get: function () {
  36296. return this._alphaMode;
  36297. },
  36298. /**
  36299. * Sets the value of the alpha mode.
  36300. *
  36301. * | Value | Type | Description |
  36302. * | --- | --- | --- |
  36303. * | 0 | ALPHA_DISABLE | |
  36304. * | 1 | ALPHA_ADD | |
  36305. * | 2 | ALPHA_COMBINE | |
  36306. * | 3 | ALPHA_SUBTRACT | |
  36307. * | 4 | ALPHA_MULTIPLY | |
  36308. * | 5 | ALPHA_MAXIMIZED | |
  36309. * | 6 | ALPHA_ONEONE | |
  36310. * | 7 | ALPHA_PREMULTIPLIED | |
  36311. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  36312. * | 9 | ALPHA_INTERPOLATE | |
  36313. * | 10 | ALPHA_SCREENMODE | |
  36314. *
  36315. */
  36316. set: function (value) {
  36317. if (this._alphaMode === value) {
  36318. return;
  36319. }
  36320. this._alphaMode = value;
  36321. this.markAsDirty(Material.TextureDirtyFlag);
  36322. },
  36323. enumerable: true,
  36324. configurable: true
  36325. });
  36326. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  36327. /**
  36328. * Gets the depth pre-pass value
  36329. */
  36330. get: function () {
  36331. return this._needDepthPrePass;
  36332. },
  36333. /**
  36334. * Sets the need depth pre-pass value
  36335. */
  36336. set: function (value) {
  36337. if (this._needDepthPrePass === value) {
  36338. return;
  36339. }
  36340. this._needDepthPrePass = value;
  36341. if (this._needDepthPrePass) {
  36342. this.checkReadyOnEveryCall = true;
  36343. }
  36344. },
  36345. enumerable: true,
  36346. configurable: true
  36347. });
  36348. Object.defineProperty(Material.prototype, "fogEnabled", {
  36349. /**
  36350. * Gets the value of the fog enabled state
  36351. */
  36352. get: function () {
  36353. return this._fogEnabled;
  36354. },
  36355. /**
  36356. * Sets the state for enabling fog
  36357. */
  36358. set: function (value) {
  36359. if (this._fogEnabled === value) {
  36360. return;
  36361. }
  36362. this._fogEnabled = value;
  36363. this.markAsDirty(Material.MiscDirtyFlag);
  36364. },
  36365. enumerable: true,
  36366. configurable: true
  36367. });
  36368. Object.defineProperty(Material.prototype, "wireframe", {
  36369. /**
  36370. * Gets a value specifying if wireframe mode is enabled
  36371. */
  36372. get: function () {
  36373. switch (this._fillMode) {
  36374. case Material.WireFrameFillMode:
  36375. case Material.LineListDrawMode:
  36376. case Material.LineLoopDrawMode:
  36377. case Material.LineStripDrawMode:
  36378. return true;
  36379. }
  36380. return this._scene.forceWireframe;
  36381. },
  36382. /**
  36383. * Sets the state of wireframe mode
  36384. */
  36385. set: function (value) {
  36386. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  36387. },
  36388. enumerable: true,
  36389. configurable: true
  36390. });
  36391. Object.defineProperty(Material.prototype, "pointsCloud", {
  36392. /**
  36393. * Gets the value specifying if point clouds are enabled
  36394. */
  36395. get: function () {
  36396. switch (this._fillMode) {
  36397. case Material.PointFillMode:
  36398. case Material.PointListDrawMode:
  36399. return true;
  36400. }
  36401. return this._scene.forcePointsCloud;
  36402. },
  36403. /**
  36404. * Sets the state of point cloud mode
  36405. */
  36406. set: function (value) {
  36407. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  36408. },
  36409. enumerable: true,
  36410. configurable: true
  36411. });
  36412. Object.defineProperty(Material.prototype, "fillMode", {
  36413. /**
  36414. * Gets the material fill mode
  36415. */
  36416. get: function () {
  36417. return this._fillMode;
  36418. },
  36419. /**
  36420. * Sets the material fill mode
  36421. */
  36422. set: function (value) {
  36423. if (this._fillMode === value) {
  36424. return;
  36425. }
  36426. this._fillMode = value;
  36427. this.markAsDirty(Material.MiscDirtyFlag);
  36428. },
  36429. enumerable: true,
  36430. configurable: true
  36431. });
  36432. /**
  36433. * Returns a string representation of the current material
  36434. * @param fullDetails defines a boolean indicating which levels of logging is desired
  36435. * @returns a string with material information
  36436. */
  36437. Material.prototype.toString = function (fullDetails) {
  36438. var ret = "Name: " + this.name;
  36439. if (fullDetails) {
  36440. }
  36441. return ret;
  36442. };
  36443. /**
  36444. * Gets the class name of the material
  36445. * @returns a string with the class name of the material
  36446. */
  36447. Material.prototype.getClassName = function () {
  36448. return "Material";
  36449. };
  36450. Object.defineProperty(Material.prototype, "isFrozen", {
  36451. /**
  36452. * Specifies if updates for the material been locked
  36453. */
  36454. get: function () {
  36455. return this.checkReadyOnlyOnce;
  36456. },
  36457. enumerable: true,
  36458. configurable: true
  36459. });
  36460. /**
  36461. * Locks updates for the material
  36462. */
  36463. Material.prototype.freeze = function () {
  36464. this.checkReadyOnlyOnce = true;
  36465. };
  36466. /**
  36467. * Unlocks updates for the material
  36468. */
  36469. Material.prototype.unfreeze = function () {
  36470. this.checkReadyOnlyOnce = false;
  36471. };
  36472. /**
  36473. * Specifies if the material is ready to be used
  36474. * @param mesh defines the mesh to check
  36475. * @param useInstances specifies if instances should be used
  36476. * @returns a boolean indicating if the material is ready to be used
  36477. */
  36478. Material.prototype.isReady = function (mesh, useInstances) {
  36479. return true;
  36480. };
  36481. /**
  36482. * Specifies that the submesh is ready to be used
  36483. * @param mesh defines the mesh to check
  36484. * @param subMesh defines which submesh to check
  36485. * @param useInstances specifies that instances should be used
  36486. * @returns a boolean indicating that the submesh is ready or not
  36487. */
  36488. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  36489. return false;
  36490. };
  36491. /**
  36492. * Returns the material effect
  36493. * @returns the effect associated with the material
  36494. */
  36495. Material.prototype.getEffect = function () {
  36496. return this._effect;
  36497. };
  36498. /**
  36499. * Returns the current scene
  36500. * @returns a Scene
  36501. */
  36502. Material.prototype.getScene = function () {
  36503. return this._scene;
  36504. };
  36505. /**
  36506. * Specifies if the material will require alpha blending
  36507. * @returns a boolean specifying if alpha blending is needed
  36508. */
  36509. Material.prototype.needAlphaBlending = function () {
  36510. return (this.alpha < 1.0);
  36511. };
  36512. /**
  36513. * Specifies if the mesh will require alpha blending
  36514. * @param mesh defines the mesh to check
  36515. * @returns a boolean specifying if alpha blending is needed for the mesh
  36516. */
  36517. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  36518. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  36519. };
  36520. /**
  36521. * Specifies if this material should be rendered in alpha test mode
  36522. * @returns a boolean specifying if an alpha test is needed.
  36523. */
  36524. Material.prototype.needAlphaTesting = function () {
  36525. return false;
  36526. };
  36527. /**
  36528. * Gets the texture used for the alpha test
  36529. * @returns the texture to use for alpha testing
  36530. */
  36531. Material.prototype.getAlphaTestTexture = function () {
  36532. return null;
  36533. };
  36534. /**
  36535. * Marks the material to indicate that it needs to be re-calculated
  36536. */
  36537. Material.prototype.markDirty = function () {
  36538. this._wasPreviouslyReady = false;
  36539. };
  36540. /** @hidden */
  36541. Material.prototype._preBind = function (effect, overrideOrientation) {
  36542. if (overrideOrientation === void 0) { overrideOrientation = null; }
  36543. var engine = this._scene.getEngine();
  36544. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  36545. var reverse = orientation === Material.ClockWiseSideOrientation;
  36546. engine.enableEffect(effect ? effect : this._effect);
  36547. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  36548. return reverse;
  36549. };
  36550. /**
  36551. * Binds the material to the mesh
  36552. * @param world defines the world transformation matrix
  36553. * @param mesh defines the mesh to bind the material to
  36554. */
  36555. Material.prototype.bind = function (world, mesh) {
  36556. };
  36557. /**
  36558. * Binds the submesh to the material
  36559. * @param world defines the world transformation matrix
  36560. * @param mesh defines the mesh containing the submesh
  36561. * @param subMesh defines the submesh to bind the material to
  36562. */
  36563. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  36564. };
  36565. /**
  36566. * Binds the world matrix to the material
  36567. * @param world defines the world transformation matrix
  36568. */
  36569. Material.prototype.bindOnlyWorldMatrix = function (world) {
  36570. };
  36571. /**
  36572. * Binds the scene's uniform buffer to the effect.
  36573. * @param effect defines the effect to bind to the scene uniform buffer
  36574. * @param sceneUbo defines the uniform buffer storing scene data
  36575. */
  36576. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  36577. sceneUbo.bindToEffect(effect, "Scene");
  36578. };
  36579. /**
  36580. * Binds the view matrix to the effect
  36581. * @param effect defines the effect to bind the view matrix to
  36582. */
  36583. Material.prototype.bindView = function (effect) {
  36584. if (!this._useUBO) {
  36585. effect.setMatrix("view", this.getScene().getViewMatrix());
  36586. }
  36587. else {
  36588. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36589. }
  36590. };
  36591. /**
  36592. * Binds the view projection matrix to the effect
  36593. * @param effect defines the effect to bind the view projection matrix to
  36594. */
  36595. Material.prototype.bindViewProjection = function (effect) {
  36596. if (!this._useUBO) {
  36597. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  36598. }
  36599. else {
  36600. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  36601. }
  36602. };
  36603. /**
  36604. * Specifies if material alpha testing should be turned on for the mesh
  36605. * @param mesh defines the mesh to check
  36606. */
  36607. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  36608. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  36609. };
  36610. /**
  36611. * Processes to execute after binding the material to a mesh
  36612. * @param mesh defines the rendered mesh
  36613. */
  36614. Material.prototype._afterBind = function (mesh) {
  36615. this._scene._cachedMaterial = this;
  36616. if (mesh) {
  36617. this._scene._cachedVisibility = mesh.visibility;
  36618. }
  36619. else {
  36620. this._scene._cachedVisibility = 1;
  36621. }
  36622. if (this._onBindObservable && mesh) {
  36623. this._onBindObservable.notifyObservers(mesh);
  36624. }
  36625. if (this.disableDepthWrite) {
  36626. var engine = this._scene.getEngine();
  36627. this._cachedDepthWriteState = engine.getDepthWrite();
  36628. engine.setDepthWrite(false);
  36629. }
  36630. };
  36631. /**
  36632. * Unbinds the material from the mesh
  36633. */
  36634. Material.prototype.unbind = function () {
  36635. if (this._onUnBindObservable) {
  36636. this._onUnBindObservable.notifyObservers(this);
  36637. }
  36638. if (this.disableDepthWrite) {
  36639. var engine = this._scene.getEngine();
  36640. engine.setDepthWrite(this._cachedDepthWriteState);
  36641. }
  36642. };
  36643. /**
  36644. * Gets the active textures from the material
  36645. * @returns an array of textures
  36646. */
  36647. Material.prototype.getActiveTextures = function () {
  36648. return [];
  36649. };
  36650. /**
  36651. * Specifies if the material uses a texture
  36652. * @param texture defines the texture to check against the material
  36653. * @returns a boolean specifying if the material uses the texture
  36654. */
  36655. Material.prototype.hasTexture = function (texture) {
  36656. return false;
  36657. };
  36658. /**
  36659. * Makes a duplicate of the material, and gives it a new name
  36660. * @param name defines the new name for the duplicated material
  36661. * @returns the cloned material
  36662. */
  36663. Material.prototype.clone = function (name) {
  36664. return null;
  36665. };
  36666. /**
  36667. * Gets the meshes bound to the material
  36668. * @returns an array of meshes bound to the material
  36669. */
  36670. Material.prototype.getBindedMeshes = function () {
  36671. var result = new Array();
  36672. for (var index = 0; index < this._scene.meshes.length; index++) {
  36673. var mesh = this._scene.meshes[index];
  36674. if (mesh.material === this) {
  36675. result.push(mesh);
  36676. }
  36677. }
  36678. return result;
  36679. };
  36680. /**
  36681. * Force shader compilation
  36682. * @param mesh defines the mesh associated with this material
  36683. * @param onCompiled defines a function to execute once the material is compiled
  36684. * @param options defines the options to configure the compilation
  36685. */
  36686. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  36687. var _this = this;
  36688. var localOptions = __assign({ clipPlane: false }, options);
  36689. var subMesh = new BABYLON.BaseSubMesh();
  36690. var scene = this.getScene();
  36691. var checkReady = function () {
  36692. if (!_this._scene || !_this._scene.getEngine()) {
  36693. return;
  36694. }
  36695. if (subMesh._materialDefines) {
  36696. subMesh._materialDefines._renderId = -1;
  36697. }
  36698. var clipPlaneState = scene.clipPlane;
  36699. if (localOptions.clipPlane) {
  36700. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  36701. }
  36702. if (_this.storeEffectOnSubMeshes) {
  36703. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  36704. if (onCompiled) {
  36705. onCompiled(_this);
  36706. }
  36707. }
  36708. else {
  36709. setTimeout(checkReady, 16);
  36710. }
  36711. }
  36712. else {
  36713. if (_this.isReady(mesh)) {
  36714. if (onCompiled) {
  36715. onCompiled(_this);
  36716. }
  36717. }
  36718. else {
  36719. setTimeout(checkReady, 16);
  36720. }
  36721. }
  36722. if (localOptions.clipPlane) {
  36723. scene.clipPlane = clipPlaneState;
  36724. }
  36725. };
  36726. checkReady();
  36727. };
  36728. /**
  36729. * Force shader compilation
  36730. * @param mesh defines the mesh that will use this material
  36731. * @param options defines additional options for compiling the shaders
  36732. * @returns a promise that resolves when the compilation completes
  36733. */
  36734. Material.prototype.forceCompilationAsync = function (mesh, options) {
  36735. var _this = this;
  36736. return new Promise(function (resolve) {
  36737. _this.forceCompilation(mesh, function () {
  36738. resolve();
  36739. }, options);
  36740. });
  36741. };
  36742. /**
  36743. * Marks a define in the material to indicate that it needs to be re-computed
  36744. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  36745. */
  36746. Material.prototype.markAsDirty = function (flag) {
  36747. if (flag & Material.TextureDirtyFlag) {
  36748. this._markAllSubMeshesAsTexturesDirty();
  36749. }
  36750. if (flag & Material.LightDirtyFlag) {
  36751. this._markAllSubMeshesAsLightsDirty();
  36752. }
  36753. if (flag & Material.FresnelDirtyFlag) {
  36754. this._markAllSubMeshesAsFresnelDirty();
  36755. }
  36756. if (flag & Material.AttributesDirtyFlag) {
  36757. this._markAllSubMeshesAsAttributesDirty();
  36758. }
  36759. if (flag & Material.MiscDirtyFlag) {
  36760. this._markAllSubMeshesAsMiscDirty();
  36761. }
  36762. this.getScene().resetCachedMaterial();
  36763. };
  36764. /**
  36765. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36766. * @param func defines a function which checks material defines against the submeshes
  36767. */
  36768. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36769. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36770. var mesh = _a[_i];
  36771. if (!mesh.subMeshes) {
  36772. continue;
  36773. }
  36774. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36775. var subMesh = _c[_b];
  36776. if (subMesh.getMaterial() !== this) {
  36777. continue;
  36778. }
  36779. if (!subMesh._materialDefines) {
  36780. continue;
  36781. }
  36782. func(subMesh._materialDefines);
  36783. }
  36784. }
  36785. };
  36786. /**
  36787. * Indicates that image processing needs to be re-calculated for all submeshes
  36788. */
  36789. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36790. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36791. };
  36792. /**
  36793. * Indicates that textures need to be re-calculated for all submeshes
  36794. */
  36795. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36796. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36797. };
  36798. /**
  36799. * Indicates that fresnel needs to be re-calculated for all submeshes
  36800. */
  36801. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36802. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36803. };
  36804. /**
  36805. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36806. */
  36807. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36808. this._markAllSubMeshesAsDirty(function (defines) {
  36809. defines.markAsFresnelDirty();
  36810. defines.markAsMiscDirty();
  36811. });
  36812. };
  36813. /**
  36814. * Indicates that lights need to be re-calculated for all submeshes
  36815. */
  36816. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36817. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36818. };
  36819. /**
  36820. * Indicates that attributes need to be re-calculated for all submeshes
  36821. */
  36822. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36823. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36824. };
  36825. /**
  36826. * Indicates that misc needs to be re-calculated for all submeshes
  36827. */
  36828. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36829. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36830. };
  36831. /**
  36832. * Indicates that textures and misc need to be re-calculated for all submeshes
  36833. */
  36834. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36835. this._markAllSubMeshesAsDirty(function (defines) {
  36836. defines.markAsTexturesDirty();
  36837. defines.markAsMiscDirty();
  36838. });
  36839. };
  36840. /**
  36841. * Disposes the material
  36842. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36843. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36844. */
  36845. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36846. // Animations
  36847. this.getScene().stopAnimation(this);
  36848. this.getScene().freeProcessedMaterials();
  36849. // Remove from scene
  36850. var index = this._scene.materials.indexOf(this);
  36851. if (index >= 0) {
  36852. this._scene.materials.splice(index, 1);
  36853. }
  36854. this._scene.onMaterialRemovedObservable.notifyObservers(this);
  36855. // Remove from meshes
  36856. for (index = 0; index < this._scene.meshes.length; index++) {
  36857. var mesh = this._scene.meshes[index];
  36858. if (mesh.material === this) {
  36859. mesh.material = null;
  36860. if (mesh.geometry) {
  36861. var geometry = (mesh.geometry);
  36862. if (this.storeEffectOnSubMeshes) {
  36863. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36864. var subMesh = _a[_i];
  36865. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36866. if (forceDisposeEffect && subMesh._materialEffect) {
  36867. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36868. }
  36869. }
  36870. }
  36871. else {
  36872. geometry._releaseVertexArrayObject(this._effect);
  36873. }
  36874. }
  36875. }
  36876. }
  36877. this._uniformBuffer.dispose();
  36878. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36879. if (forceDisposeEffect && this._effect) {
  36880. if (!this.storeEffectOnSubMeshes) {
  36881. this._scene.getEngine()._releaseEffect(this._effect);
  36882. }
  36883. this._effect = null;
  36884. }
  36885. // Callback
  36886. this.onDisposeObservable.notifyObservers(this);
  36887. this.onDisposeObservable.clear();
  36888. if (this._onBindObservable) {
  36889. this._onBindObservable.clear();
  36890. }
  36891. if (this._onUnBindObservable) {
  36892. this._onUnBindObservable.clear();
  36893. }
  36894. };
  36895. /**
  36896. * Serializes this material
  36897. * @returns the serialized material object
  36898. */
  36899. Material.prototype.serialize = function () {
  36900. return BABYLON.SerializationHelper.Serialize(this);
  36901. };
  36902. /**
  36903. * Creates a MultiMaterial from parsed MultiMaterial data.
  36904. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36905. * @param scene defines the hosting scene
  36906. * @returns a new MultiMaterial
  36907. */
  36908. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36909. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36910. multiMaterial.id = parsedMultiMaterial.id;
  36911. if (BABYLON.Tags) {
  36912. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36913. }
  36914. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36915. var subMatId = parsedMultiMaterial.materials[matIndex];
  36916. if (subMatId) {
  36917. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36918. }
  36919. else {
  36920. multiMaterial.subMaterials.push(null);
  36921. }
  36922. }
  36923. return multiMaterial;
  36924. };
  36925. /**
  36926. * Creates a material from parsed material data
  36927. * @param parsedMaterial defines parsed material data
  36928. * @param scene defines the hosting scene
  36929. * @param rootUrl defines the root URL to use to load textures
  36930. * @returns a new material
  36931. */
  36932. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36933. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36934. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36935. }
  36936. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36937. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36938. if (!BABYLON.LegacyPBRMaterial) {
  36939. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36940. return;
  36941. }
  36942. }
  36943. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36944. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36945. };
  36946. // Triangle views
  36947. Material._TriangleFillMode = 0;
  36948. Material._WireFrameFillMode = 1;
  36949. Material._PointFillMode = 2;
  36950. // Draw modes
  36951. Material._PointListDrawMode = 3;
  36952. Material._LineListDrawMode = 4;
  36953. Material._LineLoopDrawMode = 5;
  36954. Material._LineStripDrawMode = 6;
  36955. Material._TriangleStripDrawMode = 7;
  36956. Material._TriangleFanDrawMode = 8;
  36957. /**
  36958. * Stores the clock-wise side orientation
  36959. */
  36960. Material._ClockWiseSideOrientation = 0;
  36961. /**
  36962. * Stores the counter clock-wise side orientation
  36963. */
  36964. Material._CounterClockWiseSideOrientation = 1;
  36965. /**
  36966. * The dirty texture flag value
  36967. */
  36968. Material.TextureDirtyFlag = 1;
  36969. /**
  36970. * The dirty light flag value
  36971. */
  36972. Material.LightDirtyFlag = 2;
  36973. /**
  36974. * The dirty fresnel flag value
  36975. */
  36976. Material.FresnelDirtyFlag = 4;
  36977. /**
  36978. * The dirty attribute flag value
  36979. */
  36980. Material.AttributesDirtyFlag = 8;
  36981. /**
  36982. * The dirty misc flag value
  36983. */
  36984. Material.MiscDirtyFlag = 16;
  36985. /**
  36986. * The all dirty flag value
  36987. */
  36988. Material.AllDirtyFlag = 31;
  36989. __decorate([
  36990. BABYLON.serialize()
  36991. ], Material.prototype, "id", void 0);
  36992. __decorate([
  36993. BABYLON.serialize()
  36994. ], Material.prototype, "uniqueId", void 0);
  36995. __decorate([
  36996. BABYLON.serialize()
  36997. ], Material.prototype, "name", void 0);
  36998. __decorate([
  36999. BABYLON.serialize()
  37000. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  37001. __decorate([
  37002. BABYLON.serialize()
  37003. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  37004. __decorate([
  37005. BABYLON.serialize()
  37006. ], Material.prototype, "state", void 0);
  37007. __decorate([
  37008. BABYLON.serialize("alpha")
  37009. ], Material.prototype, "_alpha", void 0);
  37010. __decorate([
  37011. BABYLON.serialize("backFaceCulling")
  37012. ], Material.prototype, "_backFaceCulling", void 0);
  37013. __decorate([
  37014. BABYLON.serialize()
  37015. ], Material.prototype, "sideOrientation", void 0);
  37016. __decorate([
  37017. BABYLON.serialize("alphaMode")
  37018. ], Material.prototype, "_alphaMode", void 0);
  37019. __decorate([
  37020. BABYLON.serialize()
  37021. ], Material.prototype, "_needDepthPrePass", void 0);
  37022. __decorate([
  37023. BABYLON.serialize()
  37024. ], Material.prototype, "disableDepthWrite", void 0);
  37025. __decorate([
  37026. BABYLON.serialize()
  37027. ], Material.prototype, "forceDepthWrite", void 0);
  37028. __decorate([
  37029. BABYLON.serialize()
  37030. ], Material.prototype, "separateCullingPass", void 0);
  37031. __decorate([
  37032. BABYLON.serialize("fogEnabled")
  37033. ], Material.prototype, "_fogEnabled", void 0);
  37034. __decorate([
  37035. BABYLON.serialize()
  37036. ], Material.prototype, "pointSize", void 0);
  37037. __decorate([
  37038. BABYLON.serialize()
  37039. ], Material.prototype, "zOffset", void 0);
  37040. __decorate([
  37041. BABYLON.serialize()
  37042. ], Material.prototype, "wireframe", null);
  37043. __decorate([
  37044. BABYLON.serialize()
  37045. ], Material.prototype, "pointsCloud", null);
  37046. __decorate([
  37047. BABYLON.serialize()
  37048. ], Material.prototype, "fillMode", null);
  37049. return Material;
  37050. }());
  37051. BABYLON.Material = Material;
  37052. })(BABYLON || (BABYLON = {}));
  37053. //# sourceMappingURL=babylon.material.js.map
  37054. var BABYLON;
  37055. (function (BABYLON) {
  37056. /**
  37057. * Uniform buffer objects.
  37058. *
  37059. * Handles blocks of uniform on the GPU.
  37060. *
  37061. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37062. *
  37063. * For more information, please refer to :
  37064. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37065. */
  37066. var UniformBuffer = /** @class */ (function () {
  37067. /**
  37068. * Instantiates a new Uniform buffer objects.
  37069. *
  37070. * Handles blocks of uniform on the GPU.
  37071. *
  37072. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  37073. *
  37074. * For more information, please refer to :
  37075. * @see https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  37076. * @param engine Define the engine the buffer is associated with
  37077. * @param data Define the data contained in the buffer
  37078. * @param dynamic Define if the buffer is updatable
  37079. */
  37080. function UniformBuffer(engine, data, dynamic) {
  37081. this._engine = engine;
  37082. this._noUBO = !engine.supportsUniformBuffers;
  37083. this._dynamic = dynamic;
  37084. this._data = data || [];
  37085. this._uniformLocations = {};
  37086. this._uniformSizes = {};
  37087. this._uniformLocationPointer = 0;
  37088. this._needSync = false;
  37089. if (this._noUBO) {
  37090. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  37091. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  37092. this.updateFloat = this._updateFloatForEffect;
  37093. this.updateFloat2 = this._updateFloat2ForEffect;
  37094. this.updateFloat3 = this._updateFloat3ForEffect;
  37095. this.updateFloat4 = this._updateFloat4ForEffect;
  37096. this.updateMatrix = this._updateMatrixForEffect;
  37097. this.updateVector3 = this._updateVector3ForEffect;
  37098. this.updateVector4 = this._updateVector4ForEffect;
  37099. this.updateColor3 = this._updateColor3ForEffect;
  37100. this.updateColor4 = this._updateColor4ForEffect;
  37101. }
  37102. else {
  37103. this._engine._uniformBuffers.push(this);
  37104. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  37105. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  37106. this.updateFloat = this._updateFloatForUniform;
  37107. this.updateFloat2 = this._updateFloat2ForUniform;
  37108. this.updateFloat3 = this._updateFloat3ForUniform;
  37109. this.updateFloat4 = this._updateFloat4ForUniform;
  37110. this.updateMatrix = this._updateMatrixForUniform;
  37111. this.updateVector3 = this._updateVector3ForUniform;
  37112. this.updateVector4 = this._updateVector4ForUniform;
  37113. this.updateColor3 = this._updateColor3ForUniform;
  37114. this.updateColor4 = this._updateColor4ForUniform;
  37115. }
  37116. }
  37117. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  37118. /**
  37119. * Indicates if the buffer is using the WebGL2 UBO implementation,
  37120. * or just falling back on setUniformXXX calls.
  37121. */
  37122. get: function () {
  37123. return !this._noUBO;
  37124. },
  37125. enumerable: true,
  37126. configurable: true
  37127. });
  37128. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  37129. /**
  37130. * Indicates if the WebGL underlying uniform buffer is in sync
  37131. * with the javascript cache data.
  37132. */
  37133. get: function () {
  37134. return !this._needSync;
  37135. },
  37136. enumerable: true,
  37137. configurable: true
  37138. });
  37139. /**
  37140. * Indicates if the WebGL underlying uniform buffer is dynamic.
  37141. * Also, a dynamic UniformBuffer will disable cache verification and always
  37142. * update the underlying WebGL uniform buffer to the GPU.
  37143. * @returns if Dynamic, otherwise false
  37144. */
  37145. UniformBuffer.prototype.isDynamic = function () {
  37146. return this._dynamic !== undefined;
  37147. };
  37148. /**
  37149. * The data cache on JS side.
  37150. * @returns the underlying data as a float array
  37151. */
  37152. UniformBuffer.prototype.getData = function () {
  37153. return this._bufferData;
  37154. };
  37155. /**
  37156. * The underlying WebGL Uniform buffer.
  37157. * @returns the webgl buffer
  37158. */
  37159. UniformBuffer.prototype.getBuffer = function () {
  37160. return this._buffer;
  37161. };
  37162. /**
  37163. * std140 layout specifies how to align data within an UBO structure.
  37164. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  37165. * for specs.
  37166. */
  37167. UniformBuffer.prototype._fillAlignment = function (size) {
  37168. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  37169. // and 4x4 matrices
  37170. // TODO : change if other types are used
  37171. var alignment;
  37172. if (size <= 2) {
  37173. alignment = size;
  37174. }
  37175. else {
  37176. alignment = 4;
  37177. }
  37178. if ((this._uniformLocationPointer % alignment) !== 0) {
  37179. var oldPointer = this._uniformLocationPointer;
  37180. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  37181. var diff = this._uniformLocationPointer - oldPointer;
  37182. for (var i = 0; i < diff; i++) {
  37183. this._data.push(0);
  37184. }
  37185. }
  37186. };
  37187. /**
  37188. * Adds an uniform in the buffer.
  37189. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  37190. * for the layout to be correct !
  37191. * @param name Name of the uniform, as used in the uniform block in the shader.
  37192. * @param size Data size, or data directly.
  37193. */
  37194. UniformBuffer.prototype.addUniform = function (name, size) {
  37195. if (this._noUBO) {
  37196. return;
  37197. }
  37198. if (this._uniformLocations[name] !== undefined) {
  37199. // Already existing uniform
  37200. return;
  37201. }
  37202. // This function must be called in the order of the shader layout !
  37203. // size can be the size of the uniform, or data directly
  37204. var data;
  37205. if (size instanceof Array) {
  37206. data = size;
  37207. size = data.length;
  37208. }
  37209. else {
  37210. size = size;
  37211. data = [];
  37212. // Fill with zeros
  37213. for (var i = 0; i < size; i++) {
  37214. data.push(0);
  37215. }
  37216. }
  37217. this._fillAlignment(size);
  37218. this._uniformSizes[name] = size;
  37219. this._uniformLocations[name] = this._uniformLocationPointer;
  37220. this._uniformLocationPointer += size;
  37221. for (var i = 0; i < size; i++) {
  37222. this._data.push(data[i]);
  37223. }
  37224. this._needSync = true;
  37225. };
  37226. /**
  37227. * Adds a Matrix 4x4 to the uniform buffer.
  37228. * @param name Name of the uniform, as used in the uniform block in the shader.
  37229. * @param mat A 4x4 matrix.
  37230. */
  37231. UniformBuffer.prototype.addMatrix = function (name, mat) {
  37232. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  37233. };
  37234. /**
  37235. * Adds a vec2 to the uniform buffer.
  37236. * @param name Name of the uniform, as used in the uniform block in the shader.
  37237. * @param x Define the x component value of the vec2
  37238. * @param y Define the y component value of the vec2
  37239. */
  37240. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  37241. var temp = [x, y];
  37242. this.addUniform(name, temp);
  37243. };
  37244. /**
  37245. * Adds a vec3 to the uniform buffer.
  37246. * @param name Name of the uniform, as used in the uniform block in the shader.
  37247. * @param x Define the x component value of the vec3
  37248. * @param y Define the y component value of the vec3
  37249. * @param z Define the z component value of the vec3
  37250. */
  37251. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  37252. var temp = [x, y, z];
  37253. this.addUniform(name, temp);
  37254. };
  37255. /**
  37256. * Adds a vec3 to the uniform buffer.
  37257. * @param name Name of the uniform, as used in the uniform block in the shader.
  37258. * @param color Define the vec3 from a Color
  37259. */
  37260. UniformBuffer.prototype.addColor3 = function (name, color) {
  37261. var temp = new Array();
  37262. color.toArray(temp);
  37263. this.addUniform(name, temp);
  37264. };
  37265. /**
  37266. * Adds a vec4 to the uniform buffer.
  37267. * @param name Name of the uniform, as used in the uniform block in the shader.
  37268. * @param color Define the rgb components from a Color
  37269. * @param alpha Define the a component of the vec4
  37270. */
  37271. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  37272. var temp = new Array();
  37273. color.toArray(temp);
  37274. temp.push(alpha);
  37275. this.addUniform(name, temp);
  37276. };
  37277. /**
  37278. * Adds a vec3 to the uniform buffer.
  37279. * @param name Name of the uniform, as used in the uniform block in the shader.
  37280. * @param vector Define the vec3 components from a Vector
  37281. */
  37282. UniformBuffer.prototype.addVector3 = function (name, vector) {
  37283. var temp = new Array();
  37284. vector.toArray(temp);
  37285. this.addUniform(name, temp);
  37286. };
  37287. /**
  37288. * Adds a Matrix 3x3 to the uniform buffer.
  37289. * @param name Name of the uniform, as used in the uniform block in the shader.
  37290. */
  37291. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  37292. this.addUniform(name, 12);
  37293. };
  37294. /**
  37295. * Adds a Matrix 2x2 to the uniform buffer.
  37296. * @param name Name of the uniform, as used in the uniform block in the shader.
  37297. */
  37298. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  37299. this.addUniform(name, 8);
  37300. };
  37301. /**
  37302. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  37303. */
  37304. UniformBuffer.prototype.create = function () {
  37305. if (this._noUBO) {
  37306. return;
  37307. }
  37308. if (this._buffer) {
  37309. return; // nothing to do
  37310. }
  37311. // See spec, alignment must be filled as a vec4
  37312. this._fillAlignment(4);
  37313. this._bufferData = new Float32Array(this._data);
  37314. this._rebuild();
  37315. this._needSync = true;
  37316. };
  37317. /** @hidden */
  37318. UniformBuffer.prototype._rebuild = function () {
  37319. if (this._noUBO) {
  37320. return;
  37321. }
  37322. if (this._dynamic) {
  37323. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  37324. }
  37325. else {
  37326. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  37327. }
  37328. };
  37329. /**
  37330. * Updates the WebGL Uniform Buffer on the GPU.
  37331. * If the `dynamic` flag is set to true, no cache comparison is done.
  37332. * Otherwise, the buffer will be updated only if the cache differs.
  37333. */
  37334. UniformBuffer.prototype.update = function () {
  37335. if (!this._buffer) {
  37336. this.create();
  37337. return;
  37338. }
  37339. if (!this._dynamic && !this._needSync) {
  37340. return;
  37341. }
  37342. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  37343. this._needSync = false;
  37344. };
  37345. /**
  37346. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  37347. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37348. * @param data Define the flattened data
  37349. * @param size Define the size of the data.
  37350. */
  37351. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  37352. var location = this._uniformLocations[uniformName];
  37353. if (location === undefined) {
  37354. if (this._buffer) {
  37355. // Cannot add an uniform if the buffer is already created
  37356. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  37357. return;
  37358. }
  37359. this.addUniform(uniformName, size);
  37360. location = this._uniformLocations[uniformName];
  37361. }
  37362. if (!this._buffer) {
  37363. this.create();
  37364. }
  37365. if (!this._dynamic) {
  37366. // Cache for static uniform buffers
  37367. var changed = false;
  37368. for (var i = 0; i < size; i++) {
  37369. if (this._bufferData[location + i] !== data[i]) {
  37370. changed = true;
  37371. this._bufferData[location + i] = data[i];
  37372. }
  37373. }
  37374. this._needSync = this._needSync || changed;
  37375. }
  37376. else {
  37377. // No cache for dynamic
  37378. for (var i = 0; i < size; i++) {
  37379. this._bufferData[location + i] = data[i];
  37380. }
  37381. }
  37382. };
  37383. // Update methods
  37384. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  37385. // To match std140, matrix must be realigned
  37386. for (var i = 0; i < 3; i++) {
  37387. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  37388. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  37389. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  37390. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37391. }
  37392. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  37393. };
  37394. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  37395. this._currentEffect.setMatrix3x3(name, matrix);
  37396. };
  37397. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  37398. this._currentEffect.setMatrix2x2(name, matrix);
  37399. };
  37400. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  37401. // To match std140, matrix must be realigned
  37402. for (var i = 0; i < 2; i++) {
  37403. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  37404. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  37405. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  37406. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  37407. }
  37408. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  37409. };
  37410. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  37411. this._currentEffect.setFloat(name, x);
  37412. };
  37413. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  37414. UniformBuffer._tempBuffer[0] = x;
  37415. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  37416. };
  37417. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  37418. if (suffix === void 0) { suffix = ""; }
  37419. this._currentEffect.setFloat2(name + suffix, x, y);
  37420. };
  37421. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  37422. if (suffix === void 0) { suffix = ""; }
  37423. UniformBuffer._tempBuffer[0] = x;
  37424. UniformBuffer._tempBuffer[1] = y;
  37425. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  37426. };
  37427. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  37428. if (suffix === void 0) { suffix = ""; }
  37429. this._currentEffect.setFloat3(name + suffix, x, y, z);
  37430. };
  37431. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  37432. if (suffix === void 0) { suffix = ""; }
  37433. UniformBuffer._tempBuffer[0] = x;
  37434. UniformBuffer._tempBuffer[1] = y;
  37435. UniformBuffer._tempBuffer[2] = z;
  37436. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37437. };
  37438. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  37439. if (suffix === void 0) { suffix = ""; }
  37440. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  37441. };
  37442. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  37443. if (suffix === void 0) { suffix = ""; }
  37444. UniformBuffer._tempBuffer[0] = x;
  37445. UniformBuffer._tempBuffer[1] = y;
  37446. UniformBuffer._tempBuffer[2] = z;
  37447. UniformBuffer._tempBuffer[3] = w;
  37448. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37449. };
  37450. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  37451. this._currentEffect.setMatrix(name, mat);
  37452. };
  37453. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  37454. this.updateUniform(name, mat.toArray(), 16);
  37455. };
  37456. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  37457. this._currentEffect.setVector3(name, vector);
  37458. };
  37459. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  37460. vector.toArray(UniformBuffer._tempBuffer);
  37461. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37462. };
  37463. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  37464. this._currentEffect.setVector4(name, vector);
  37465. };
  37466. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  37467. vector.toArray(UniformBuffer._tempBuffer);
  37468. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37469. };
  37470. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  37471. if (suffix === void 0) { suffix = ""; }
  37472. this._currentEffect.setColor3(name + suffix, color);
  37473. };
  37474. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  37475. if (suffix === void 0) { suffix = ""; }
  37476. color.toArray(UniformBuffer._tempBuffer);
  37477. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  37478. };
  37479. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  37480. if (suffix === void 0) { suffix = ""; }
  37481. this._currentEffect.setColor4(name + suffix, color, alpha);
  37482. };
  37483. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  37484. if (suffix === void 0) { suffix = ""; }
  37485. color.toArray(UniformBuffer._tempBuffer);
  37486. UniformBuffer._tempBuffer[3] = alpha;
  37487. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  37488. };
  37489. /**
  37490. * Sets a sampler uniform on the effect.
  37491. * @param name Define the name of the sampler.
  37492. * @param texture Define the texture to set in the sampler
  37493. */
  37494. UniformBuffer.prototype.setTexture = function (name, texture) {
  37495. this._currentEffect.setTexture(name, texture);
  37496. };
  37497. /**
  37498. * Directly updates the value of the uniform in the cache AND on the GPU.
  37499. * @param uniformName Define the name of the uniform, as used in the uniform block in the shader.
  37500. * @param data Define the flattened data
  37501. */
  37502. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  37503. this.updateUniform(uniformName, data, data.length);
  37504. this.update();
  37505. };
  37506. /**
  37507. * Binds this uniform buffer to an effect.
  37508. * @param effect Define the effect to bind the buffer to
  37509. * @param name Name of the uniform block in the shader.
  37510. */
  37511. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  37512. this._currentEffect = effect;
  37513. if (this._noUBO || !this._buffer) {
  37514. return;
  37515. }
  37516. effect.bindUniformBuffer(this._buffer, name);
  37517. };
  37518. /**
  37519. * Disposes the uniform buffer.
  37520. */
  37521. UniformBuffer.prototype.dispose = function () {
  37522. if (this._noUBO) {
  37523. return;
  37524. }
  37525. var index = this._engine._uniformBuffers.indexOf(this);
  37526. if (index !== -1) {
  37527. this._engine._uniformBuffers.splice(index, 1);
  37528. }
  37529. if (!this._buffer) {
  37530. return;
  37531. }
  37532. if (this._engine._releaseBuffer(this._buffer)) {
  37533. this._buffer = null;
  37534. }
  37535. };
  37536. // Pool for avoiding memory leaks
  37537. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  37538. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  37539. return UniformBuffer;
  37540. }());
  37541. BABYLON.UniformBuffer = UniformBuffer;
  37542. })(BABYLON || (BABYLON = {}));
  37543. //# sourceMappingURL=babylon.uniformBuffer.js.map
  37544. var BABYLON;
  37545. (function (BABYLON) {
  37546. /**
  37547. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  37548. */
  37549. var VertexData = /** @class */ (function () {
  37550. function VertexData() {
  37551. }
  37552. /**
  37553. * Uses the passed data array to set the set the values for the specified kind of data
  37554. * @param data a linear array of floating numbers
  37555. * @param kind the type of data that is being set, eg positions, colors etc
  37556. */
  37557. VertexData.prototype.set = function (data, kind) {
  37558. switch (kind) {
  37559. case BABYLON.VertexBuffer.PositionKind:
  37560. this.positions = data;
  37561. break;
  37562. case BABYLON.VertexBuffer.NormalKind:
  37563. this.normals = data;
  37564. break;
  37565. case BABYLON.VertexBuffer.TangentKind:
  37566. this.tangents = data;
  37567. break;
  37568. case BABYLON.VertexBuffer.UVKind:
  37569. this.uvs = data;
  37570. break;
  37571. case BABYLON.VertexBuffer.UV2Kind:
  37572. this.uvs2 = data;
  37573. break;
  37574. case BABYLON.VertexBuffer.UV3Kind:
  37575. this.uvs3 = data;
  37576. break;
  37577. case BABYLON.VertexBuffer.UV4Kind:
  37578. this.uvs4 = data;
  37579. break;
  37580. case BABYLON.VertexBuffer.UV5Kind:
  37581. this.uvs5 = data;
  37582. break;
  37583. case BABYLON.VertexBuffer.UV6Kind:
  37584. this.uvs6 = data;
  37585. break;
  37586. case BABYLON.VertexBuffer.ColorKind:
  37587. this.colors = data;
  37588. break;
  37589. case BABYLON.VertexBuffer.MatricesIndicesKind:
  37590. this.matricesIndices = data;
  37591. break;
  37592. case BABYLON.VertexBuffer.MatricesWeightsKind:
  37593. this.matricesWeights = data;
  37594. break;
  37595. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  37596. this.matricesIndicesExtra = data;
  37597. break;
  37598. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  37599. this.matricesWeightsExtra = data;
  37600. break;
  37601. }
  37602. };
  37603. /**
  37604. * Associates the vertexData to the passed Mesh.
  37605. * Sets it as updatable or not (default `false`)
  37606. * @param mesh the mesh the vertexData is applied to
  37607. * @param updatable when used and having the value true allows new data to update the vertexData
  37608. * @returns the VertexData
  37609. */
  37610. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  37611. this._applyTo(mesh, updatable);
  37612. return this;
  37613. };
  37614. /**
  37615. * Associates the vertexData to the passed Geometry.
  37616. * Sets it as updatable or not (default `false`)
  37617. * @param geometry the geometry the vertexData is applied to
  37618. * @param updatable when used and having the value true allows new data to update the vertexData
  37619. * @returns VertexData
  37620. */
  37621. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  37622. this._applyTo(geometry, updatable);
  37623. return this;
  37624. };
  37625. /**
  37626. * Updates the associated mesh
  37627. * @param mesh the mesh to be updated
  37628. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37629. * @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
  37630. * @returns VertexData
  37631. */
  37632. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  37633. this._update(mesh);
  37634. return this;
  37635. };
  37636. /**
  37637. * Updates the associated geometry
  37638. * @param geometry the geometry to be updated
  37639. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  37640. * @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
  37641. * @returns VertexData.
  37642. */
  37643. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  37644. this._update(geometry);
  37645. return this;
  37646. };
  37647. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  37648. if (updatable === void 0) { updatable = false; }
  37649. if (this.positions) {
  37650. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  37651. }
  37652. if (this.normals) {
  37653. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  37654. }
  37655. if (this.tangents) {
  37656. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  37657. }
  37658. if (this.uvs) {
  37659. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  37660. }
  37661. if (this.uvs2) {
  37662. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  37663. }
  37664. if (this.uvs3) {
  37665. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  37666. }
  37667. if (this.uvs4) {
  37668. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  37669. }
  37670. if (this.uvs5) {
  37671. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  37672. }
  37673. if (this.uvs6) {
  37674. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  37675. }
  37676. if (this.colors) {
  37677. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  37678. }
  37679. if (this.matricesIndices) {
  37680. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  37681. }
  37682. if (this.matricesWeights) {
  37683. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  37684. }
  37685. if (this.matricesIndicesExtra) {
  37686. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  37687. }
  37688. if (this.matricesWeightsExtra) {
  37689. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  37690. }
  37691. if (this.indices) {
  37692. meshOrGeometry.setIndices(this.indices, null, updatable);
  37693. }
  37694. else {
  37695. meshOrGeometry.setIndices([], null);
  37696. }
  37697. return this;
  37698. };
  37699. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  37700. if (this.positions) {
  37701. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  37702. }
  37703. if (this.normals) {
  37704. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  37705. }
  37706. if (this.tangents) {
  37707. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  37708. }
  37709. if (this.uvs) {
  37710. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  37711. }
  37712. if (this.uvs2) {
  37713. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  37714. }
  37715. if (this.uvs3) {
  37716. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  37717. }
  37718. if (this.uvs4) {
  37719. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  37720. }
  37721. if (this.uvs5) {
  37722. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  37723. }
  37724. if (this.uvs6) {
  37725. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  37726. }
  37727. if (this.colors) {
  37728. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  37729. }
  37730. if (this.matricesIndices) {
  37731. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  37732. }
  37733. if (this.matricesWeights) {
  37734. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  37735. }
  37736. if (this.matricesIndicesExtra) {
  37737. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  37738. }
  37739. if (this.matricesWeightsExtra) {
  37740. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  37741. }
  37742. if (this.indices) {
  37743. meshOrGeometry.setIndices(this.indices, null);
  37744. }
  37745. return this;
  37746. };
  37747. /**
  37748. * Transforms each position and each normal of the vertexData according to the passed Matrix
  37749. * @param matrix the transforming matrix
  37750. * @returns the VertexData
  37751. */
  37752. VertexData.prototype.transform = function (matrix) {
  37753. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  37754. var transformed = BABYLON.Vector3.Zero();
  37755. var index;
  37756. if (this.positions) {
  37757. var position = BABYLON.Vector3.Zero();
  37758. for (index = 0; index < this.positions.length; index += 3) {
  37759. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  37760. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  37761. this.positions[index] = transformed.x;
  37762. this.positions[index + 1] = transformed.y;
  37763. this.positions[index + 2] = transformed.z;
  37764. }
  37765. }
  37766. if (this.normals) {
  37767. var normal = BABYLON.Vector3.Zero();
  37768. for (index = 0; index < this.normals.length; index += 3) {
  37769. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  37770. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  37771. this.normals[index] = transformed.x;
  37772. this.normals[index + 1] = transformed.y;
  37773. this.normals[index + 2] = transformed.z;
  37774. }
  37775. }
  37776. if (this.tangents) {
  37777. var tangent = BABYLON.Vector4.Zero();
  37778. var tangentTransformed = BABYLON.Vector4.Zero();
  37779. for (index = 0; index < this.tangents.length; index += 4) {
  37780. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  37781. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37782. this.tangents[index] = tangentTransformed.x;
  37783. this.tangents[index + 1] = tangentTransformed.y;
  37784. this.tangents[index + 2] = tangentTransformed.z;
  37785. this.tangents[index + 3] = tangentTransformed.w;
  37786. }
  37787. }
  37788. if (flip && this.indices) {
  37789. for (index = 0; index < this.indices.length; index += 3) {
  37790. var tmp = this.indices[index + 1];
  37791. this.indices[index + 1] = this.indices[index + 2];
  37792. this.indices[index + 2] = tmp;
  37793. }
  37794. }
  37795. return this;
  37796. };
  37797. /**
  37798. * Merges the passed VertexData into the current one
  37799. * @param other the VertexData to be merged into the current one
  37800. * @param use32BitsIndices defines a boolean indicating if indices must be store in a 32 bits array
  37801. * @returns the modified VertexData
  37802. */
  37803. VertexData.prototype.merge = function (other, use32BitsIndices) {
  37804. if (use32BitsIndices === void 0) { use32BitsIndices = false; }
  37805. this._validate();
  37806. other._validate();
  37807. if (!this.normals !== !other.normals ||
  37808. !this.tangents !== !other.tangents ||
  37809. !this.uvs !== !other.uvs ||
  37810. !this.uvs2 !== !other.uvs2 ||
  37811. !this.uvs3 !== !other.uvs3 ||
  37812. !this.uvs4 !== !other.uvs4 ||
  37813. !this.uvs5 !== !other.uvs5 ||
  37814. !this.uvs6 !== !other.uvs6 ||
  37815. !this.colors !== !other.colors ||
  37816. !this.matricesIndices !== !other.matricesIndices ||
  37817. !this.matricesWeights !== !other.matricesWeights ||
  37818. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37819. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37820. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37821. }
  37822. if (other.indices) {
  37823. if (!this.indices) {
  37824. this.indices = [];
  37825. }
  37826. var offset = this.positions ? this.positions.length / 3 : 0;
  37827. var isSrcTypedArray = this.indices.BYTES_PER_ELEMENT !== undefined;
  37828. if (isSrcTypedArray) {
  37829. var len = this.indices.length + other.indices.length;
  37830. var temp = use32BitsIndices || this.indices instanceof Uint32Array ? new Uint32Array(len) : new Uint16Array(len);
  37831. temp.set(this.indices);
  37832. var decal = this.indices.length;
  37833. for (var index = 0; index < other.indices.length; index++) {
  37834. temp[decal + index] = other.indices[index] + offset;
  37835. }
  37836. this.indices = temp;
  37837. }
  37838. else {
  37839. for (var index = 0; index < other.indices.length; index++) {
  37840. this.indices.push(other.indices[index] + offset);
  37841. }
  37842. }
  37843. }
  37844. this.positions = this._mergeElement(this.positions, other.positions);
  37845. this.normals = this._mergeElement(this.normals, other.normals);
  37846. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37847. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37848. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37849. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37850. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37851. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37852. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37853. this.colors = this._mergeElement(this.colors, other.colors);
  37854. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37855. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37856. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37857. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37858. return this;
  37859. };
  37860. VertexData.prototype._mergeElement = function (source, other) {
  37861. if (!source) {
  37862. return other;
  37863. }
  37864. if (!other) {
  37865. return source;
  37866. }
  37867. var len = other.length + source.length;
  37868. var isSrcTypedArray = source instanceof Float32Array;
  37869. var isOthTypedArray = other instanceof Float32Array;
  37870. // use non-loop method when the source is Float32Array
  37871. if (isSrcTypedArray) {
  37872. var ret32 = new Float32Array(len);
  37873. ret32.set(source);
  37874. ret32.set(other, source.length);
  37875. return ret32;
  37876. // source is number[], when other is also use concat
  37877. }
  37878. else if (!isOthTypedArray) {
  37879. return source.concat(other);
  37880. // source is a number[], but other is a Float32Array, loop required
  37881. }
  37882. else {
  37883. var ret = source.slice(0); // copy source to a separate array
  37884. for (var i = 0, len = other.length; i < len; i++) {
  37885. ret.push(other[i]);
  37886. }
  37887. return ret;
  37888. }
  37889. };
  37890. VertexData.prototype._validate = function () {
  37891. if (!this.positions) {
  37892. throw new Error("Positions are required");
  37893. }
  37894. var getElementCount = function (kind, values) {
  37895. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37896. if ((values.length % stride) !== 0) {
  37897. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37898. }
  37899. return values.length / stride;
  37900. };
  37901. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37902. var validateElementCount = function (kind, values) {
  37903. var elementCount = getElementCount(kind, values);
  37904. if (elementCount !== positionsElementCount) {
  37905. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37906. }
  37907. };
  37908. if (this.normals)
  37909. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37910. if (this.tangents)
  37911. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37912. if (this.uvs)
  37913. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37914. if (this.uvs2)
  37915. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37916. if (this.uvs3)
  37917. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37918. if (this.uvs4)
  37919. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37920. if (this.uvs5)
  37921. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37922. if (this.uvs6)
  37923. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37924. if (this.colors)
  37925. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37926. if (this.matricesIndices)
  37927. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37928. if (this.matricesWeights)
  37929. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37930. if (this.matricesIndicesExtra)
  37931. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37932. if (this.matricesWeightsExtra)
  37933. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37934. };
  37935. /**
  37936. * Serializes the VertexData
  37937. * @returns a serialized object
  37938. */
  37939. VertexData.prototype.serialize = function () {
  37940. var serializationObject = this.serialize();
  37941. if (this.positions) {
  37942. serializationObject.positions = this.positions;
  37943. }
  37944. if (this.normals) {
  37945. serializationObject.normals = this.normals;
  37946. }
  37947. if (this.tangents) {
  37948. serializationObject.tangents = this.tangents;
  37949. }
  37950. if (this.uvs) {
  37951. serializationObject.uvs = this.uvs;
  37952. }
  37953. if (this.uvs2) {
  37954. serializationObject.uvs2 = this.uvs2;
  37955. }
  37956. if (this.uvs3) {
  37957. serializationObject.uvs3 = this.uvs3;
  37958. }
  37959. if (this.uvs4) {
  37960. serializationObject.uvs4 = this.uvs4;
  37961. }
  37962. if (this.uvs5) {
  37963. serializationObject.uvs5 = this.uvs5;
  37964. }
  37965. if (this.uvs6) {
  37966. serializationObject.uvs6 = this.uvs6;
  37967. }
  37968. if (this.colors) {
  37969. serializationObject.colors = this.colors;
  37970. }
  37971. if (this.matricesIndices) {
  37972. serializationObject.matricesIndices = this.matricesIndices;
  37973. serializationObject.matricesIndices._isExpanded = true;
  37974. }
  37975. if (this.matricesWeights) {
  37976. serializationObject.matricesWeights = this.matricesWeights;
  37977. }
  37978. if (this.matricesIndicesExtra) {
  37979. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37980. serializationObject.matricesIndicesExtra._isExpanded = true;
  37981. }
  37982. if (this.matricesWeightsExtra) {
  37983. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37984. }
  37985. serializationObject.indices = this.indices;
  37986. return serializationObject;
  37987. };
  37988. // Statics
  37989. /**
  37990. * Extracts the vertexData from a mesh
  37991. * @param mesh the mesh from which to extract the VertexData
  37992. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37993. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37994. * @returns the object VertexData associated to the passed mesh
  37995. */
  37996. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37997. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37998. };
  37999. /**
  38000. * Extracts the vertexData from the geometry
  38001. * @param geometry the geometry from which to extract the VertexData
  38002. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  38003. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  38004. * @returns the object VertexData associated to the passed mesh
  38005. */
  38006. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  38007. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  38008. };
  38009. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  38010. var result = new VertexData();
  38011. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  38012. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  38013. }
  38014. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  38015. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  38016. }
  38017. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  38018. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  38019. }
  38020. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38021. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  38022. }
  38023. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  38024. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  38025. }
  38026. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  38027. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  38028. }
  38029. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  38030. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  38031. }
  38032. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  38033. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  38034. }
  38035. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  38036. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  38037. }
  38038. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  38039. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  38040. }
  38041. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  38042. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  38043. }
  38044. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  38045. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  38046. }
  38047. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  38048. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  38049. }
  38050. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  38051. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  38052. }
  38053. result.indices = meshOrGeometry.getIndices(copyWhenShared, forceCopy);
  38054. return result;
  38055. };
  38056. /**
  38057. * Creates the VertexData for a Ribbon
  38058. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  38059. * * pathArray array of paths, each of which an array of successive Vector3
  38060. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  38061. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  38062. * * 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
  38063. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38064. * * 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)
  38065. * * 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)
  38066. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  38067. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  38068. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  38069. * @returns the VertexData of the ribbon
  38070. */
  38071. VertexData.CreateRibbon = function (options) {
  38072. var pathArray = options.pathArray;
  38073. var closeArray = options.closeArray || false;
  38074. var closePath = options.closePath || false;
  38075. var invertUV = options.invertUV || false;
  38076. var defaultOffset = Math.floor(pathArray[0].length / 2);
  38077. var offset = options.offset || defaultOffset;
  38078. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  38079. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38080. var customUV = options.uvs;
  38081. var customColors = options.colors;
  38082. var positions = [];
  38083. var indices = [];
  38084. var normals = [];
  38085. var uvs = [];
  38086. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  38087. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  38088. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  38089. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  38090. var minlg; // minimal length among all paths from pathArray
  38091. var lg = []; // array of path lengths : nb of vertex per path
  38092. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  38093. var p; // path iterator
  38094. var i; // point iterator
  38095. var j; // point iterator
  38096. // if single path in pathArray
  38097. if (pathArray.length < 2) {
  38098. var ar1 = [];
  38099. var ar2 = [];
  38100. for (i = 0; i < pathArray[0].length - offset; i++) {
  38101. ar1.push(pathArray[0][i]);
  38102. ar2.push(pathArray[0][i + offset]);
  38103. }
  38104. pathArray = [ar1, ar2];
  38105. }
  38106. // positions and horizontal distances (u)
  38107. var idc = 0;
  38108. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  38109. var path;
  38110. var l;
  38111. minlg = pathArray[0].length;
  38112. var vectlg;
  38113. var dist;
  38114. for (p = 0; p < pathArray.length; p++) {
  38115. uTotalDistance[p] = 0;
  38116. us[p] = [0];
  38117. path = pathArray[p];
  38118. l = path.length;
  38119. minlg = (minlg < l) ? minlg : l;
  38120. j = 0;
  38121. while (j < l) {
  38122. positions.push(path[j].x, path[j].y, path[j].z);
  38123. if (j > 0) {
  38124. vectlg = path[j].subtract(path[j - 1]).length();
  38125. dist = vectlg + uTotalDistance[p];
  38126. us[p].push(dist);
  38127. uTotalDistance[p] = dist;
  38128. }
  38129. j++;
  38130. }
  38131. if (closePath) { // an extra hidden vertex is added in the "positions" array
  38132. j--;
  38133. positions.push(path[0].x, path[0].y, path[0].z);
  38134. vectlg = path[j].subtract(path[0]).length();
  38135. dist = vectlg + uTotalDistance[p];
  38136. us[p].push(dist);
  38137. uTotalDistance[p] = dist;
  38138. }
  38139. lg[p] = l + closePathCorr;
  38140. idx[p] = idc;
  38141. idc += (l + closePathCorr);
  38142. }
  38143. // vertical distances (v)
  38144. var path1;
  38145. var path2;
  38146. var vertex1 = null;
  38147. var vertex2 = null;
  38148. for (i = 0; i < minlg + closePathCorr; i++) {
  38149. vTotalDistance[i] = 0;
  38150. vs[i] = [0];
  38151. for (p = 0; p < pathArray.length - 1; p++) {
  38152. path1 = pathArray[p];
  38153. path2 = pathArray[p + 1];
  38154. if (i === minlg) { // closePath
  38155. vertex1 = path1[0];
  38156. vertex2 = path2[0];
  38157. }
  38158. else {
  38159. vertex1 = path1[i];
  38160. vertex2 = path2[i];
  38161. }
  38162. vectlg = vertex2.subtract(vertex1).length();
  38163. dist = vectlg + vTotalDistance[i];
  38164. vs[i].push(dist);
  38165. vTotalDistance[i] = dist;
  38166. }
  38167. if (closeArray && vertex2 && vertex1) {
  38168. path1 = pathArray[p];
  38169. path2 = pathArray[0];
  38170. if (i === minlg) { // closePath
  38171. vertex2 = path2[0];
  38172. }
  38173. vectlg = vertex2.subtract(vertex1).length();
  38174. dist = vectlg + vTotalDistance[i];
  38175. vTotalDistance[i] = dist;
  38176. }
  38177. }
  38178. // uvs
  38179. var u;
  38180. var v;
  38181. if (customUV) {
  38182. for (p = 0; p < customUV.length; p++) {
  38183. uvs.push(customUV[p].x, customUV[p].y);
  38184. }
  38185. }
  38186. else {
  38187. for (p = 0; p < pathArray.length; p++) {
  38188. for (i = 0; i < minlg + closePathCorr; i++) {
  38189. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  38190. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  38191. if (invertUV) {
  38192. uvs.push(v, u);
  38193. }
  38194. else {
  38195. uvs.push(u, v);
  38196. }
  38197. }
  38198. }
  38199. }
  38200. // indices
  38201. p = 0; // path index
  38202. var pi = 0; // positions array index
  38203. var l1 = lg[p] - 1; // path1 length
  38204. var l2 = lg[p + 1] - 1; // path2 length
  38205. var min = (l1 < l2) ? l1 : l2; // current path stop index
  38206. var shft = idx[1] - idx[0]; // shift
  38207. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  38208. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  38209. // 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
  38210. indices.push(pi, pi + shft, pi + 1);
  38211. indices.push(pi + shft + 1, pi + 1, pi + shft);
  38212. pi += 1;
  38213. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  38214. p++;
  38215. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  38216. shft = idx[0] - idx[p];
  38217. l1 = lg[p] - 1;
  38218. l2 = lg[0] - 1;
  38219. }
  38220. else {
  38221. shft = idx[p + 1] - idx[p];
  38222. l1 = lg[p] - 1;
  38223. l2 = lg[p + 1] - 1;
  38224. }
  38225. pi = idx[p];
  38226. min = (l1 < l2) ? l1 + pi : l2 + pi;
  38227. }
  38228. }
  38229. // normals
  38230. VertexData.ComputeNormals(positions, indices, normals);
  38231. if (closePath) { // update both the first and last vertex normals to their average value
  38232. var indexFirst = 0;
  38233. var indexLast = 0;
  38234. for (p = 0; p < pathArray.length; p++) {
  38235. indexFirst = idx[p] * 3;
  38236. if (p + 1 < pathArray.length) {
  38237. indexLast = (idx[p + 1] - 1) * 3;
  38238. }
  38239. else {
  38240. indexLast = normals.length - 3;
  38241. }
  38242. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  38243. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  38244. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  38245. normals[indexLast] = normals[indexFirst];
  38246. normals[indexLast + 1] = normals[indexFirst + 1];
  38247. normals[indexLast + 2] = normals[indexFirst + 2];
  38248. }
  38249. }
  38250. // sides
  38251. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38252. // Colors
  38253. var colors = null;
  38254. if (customColors) {
  38255. colors = new Float32Array(customColors.length * 4);
  38256. for (var c = 0; c < customColors.length; c++) {
  38257. colors[c * 4] = customColors[c].r;
  38258. colors[c * 4 + 1] = customColors[c].g;
  38259. colors[c * 4 + 2] = customColors[c].b;
  38260. colors[c * 4 + 3] = customColors[c].a;
  38261. }
  38262. }
  38263. // Result
  38264. var vertexData = new VertexData();
  38265. var positions32 = new Float32Array(positions);
  38266. var normals32 = new Float32Array(normals);
  38267. var uvs32 = new Float32Array(uvs);
  38268. vertexData.indices = indices;
  38269. vertexData.positions = positions32;
  38270. vertexData.normals = normals32;
  38271. vertexData.uvs = uvs32;
  38272. if (colors) {
  38273. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  38274. }
  38275. if (closePath) {
  38276. vertexData._idx = idx;
  38277. }
  38278. return vertexData;
  38279. };
  38280. /**
  38281. * Creates the VertexData for a box
  38282. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38283. * * size sets the width, height and depth of the box to the value of size, optional default 1
  38284. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  38285. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  38286. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  38287. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  38288. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  38289. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38290. * * 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)
  38291. * * 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)
  38292. * @returns the VertexData of the box
  38293. */
  38294. VertexData.CreateBox = function (options) {
  38295. var normalsSource = [
  38296. new BABYLON.Vector3(0, 0, 1),
  38297. new BABYLON.Vector3(0, 0, -1),
  38298. new BABYLON.Vector3(1, 0, 0),
  38299. new BABYLON.Vector3(-1, 0, 0),
  38300. new BABYLON.Vector3(0, 1, 0),
  38301. new BABYLON.Vector3(0, -1, 0)
  38302. ];
  38303. var indices = [];
  38304. var positions = [];
  38305. var normals = [];
  38306. var uvs = [];
  38307. var width = options.width || options.size || 1;
  38308. var height = options.height || options.size || 1;
  38309. var depth = options.depth || options.size || 1;
  38310. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38311. var faceUV = options.faceUV || new Array(6);
  38312. var faceColors = options.faceColors;
  38313. var colors = [];
  38314. // default face colors and UV if undefined
  38315. for (var f = 0; f < 6; f++) {
  38316. if (faceUV[f] === undefined) {
  38317. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38318. }
  38319. if (faceColors && faceColors[f] === undefined) {
  38320. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38321. }
  38322. }
  38323. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  38324. // Create each face in turn.
  38325. for (var index = 0; index < normalsSource.length; index++) {
  38326. var normal = normalsSource[index];
  38327. // Get two vectors perpendicular to the face normal and to each other.
  38328. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  38329. var side2 = BABYLON.Vector3.Cross(normal, side1);
  38330. // Six indices (two triangles) per face.
  38331. var verticesLength = positions.length / 3;
  38332. indices.push(verticesLength);
  38333. indices.push(verticesLength + 1);
  38334. indices.push(verticesLength + 2);
  38335. indices.push(verticesLength);
  38336. indices.push(verticesLength + 2);
  38337. indices.push(verticesLength + 3);
  38338. // Four vertices per face.
  38339. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  38340. positions.push(vertex.x, vertex.y, vertex.z);
  38341. normals.push(normal.x, normal.y, normal.z);
  38342. uvs.push(faceUV[index].z, faceUV[index].w);
  38343. if (faceColors) {
  38344. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38345. }
  38346. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  38347. positions.push(vertex.x, vertex.y, vertex.z);
  38348. normals.push(normal.x, normal.y, normal.z);
  38349. uvs.push(faceUV[index].x, faceUV[index].w);
  38350. if (faceColors) {
  38351. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38352. }
  38353. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  38354. positions.push(vertex.x, vertex.y, vertex.z);
  38355. normals.push(normal.x, normal.y, normal.z);
  38356. uvs.push(faceUV[index].x, faceUV[index].y);
  38357. if (faceColors) {
  38358. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38359. }
  38360. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  38361. positions.push(vertex.x, vertex.y, vertex.z);
  38362. normals.push(normal.x, normal.y, normal.z);
  38363. uvs.push(faceUV[index].z, faceUV[index].y);
  38364. if (faceColors) {
  38365. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  38366. }
  38367. }
  38368. // sides
  38369. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38370. // Result
  38371. var vertexData = new VertexData();
  38372. vertexData.indices = indices;
  38373. vertexData.positions = positions;
  38374. vertexData.normals = normals;
  38375. vertexData.uvs = uvs;
  38376. if (faceColors) {
  38377. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38378. vertexData.colors = totalColors;
  38379. }
  38380. return vertexData;
  38381. };
  38382. /**
  38383. * Creates the VertexData for an ellipsoid, defaults to a sphere
  38384. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38385. * * segments sets the number of horizontal strips optional, default 32
  38386. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  38387. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  38388. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  38389. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  38390. * * 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
  38391. * * 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
  38392. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38393. * * 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)
  38394. * * 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)
  38395. * @returns the VertexData of the ellipsoid
  38396. */
  38397. VertexData.CreateSphere = function (options) {
  38398. var segments = options.segments || 32;
  38399. var diameterX = options.diameterX || options.diameter || 1;
  38400. var diameterY = options.diameterY || options.diameter || 1;
  38401. var diameterZ = options.diameterZ || options.diameter || 1;
  38402. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38403. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  38404. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38405. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  38406. var totalZRotationSteps = 2 + segments;
  38407. var totalYRotationSteps = 2 * totalZRotationSteps;
  38408. var indices = [];
  38409. var positions = [];
  38410. var normals = [];
  38411. var uvs = [];
  38412. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  38413. var normalizedZ = zRotationStep / totalZRotationSteps;
  38414. var angleZ = normalizedZ * Math.PI * slice;
  38415. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  38416. var normalizedY = yRotationStep / totalYRotationSteps;
  38417. var angleY = normalizedY * Math.PI * 2 * arc;
  38418. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  38419. var rotationY = BABYLON.Matrix.RotationY(angleY);
  38420. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  38421. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  38422. var vertex = complete.multiply(radius);
  38423. var normal = complete.divide(radius).normalize();
  38424. positions.push(vertex.x, vertex.y, vertex.z);
  38425. normals.push(normal.x, normal.y, normal.z);
  38426. uvs.push(normalizedY, normalizedZ);
  38427. }
  38428. if (zRotationStep > 0) {
  38429. var verticesCount = positions.length / 3;
  38430. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  38431. indices.push((firstIndex));
  38432. indices.push((firstIndex + 1));
  38433. indices.push(firstIndex + totalYRotationSteps + 1);
  38434. indices.push((firstIndex + totalYRotationSteps + 1));
  38435. indices.push((firstIndex + 1));
  38436. indices.push((firstIndex + totalYRotationSteps + 2));
  38437. }
  38438. }
  38439. }
  38440. // Sides
  38441. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38442. // Result
  38443. var vertexData = new VertexData();
  38444. vertexData.indices = indices;
  38445. vertexData.positions = positions;
  38446. vertexData.normals = normals;
  38447. vertexData.uvs = uvs;
  38448. return vertexData;
  38449. };
  38450. /**
  38451. * Creates the VertexData for a cylinder, cone or prism
  38452. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38453. * * height sets the height (y direction) of the cylinder, optional, default 2
  38454. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  38455. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  38456. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  38457. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38458. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  38459. * * 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
  38460. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38461. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38462. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  38463. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  38464. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38465. * * 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)
  38466. * * 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)
  38467. * @returns the VertexData of the cylinder, cone or prism
  38468. */
  38469. VertexData.CreateCylinder = function (options) {
  38470. var height = options.height || 2;
  38471. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  38472. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  38473. var tessellation = options.tessellation || 24;
  38474. var subdivisions = options.subdivisions || 1;
  38475. var hasRings = options.hasRings ? true : false;
  38476. var enclose = options.enclose ? true : false;
  38477. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38478. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38479. var faceUV = options.faceUV || new Array(3);
  38480. var faceColors = options.faceColors;
  38481. // default face colors and UV if undefined
  38482. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  38483. var ringNb = (hasRings) ? subdivisions : 1;
  38484. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  38485. var f;
  38486. for (f = 0; f < surfaceNb; f++) {
  38487. if (faceColors && faceColors[f] === undefined) {
  38488. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38489. }
  38490. }
  38491. for (f = 0; f < surfaceNb; f++) {
  38492. if (faceUV && faceUV[f] === undefined) {
  38493. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38494. }
  38495. }
  38496. var indices = new Array();
  38497. var positions = new Array();
  38498. var normals = new Array();
  38499. var uvs = new Array();
  38500. var colors = new Array();
  38501. var angle_step = Math.PI * 2 * arc / tessellation;
  38502. var angle;
  38503. var h;
  38504. var radius;
  38505. var tan = (diameterBottom - diameterTop) / 2 / height;
  38506. var ringVertex = BABYLON.Vector3.Zero();
  38507. var ringNormal = BABYLON.Vector3.Zero();
  38508. var ringFirstVertex = BABYLON.Vector3.Zero();
  38509. var ringFirstNormal = BABYLON.Vector3.Zero();
  38510. var quadNormal = BABYLON.Vector3.Zero();
  38511. var Y = BABYLON.Axis.Y;
  38512. // positions, normals, uvs
  38513. var i;
  38514. var j;
  38515. var r;
  38516. var ringIdx = 1;
  38517. var s = 1; // surface index
  38518. var cs = 0;
  38519. var v = 0;
  38520. for (i = 0; i <= subdivisions; i++) {
  38521. h = i / subdivisions;
  38522. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  38523. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  38524. for (r = 0; r < ringIdx; r++) {
  38525. if (hasRings) {
  38526. s += r;
  38527. }
  38528. if (enclose) {
  38529. s += 2 * r;
  38530. }
  38531. for (j = 0; j <= tessellation; j++) {
  38532. angle = j * angle_step;
  38533. // position
  38534. ringVertex.x = Math.cos(-angle) * radius;
  38535. ringVertex.y = -height / 2 + h * height;
  38536. ringVertex.z = Math.sin(-angle) * radius;
  38537. // normal
  38538. if (diameterTop === 0 && i === subdivisions) {
  38539. // if no top cap, reuse former normals
  38540. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  38541. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  38542. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  38543. }
  38544. else {
  38545. ringNormal.x = ringVertex.x;
  38546. ringNormal.z = ringVertex.z;
  38547. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  38548. ringNormal.normalize();
  38549. }
  38550. // keep first ring vertex values for enclose
  38551. if (j === 0) {
  38552. ringFirstVertex.copyFrom(ringVertex);
  38553. ringFirstNormal.copyFrom(ringNormal);
  38554. }
  38555. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38556. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  38557. if (hasRings) {
  38558. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  38559. }
  38560. else {
  38561. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  38562. }
  38563. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  38564. if (faceColors) {
  38565. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  38566. }
  38567. }
  38568. // if enclose, add four vertices and their dedicated normals
  38569. if (arc !== 1 && enclose) {
  38570. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  38571. positions.push(0, ringVertex.y, 0);
  38572. positions.push(0, ringVertex.y, 0);
  38573. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  38574. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  38575. quadNormal.normalize();
  38576. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38577. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  38578. quadNormal.normalize();
  38579. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  38580. if (hasRings) {
  38581. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  38582. }
  38583. else {
  38584. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  38585. }
  38586. uvs.push(faceUV[s + 1].x, v);
  38587. uvs.push(faceUV[s + 1].z, v);
  38588. if (hasRings) {
  38589. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  38590. }
  38591. else {
  38592. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  38593. }
  38594. uvs.push(faceUV[s + 2].x, v);
  38595. uvs.push(faceUV[s + 2].z, v);
  38596. if (faceColors) {
  38597. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38598. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  38599. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38600. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  38601. }
  38602. }
  38603. if (cs !== s) {
  38604. cs = s;
  38605. }
  38606. }
  38607. }
  38608. // indices
  38609. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  38610. var s;
  38611. i = 0;
  38612. for (s = 0; s < subdivisions; s++) {
  38613. var i0 = 0;
  38614. var i1 = 0;
  38615. var i2 = 0;
  38616. var i3 = 0;
  38617. for (j = 0; j < tessellation; j++) {
  38618. i0 = i * (e + 1) + j;
  38619. i1 = (i + 1) * (e + 1) + j;
  38620. i2 = i * (e + 1) + (j + 1);
  38621. i3 = (i + 1) * (e + 1) + (j + 1);
  38622. indices.push(i0, i1, i2);
  38623. indices.push(i3, i2, i1);
  38624. }
  38625. if (arc !== 1 && enclose) { // if enclose, add two quads
  38626. indices.push(i0 + 2, i1 + 2, i2 + 2);
  38627. indices.push(i3 + 2, i2 + 2, i1 + 2);
  38628. indices.push(i0 + 4, i1 + 4, i2 + 4);
  38629. indices.push(i3 + 4, i2 + 4, i1 + 4);
  38630. }
  38631. i = (hasRings) ? (i + 2) : (i + 1);
  38632. }
  38633. // Caps
  38634. var createCylinderCap = function (isTop) {
  38635. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  38636. if (radius === 0) {
  38637. return;
  38638. }
  38639. // Cap positions, normals & uvs
  38640. var angle;
  38641. var circleVector;
  38642. var i;
  38643. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  38644. var c = null;
  38645. if (faceColors) {
  38646. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  38647. }
  38648. // cap center
  38649. var vbase = positions.length / 3;
  38650. var offset = isTop ? height / 2 : -height / 2;
  38651. var center = new BABYLON.Vector3(0, offset, 0);
  38652. positions.push(center.x, center.y, center.z);
  38653. normals.push(0, isTop ? 1 : -1, 0);
  38654. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  38655. if (c) {
  38656. colors.push(c.r, c.g, c.b, c.a);
  38657. }
  38658. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  38659. for (i = 0; i <= tessellation; i++) {
  38660. angle = Math.PI * 2 * i * arc / tessellation;
  38661. var cos = Math.cos(-angle);
  38662. var sin = Math.sin(-angle);
  38663. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  38664. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  38665. positions.push(circleVector.x, circleVector.y, circleVector.z);
  38666. normals.push(0, isTop ? 1 : -1, 0);
  38667. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  38668. if (c) {
  38669. colors.push(c.r, c.g, c.b, c.a);
  38670. }
  38671. }
  38672. // Cap indices
  38673. for (i = 0; i < tessellation; i++) {
  38674. if (!isTop) {
  38675. indices.push(vbase);
  38676. indices.push(vbase + (i + 1));
  38677. indices.push(vbase + (i + 2));
  38678. }
  38679. else {
  38680. indices.push(vbase);
  38681. indices.push(vbase + (i + 2));
  38682. indices.push(vbase + (i + 1));
  38683. }
  38684. }
  38685. };
  38686. // add caps to geometry
  38687. createCylinderCap(false);
  38688. createCylinderCap(true);
  38689. // Sides
  38690. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38691. var vertexData = new VertexData();
  38692. vertexData.indices = indices;
  38693. vertexData.positions = positions;
  38694. vertexData.normals = normals;
  38695. vertexData.uvs = uvs;
  38696. if (faceColors) {
  38697. vertexData.colors = colors;
  38698. }
  38699. return vertexData;
  38700. };
  38701. /**
  38702. * Creates the VertexData for a torus
  38703. * @param options an object used to set the following optional parameters for the box, required but can be empty
  38704. * * diameter the diameter of the torus, optional default 1
  38705. * * thickness the diameter of the tube forming the torus, optional default 0.5
  38706. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  38707. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38708. * * 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)
  38709. * * 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)
  38710. * @returns the VertexData of the torus
  38711. */
  38712. VertexData.CreateTorus = function (options) {
  38713. var indices = [];
  38714. var positions = [];
  38715. var normals = [];
  38716. var uvs = [];
  38717. var diameter = options.diameter || 1;
  38718. var thickness = options.thickness || 0.5;
  38719. var tessellation = options.tessellation || 16;
  38720. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38721. var stride = tessellation + 1;
  38722. for (var i = 0; i <= tessellation; i++) {
  38723. var u = i / tessellation;
  38724. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  38725. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  38726. for (var j = 0; j <= tessellation; j++) {
  38727. var v = 1 - j / tessellation;
  38728. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  38729. var dx = Math.cos(innerAngle);
  38730. var dy = Math.sin(innerAngle);
  38731. // Create a vertex.
  38732. var normal = new BABYLON.Vector3(dx, dy, 0);
  38733. var position = normal.scale(thickness / 2);
  38734. var textureCoordinate = new BABYLON.Vector2(u, v);
  38735. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  38736. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  38737. positions.push(position.x, position.y, position.z);
  38738. normals.push(normal.x, normal.y, normal.z);
  38739. uvs.push(textureCoordinate.x, textureCoordinate.y);
  38740. // And create indices for two triangles.
  38741. var nextI = (i + 1) % stride;
  38742. var nextJ = (j + 1) % stride;
  38743. indices.push(i * stride + j);
  38744. indices.push(i * stride + nextJ);
  38745. indices.push(nextI * stride + j);
  38746. indices.push(i * stride + nextJ);
  38747. indices.push(nextI * stride + nextJ);
  38748. indices.push(nextI * stride + j);
  38749. }
  38750. }
  38751. // Sides
  38752. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38753. // Result
  38754. var vertexData = new VertexData();
  38755. vertexData.indices = indices;
  38756. vertexData.positions = positions;
  38757. vertexData.normals = normals;
  38758. vertexData.uvs = uvs;
  38759. return vertexData;
  38760. };
  38761. /**
  38762. * Creates the VertexData of the LineSystem
  38763. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  38764. * - lines an array of lines, each line being an array of successive Vector3
  38765. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  38766. * @returns the VertexData of the LineSystem
  38767. */
  38768. VertexData.CreateLineSystem = function (options) {
  38769. var indices = [];
  38770. var positions = [];
  38771. var lines = options.lines;
  38772. var colors = options.colors;
  38773. var vertexColors = [];
  38774. var idx = 0;
  38775. for (var l = 0; l < lines.length; l++) {
  38776. var points = lines[l];
  38777. for (var index = 0; index < points.length; index++) {
  38778. positions.push(points[index].x, points[index].y, points[index].z);
  38779. if (colors) {
  38780. var color = colors[l];
  38781. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  38782. }
  38783. if (index > 0) {
  38784. indices.push(idx - 1);
  38785. indices.push(idx);
  38786. }
  38787. idx++;
  38788. }
  38789. }
  38790. var vertexData = new VertexData();
  38791. vertexData.indices = indices;
  38792. vertexData.positions = positions;
  38793. if (colors) {
  38794. vertexData.colors = vertexColors;
  38795. }
  38796. return vertexData;
  38797. };
  38798. /**
  38799. * Create the VertexData for a DashedLines
  38800. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38801. * - points an array successive Vector3
  38802. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38803. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38804. * - dashNb the intended total number of dashes, optional, default 200
  38805. * @returns the VertexData for the DashedLines
  38806. */
  38807. VertexData.CreateDashedLines = function (options) {
  38808. var dashSize = options.dashSize || 3;
  38809. var gapSize = options.gapSize || 1;
  38810. var dashNb = options.dashNb || 200;
  38811. var points = options.points;
  38812. var positions = new Array();
  38813. var indices = new Array();
  38814. var curvect = BABYLON.Vector3.Zero();
  38815. var lg = 0;
  38816. var nb = 0;
  38817. var shft = 0;
  38818. var dashshft = 0;
  38819. var curshft = 0;
  38820. var idx = 0;
  38821. var i = 0;
  38822. for (i = 0; i < points.length - 1; i++) {
  38823. points[i + 1].subtractToRef(points[i], curvect);
  38824. lg += curvect.length();
  38825. }
  38826. shft = lg / dashNb;
  38827. dashshft = dashSize * shft / (dashSize + gapSize);
  38828. for (i = 0; i < points.length - 1; i++) {
  38829. points[i + 1].subtractToRef(points[i], curvect);
  38830. nb = Math.floor(curvect.length() / shft);
  38831. curvect.normalize();
  38832. for (var j = 0; j < nb; j++) {
  38833. curshft = shft * j;
  38834. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38835. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38836. indices.push(idx, idx + 1);
  38837. idx += 2;
  38838. }
  38839. }
  38840. // Result
  38841. var vertexData = new VertexData();
  38842. vertexData.positions = positions;
  38843. vertexData.indices = indices;
  38844. return vertexData;
  38845. };
  38846. /**
  38847. * Creates the VertexData for a Ground
  38848. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38849. * - width the width (x direction) of the ground, optional, default 1
  38850. * - height the height (z direction) of the ground, optional, default 1
  38851. * - subdivisions the number of subdivisions per side, optional, default 1
  38852. * @returns the VertexData of the Ground
  38853. */
  38854. VertexData.CreateGround = function (options) {
  38855. var indices = [];
  38856. var positions = [];
  38857. var normals = [];
  38858. var uvs = [];
  38859. var row, col;
  38860. var width = options.width || 1;
  38861. var height = options.height || 1;
  38862. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38863. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38864. for (row = 0; row <= subdivisionsY; row++) {
  38865. for (col = 0; col <= subdivisionsX; col++) {
  38866. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38867. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38868. positions.push(position.x, position.y, position.z);
  38869. normals.push(normal.x, normal.y, normal.z);
  38870. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38871. }
  38872. }
  38873. for (row = 0; row < subdivisionsY; row++) {
  38874. for (col = 0; col < subdivisionsX; col++) {
  38875. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38876. indices.push(col + 1 + row * (subdivisionsX + 1));
  38877. indices.push(col + row * (subdivisionsX + 1));
  38878. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38879. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38880. indices.push(col + row * (subdivisionsX + 1));
  38881. }
  38882. }
  38883. // Result
  38884. var vertexData = new VertexData();
  38885. vertexData.indices = indices;
  38886. vertexData.positions = positions;
  38887. vertexData.normals = normals;
  38888. vertexData.uvs = uvs;
  38889. return vertexData;
  38890. };
  38891. /**
  38892. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38893. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38894. * * xmin the ground minimum X coordinate, optional, default -1
  38895. * * zmin the ground minimum Z coordinate, optional, default -1
  38896. * * xmax the ground maximum X coordinate, optional, default 1
  38897. * * zmax the ground maximum Z coordinate, optional, default 1
  38898. * * 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}
  38899. * * 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}
  38900. * @returns the VertexData of the TiledGround
  38901. */
  38902. VertexData.CreateTiledGround = function (options) {
  38903. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38904. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38905. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38906. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38907. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38908. var precision = options.precision || { w: 1, h: 1 };
  38909. var indices = new Array();
  38910. var positions = new Array();
  38911. var normals = new Array();
  38912. var uvs = new Array();
  38913. var row, col, tileRow, tileCol;
  38914. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38915. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38916. precision.w = (precision.w < 1) ? 1 : precision.w;
  38917. precision.h = (precision.h < 1) ? 1 : precision.h;
  38918. var tileSize = {
  38919. 'w': (xmax - xmin) / subdivisions.w,
  38920. 'h': (zmax - zmin) / subdivisions.h
  38921. };
  38922. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38923. // Indices
  38924. var base = positions.length / 3;
  38925. var rowLength = precision.w + 1;
  38926. for (row = 0; row < precision.h; row++) {
  38927. for (col = 0; col < precision.w; col++) {
  38928. var square = [
  38929. base + col + row * rowLength,
  38930. base + (col + 1) + row * rowLength,
  38931. base + (col + 1) + (row + 1) * rowLength,
  38932. base + col + (row + 1) * rowLength
  38933. ];
  38934. indices.push(square[1]);
  38935. indices.push(square[2]);
  38936. indices.push(square[3]);
  38937. indices.push(square[0]);
  38938. indices.push(square[1]);
  38939. indices.push(square[3]);
  38940. }
  38941. }
  38942. // Position, normals and uvs
  38943. var position = BABYLON.Vector3.Zero();
  38944. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38945. for (row = 0; row <= precision.h; row++) {
  38946. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38947. for (col = 0; col <= precision.w; col++) {
  38948. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38949. position.y = 0;
  38950. positions.push(position.x, position.y, position.z);
  38951. normals.push(normal.x, normal.y, normal.z);
  38952. uvs.push(col / precision.w, row / precision.h);
  38953. }
  38954. }
  38955. }
  38956. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38957. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38958. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38959. }
  38960. }
  38961. // Result
  38962. var vertexData = new VertexData();
  38963. vertexData.indices = indices;
  38964. vertexData.positions = positions;
  38965. vertexData.normals = normals;
  38966. vertexData.uvs = uvs;
  38967. return vertexData;
  38968. };
  38969. /**
  38970. * Creates the VertexData of the Ground designed from a heightmap
  38971. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38972. * * width the width (x direction) of the ground
  38973. * * height the height (z direction) of the ground
  38974. * * subdivisions the number of subdivisions per side
  38975. * * minHeight the minimum altitude on the ground, optional, default 0
  38976. * * maxHeight the maximum altitude on the ground, optional default 1
  38977. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38978. * * buffer the array holding the image color data
  38979. * * bufferWidth the width of image
  38980. * * bufferHeight the height of image
  38981. * * alphaFilter Remove any data where the alpha channel is below this value, defaults 0 (all data visible)
  38982. * @returns the VertexData of the Ground designed from a heightmap
  38983. */
  38984. VertexData.CreateGroundFromHeightMap = function (options) {
  38985. var indices = [];
  38986. var positions = [];
  38987. var normals = [];
  38988. var uvs = [];
  38989. var row, col;
  38990. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38991. var alphaFilter = options.alphaFilter || 0.0;
  38992. // Vertices
  38993. for (row = 0; row <= options.subdivisions; row++) {
  38994. for (col = 0; col <= options.subdivisions; col++) {
  38995. 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));
  38996. // Compute height
  38997. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38998. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38999. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  39000. var r = options.buffer[pos] / 255.0;
  39001. var g = options.buffer[pos + 1] / 255.0;
  39002. var b = options.buffer[pos + 2] / 255.0;
  39003. var a = options.buffer[pos + 3] / 255.0;
  39004. var gradient = r * filter.r + g * filter.g + b * filter.b;
  39005. // If our alpha channel is not within our filter then we will assign a 'special' height
  39006. // Then when building the indices, we will ignore any vertex that is using the special height
  39007. if (a >= alphaFilter)
  39008. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  39009. else {
  39010. position.y = options.minHeight - BABYLON.Epsilon; // We can't have a height below minHeight, normally.
  39011. }
  39012. // Add vertex
  39013. positions.push(position.x, position.y, position.z);
  39014. normals.push(0, 0, 0);
  39015. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  39016. }
  39017. }
  39018. // Indices
  39019. for (row = 0; row < options.subdivisions; row++) {
  39020. for (col = 0; col < options.subdivisions; col++) {
  39021. // Calculate Indices
  39022. var idx1 = (col + 1 + (row + 1) * (options.subdivisions + 1));
  39023. var idx2 = (col + 1 + row * (options.subdivisions + 1));
  39024. var idx3 = (col + row * (options.subdivisions + 1));
  39025. var idx4 = (col + (row + 1) * (options.subdivisions + 1));
  39026. // Check that all indices are visible (based on our special height)
  39027. // Only display the vertex if all Indices are visible
  39028. // Positions are stored x,y,z for each vertex, hence the * 3 and + 1 for height
  39029. var isVisibleIdx1 = positions[idx1 * 3 + 1] >= options.minHeight;
  39030. var isVisibleIdx2 = positions[idx2 * 3 + 1] >= options.minHeight;
  39031. var isVisibleIdx3 = positions[idx3 * 3 + 1] >= options.minHeight;
  39032. if (isVisibleIdx1 && isVisibleIdx2 && isVisibleIdx3) {
  39033. indices.push(idx1);
  39034. indices.push(idx2);
  39035. indices.push(idx3);
  39036. }
  39037. var isVisibleIdx4 = positions[idx4 * 3 + 1] >= options.minHeight;
  39038. if (isVisibleIdx4 && isVisibleIdx1 && isVisibleIdx3) {
  39039. indices.push(idx4);
  39040. indices.push(idx1);
  39041. indices.push(idx3);
  39042. }
  39043. }
  39044. }
  39045. // Normals
  39046. VertexData.ComputeNormals(positions, indices, normals);
  39047. // Result
  39048. var vertexData = new VertexData();
  39049. vertexData.indices = indices;
  39050. vertexData.positions = positions;
  39051. vertexData.normals = normals;
  39052. vertexData.uvs = uvs;
  39053. return vertexData;
  39054. };
  39055. /**
  39056. * Creates the VertexData for a Plane
  39057. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  39058. * * size sets the width and height of the plane to the value of size, optional default 1
  39059. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  39060. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  39061. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39062. * * 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)
  39063. * * 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)
  39064. * @returns the VertexData of the box
  39065. */
  39066. VertexData.CreatePlane = function (options) {
  39067. var indices = [];
  39068. var positions = [];
  39069. var normals = [];
  39070. var uvs = [];
  39071. var width = options.width || options.size || 1;
  39072. var height = options.height || options.size || 1;
  39073. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39074. // Vertices
  39075. var halfWidth = width / 2.0;
  39076. var halfHeight = height / 2.0;
  39077. positions.push(-halfWidth, -halfHeight, 0);
  39078. normals.push(0, 0, -1.0);
  39079. uvs.push(0.0, 0.0);
  39080. positions.push(halfWidth, -halfHeight, 0);
  39081. normals.push(0, 0, -1.0);
  39082. uvs.push(1.0, 0.0);
  39083. positions.push(halfWidth, halfHeight, 0);
  39084. normals.push(0, 0, -1.0);
  39085. uvs.push(1.0, 1.0);
  39086. positions.push(-halfWidth, halfHeight, 0);
  39087. normals.push(0, 0, -1.0);
  39088. uvs.push(0.0, 1.0);
  39089. // Indices
  39090. indices.push(0);
  39091. indices.push(1);
  39092. indices.push(2);
  39093. indices.push(0);
  39094. indices.push(2);
  39095. indices.push(3);
  39096. // Sides
  39097. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39098. // Result
  39099. var vertexData = new VertexData();
  39100. vertexData.indices = indices;
  39101. vertexData.positions = positions;
  39102. vertexData.normals = normals;
  39103. vertexData.uvs = uvs;
  39104. return vertexData;
  39105. };
  39106. /**
  39107. * Creates the VertexData of the Disc or regular Polygon
  39108. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  39109. * * radius the radius of the disc, optional default 0.5
  39110. * * tessellation the number of polygon sides, optional, default 64
  39111. * * 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
  39112. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39113. * * 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)
  39114. * * 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)
  39115. * @returns the VertexData of the box
  39116. */
  39117. VertexData.CreateDisc = function (options) {
  39118. var positions = new Array();
  39119. var indices = new Array();
  39120. var normals = new Array();
  39121. var uvs = new Array();
  39122. var radius = options.radius || 0.5;
  39123. var tessellation = options.tessellation || 64;
  39124. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  39125. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39126. // positions and uvs
  39127. positions.push(0, 0, 0); // disc center first
  39128. uvs.push(0.5, 0.5);
  39129. var theta = Math.PI * 2 * arc;
  39130. var step = theta / tessellation;
  39131. for (var a = 0; a < theta; a += step) {
  39132. var x = Math.cos(a);
  39133. var y = Math.sin(a);
  39134. var u = (x + 1) / 2;
  39135. var v = (1 - y) / 2;
  39136. positions.push(radius * x, radius * y, 0);
  39137. uvs.push(u, v);
  39138. }
  39139. if (arc === 1) {
  39140. positions.push(positions[3], positions[4], positions[5]); // close the circle
  39141. uvs.push(uvs[2], uvs[3]);
  39142. }
  39143. //indices
  39144. var vertexNb = positions.length / 3;
  39145. for (var i = 1; i < vertexNb - 1; i++) {
  39146. indices.push(i + 1, 0, i);
  39147. }
  39148. // result
  39149. VertexData.ComputeNormals(positions, indices, normals);
  39150. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39151. var vertexData = new VertexData();
  39152. vertexData.indices = indices;
  39153. vertexData.positions = positions;
  39154. vertexData.normals = normals;
  39155. vertexData.uvs = uvs;
  39156. return vertexData;
  39157. };
  39158. /**
  39159. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  39160. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  39161. * @param polygon a mesh built from polygonTriangulation.build()
  39162. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39163. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39164. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39165. * @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)
  39166. * @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)
  39167. * @returns the VertexData of the Polygon
  39168. */
  39169. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  39170. var faceUV = fUV || new Array(3);
  39171. var faceColors = fColors;
  39172. var colors = [];
  39173. // default face colors and UV if undefined
  39174. for (var f = 0; f < 3; f++) {
  39175. if (faceUV[f] === undefined) {
  39176. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39177. }
  39178. if (faceColors && faceColors[f] === undefined) {
  39179. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39180. }
  39181. }
  39182. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39183. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39184. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39185. var indices = polygon.getIndices();
  39186. // set face colours and textures
  39187. var idx = 0;
  39188. var face = 0;
  39189. for (var index = 0; index < normals.length; index += 3) {
  39190. //Edge Face no. 1
  39191. if (Math.abs(normals[index + 1]) < 0.001) {
  39192. face = 1;
  39193. }
  39194. //Top Face no. 0
  39195. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  39196. face = 0;
  39197. }
  39198. //Bottom Face no. 2
  39199. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  39200. face = 2;
  39201. }
  39202. idx = index / 3;
  39203. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  39204. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  39205. if (faceColors) {
  39206. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  39207. }
  39208. }
  39209. // sides
  39210. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  39211. // Result
  39212. var vertexData = new VertexData();
  39213. vertexData.indices = indices;
  39214. vertexData.positions = positions;
  39215. vertexData.normals = normals;
  39216. vertexData.uvs = uvs;
  39217. if (faceColors) {
  39218. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  39219. vertexData.colors = totalColors;
  39220. }
  39221. return vertexData;
  39222. };
  39223. /**
  39224. * Creates the VertexData of the IcoSphere
  39225. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  39226. * * radius the radius of the IcoSphere, optional default 1
  39227. * * radiusX allows stretching in the x direction, optional, default radius
  39228. * * radiusY allows stretching in the y direction, optional, default radius
  39229. * * radiusZ allows stretching in the z direction, optional, default radius
  39230. * * flat when true creates a flat shaded mesh, optional, default true
  39231. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39232. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39233. * * 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)
  39234. * * 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)
  39235. * @returns the VertexData of the IcoSphere
  39236. */
  39237. VertexData.CreateIcoSphere = function (options) {
  39238. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39239. var radius = options.radius || 1;
  39240. var flat = (options.flat === undefined) ? true : options.flat;
  39241. var subdivisions = options.subdivisions || 4;
  39242. var radiusX = options.radiusX || radius;
  39243. var radiusY = options.radiusY || radius;
  39244. var radiusZ = options.radiusZ || radius;
  39245. var t = (1 + Math.sqrt(5)) / 2;
  39246. // 12 vertex x,y,z
  39247. var ico_vertices = [
  39248. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  39249. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  39250. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  39251. ];
  39252. // index of 3 vertex makes a face of icopshere
  39253. var ico_indices = [
  39254. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  39255. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  39256. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  39257. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  39258. ];
  39259. // vertex for uv have aliased position, not for UV
  39260. var vertices_unalias_id = [
  39261. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  39262. // vertex alias
  39263. 0,
  39264. 2,
  39265. 3,
  39266. 3,
  39267. 3,
  39268. 4,
  39269. 7,
  39270. 8,
  39271. 9,
  39272. 9,
  39273. 10,
  39274. 11 // 23: B + 12
  39275. ];
  39276. // uv as integer step (not pixels !)
  39277. var ico_vertexuv = [
  39278. 5, 1, 3, 1, 6, 4, 0, 0,
  39279. 5, 3, 4, 2, 2, 2, 4, 0,
  39280. 2, 0, 1, 1, 6, 0, 6, 2,
  39281. // vertex alias (for same vertex on different faces)
  39282. 0, 4,
  39283. 3, 3,
  39284. 4, 4,
  39285. 3, 1,
  39286. 4, 2,
  39287. 4, 4,
  39288. 0, 2,
  39289. 1, 1,
  39290. 2, 2,
  39291. 3, 3,
  39292. 1, 3,
  39293. 2, 4 // 23: B + 12
  39294. ];
  39295. // Vertices[0, 1, ...9, A, B] : position on UV plane
  39296. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  39297. // First island of uv mapping
  39298. // v = 4h 3+ 2
  39299. // v = 3h 9+ 4
  39300. // v = 2h 9+ 5 B
  39301. // v = 1h 9 1 0
  39302. // v = 0h 3 8 7 A
  39303. // u = 0 1 2 3 4 5 6 *a
  39304. // Second island of uv mapping
  39305. // v = 4h 0+ B+ 4+
  39306. // v = 3h A+ 2+
  39307. // v = 2h 7+ 6 3+
  39308. // v = 1h 8+ 3+
  39309. // v = 0h
  39310. // u = 0 1 2 3 4 5 6 *a
  39311. // Face layout on texture UV mapping
  39312. // ============
  39313. // \ 4 /\ 16 / ======
  39314. // \ / \ / /\ 11 /
  39315. // \/ 7 \/ / \ /
  39316. // ======= / 10 \/
  39317. // /\ 17 /\ =======
  39318. // / \ / \ \ 15 /\
  39319. // / 8 \/ 12 \ \ / \
  39320. // ============ \/ 6 \
  39321. // \ 18 /\ ============
  39322. // \ / \ \ 5 /\ 0 /
  39323. // \/ 13 \ \ / \ /
  39324. // ======= \/ 1 \/
  39325. // =============
  39326. // /\ 19 /\ 2 /\
  39327. // / \ / \ / \
  39328. // / 14 \/ 9 \/ 3 \
  39329. // ===================
  39330. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  39331. var ustep = 138 / 1024;
  39332. var vstep = 239 / 1024;
  39333. var uoffset = 60 / 1024;
  39334. var voffset = 26 / 1024;
  39335. // Second island should have margin, not to touch the first island
  39336. // avoid any borderline artefact in pixel rounding
  39337. var island_u_offset = -40 / 1024;
  39338. var island_v_offset = +20 / 1024;
  39339. // face is either island 0 or 1 :
  39340. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  39341. var island = [
  39342. 0, 0, 0, 0, 1,
  39343. 0, 0, 1, 1, 0,
  39344. 0, 0, 1, 1, 0,
  39345. 0, 1, 1, 1, 0 // 15 - 19
  39346. ];
  39347. var indices = new Array();
  39348. var positions = new Array();
  39349. var normals = new Array();
  39350. var uvs = new Array();
  39351. var current_indice = 0;
  39352. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  39353. var face_vertex_pos = new Array(3);
  39354. var face_vertex_uv = new Array(3);
  39355. var v012;
  39356. for (v012 = 0; v012 < 3; v012++) {
  39357. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  39358. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  39359. }
  39360. // create all with normals
  39361. for (var face = 0; face < 20; face++) {
  39362. // 3 vertex per face
  39363. for (v012 = 0; v012 < 3; v012++) {
  39364. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  39365. var v_id = ico_indices[3 * face + v012];
  39366. // vertex have 3D position (x,y,z)
  39367. 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]);
  39368. // Normalize to get normal, then scale to radius
  39369. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  39370. // uv Coordinates from vertex ID
  39371. 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);
  39372. }
  39373. // Subdivide the face (interpolate pos, norm, uv)
  39374. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  39375. // - norm is linear interpolation of vertex corner normal
  39376. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  39377. // - uv is linear interpolation
  39378. //
  39379. // Topology is as below for sub-divide by 2
  39380. // vertex shown as v0,v1,v2
  39381. // interp index is i1 to progress in range [v0,v1[
  39382. // interp index is i2 to progress in range [v0,v2[
  39383. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  39384. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39385. //
  39386. //
  39387. // i2 v2
  39388. // ^ ^
  39389. // / / \
  39390. // / / \
  39391. // / / \
  39392. // / / (0,1) \
  39393. // / #---------\
  39394. // / / \ (0,0)'/ \
  39395. // / / \ / \
  39396. // / / \ / \
  39397. // / / (0,0) \ / (1,0) \
  39398. // / #---------#---------\
  39399. // v0 v1
  39400. //
  39401. // --------------------> i1
  39402. //
  39403. // interp of (i1,i2):
  39404. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  39405. // along i1 : lerp(x0,x1, i1/(S-i2))
  39406. //
  39407. // centroid of triangle is needed to get help normal computation
  39408. // (c1,c2) are used for centroid location
  39409. var interp_vertex = function (i1, i2, c1, c2) {
  39410. // vertex is interpolated from
  39411. // - face_vertex_pos[0..2]
  39412. // - face_vertex_uv[0..2]
  39413. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  39414. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  39415. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  39416. pos_interp.normalize();
  39417. var vertex_normal;
  39418. if (flat) {
  39419. // in flat mode, recalculate normal as face centroid normal
  39420. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  39421. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  39422. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  39423. }
  39424. else {
  39425. // in smooth mode, recalculate normal from each single vertex position
  39426. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  39427. }
  39428. // Vertex normal need correction due to X,Y,Z radius scaling
  39429. vertex_normal.x /= radiusX;
  39430. vertex_normal.y /= radiusY;
  39431. vertex_normal.z /= radiusZ;
  39432. vertex_normal.normalize();
  39433. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  39434. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  39435. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  39436. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  39437. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  39438. uvs.push(uv_interp.x, uv_interp.y);
  39439. // push each vertex has member of a face
  39440. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  39441. indices.push(current_indice);
  39442. current_indice++;
  39443. };
  39444. for (var i2 = 0; i2 < subdivisions; i2++) {
  39445. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  39446. // face : (i1,i2) for /\ :
  39447. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  39448. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39449. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39450. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  39451. if (i1 + i2 + 1 < subdivisions) {
  39452. // face : (i1,i2)' for \/ :
  39453. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  39454. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39455. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39456. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  39457. }
  39458. }
  39459. }
  39460. }
  39461. // Sides
  39462. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39463. // Result
  39464. var vertexData = new VertexData();
  39465. vertexData.indices = indices;
  39466. vertexData.positions = positions;
  39467. vertexData.normals = normals;
  39468. vertexData.uvs = uvs;
  39469. return vertexData;
  39470. };
  39471. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  39472. /**
  39473. * Creates the VertexData for a Polyhedron
  39474. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  39475. * * type provided types are:
  39476. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39477. * * 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)
  39478. * * size the size of the IcoSphere, optional default 1
  39479. * * sizeX allows stretching in the x direction, optional, default size
  39480. * * sizeY allows stretching in the y direction, optional, default size
  39481. * * sizeZ allows stretching in the z direction, optional, default size
  39482. * * 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
  39483. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  39484. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  39485. * * flat when true creates a flat shaded mesh, optional, default true
  39486. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  39487. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39488. * * 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)
  39489. * * 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)
  39490. * @returns the VertexData of the Polyhedron
  39491. */
  39492. VertexData.CreatePolyhedron = function (options) {
  39493. // provided polyhedron types :
  39494. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  39495. // 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)
  39496. var polyhedra = [];
  39497. 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]] };
  39498. 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]] };
  39499. polyhedra[2] = {
  39500. 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]],
  39501. 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]]
  39502. };
  39503. polyhedra[3] = {
  39504. 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]],
  39505. 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]]
  39506. };
  39507. polyhedra[4] = {
  39508. 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]],
  39509. 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]]
  39510. };
  39511. 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]] };
  39512. 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]] };
  39513. 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]] };
  39514. 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]] };
  39515. 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]] };
  39516. 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]] };
  39517. 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]] };
  39518. 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]] };
  39519. 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]] };
  39520. polyhedra[14] = {
  39521. 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]],
  39522. 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]]
  39523. };
  39524. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  39525. var size = options.size;
  39526. var sizeX = options.sizeX || size || 1;
  39527. var sizeY = options.sizeY || size || 1;
  39528. var sizeZ = options.sizeZ || size || 1;
  39529. var data = options.custom || polyhedra[type];
  39530. var nbfaces = data.face.length;
  39531. var faceUV = options.faceUV || new Array(nbfaces);
  39532. var faceColors = options.faceColors;
  39533. var flat = (options.flat === undefined) ? true : options.flat;
  39534. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39535. var positions = new Array();
  39536. var indices = new Array();
  39537. var normals = new Array();
  39538. var uvs = new Array();
  39539. var colors = new Array();
  39540. var index = 0;
  39541. var faceIdx = 0; // face cursor in the array "indexes"
  39542. var indexes = new Array();
  39543. var i = 0;
  39544. var f = 0;
  39545. var u, v, ang, x, y, tmp;
  39546. // default face colors and UV if undefined
  39547. if (flat) {
  39548. for (f = 0; f < nbfaces; f++) {
  39549. if (faceColors && faceColors[f] === undefined) {
  39550. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  39551. }
  39552. if (faceUV && faceUV[f] === undefined) {
  39553. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  39554. }
  39555. }
  39556. }
  39557. if (!flat) {
  39558. for (i = 0; i < data.vertex.length; i++) {
  39559. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  39560. uvs.push(0, 0);
  39561. }
  39562. for (f = 0; f < nbfaces; f++) {
  39563. for (i = 0; i < data.face[f].length - 2; i++) {
  39564. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  39565. }
  39566. }
  39567. }
  39568. else {
  39569. for (f = 0; f < nbfaces; f++) {
  39570. var fl = data.face[f].length; // number of vertices of the current face
  39571. ang = 2 * Math.PI / fl;
  39572. x = 0.5 * Math.tan(ang / 2);
  39573. y = 0.5;
  39574. // positions, uvs, colors
  39575. for (i = 0; i < fl; i++) {
  39576. // positions
  39577. 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);
  39578. indexes.push(index);
  39579. index++;
  39580. // uvs
  39581. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  39582. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  39583. uvs.push(u, v);
  39584. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  39585. y = x * Math.sin(ang) + y * Math.cos(ang);
  39586. x = tmp;
  39587. // colors
  39588. if (faceColors) {
  39589. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  39590. }
  39591. }
  39592. // indices from indexes
  39593. for (i = 0; i < fl - 2; i++) {
  39594. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  39595. }
  39596. faceIdx += fl;
  39597. }
  39598. }
  39599. VertexData.ComputeNormals(positions, indices, normals);
  39600. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39601. var vertexData = new VertexData();
  39602. vertexData.positions = positions;
  39603. vertexData.indices = indices;
  39604. vertexData.normals = normals;
  39605. vertexData.uvs = uvs;
  39606. if (faceColors && flat) {
  39607. vertexData.colors = colors;
  39608. }
  39609. return vertexData;
  39610. };
  39611. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  39612. /**
  39613. * Creates the VertexData for a TorusKnot
  39614. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  39615. * * radius the radius of the torus knot, optional, default 2
  39616. * * tube the thickness of the tube, optional, default 0.5
  39617. * * radialSegments the number of sides on each tube segments, optional, default 32
  39618. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  39619. * * p the number of windings around the z axis, optional, default 2
  39620. * * q the number of windings around the x axis, optional, default 3
  39621. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  39622. * * 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)
  39623. * * 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)
  39624. * @returns the VertexData of the Torus Knot
  39625. */
  39626. VertexData.CreateTorusKnot = function (options) {
  39627. var indices = new Array();
  39628. var positions = new Array();
  39629. var normals = new Array();
  39630. var uvs = new Array();
  39631. var radius = options.radius || 2;
  39632. var tube = options.tube || 0.5;
  39633. var radialSegments = options.radialSegments || 32;
  39634. var tubularSegments = options.tubularSegments || 32;
  39635. var p = options.p || 2;
  39636. var q = options.q || 3;
  39637. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39638. // Helper
  39639. var getPos = function (angle) {
  39640. var cu = Math.cos(angle);
  39641. var su = Math.sin(angle);
  39642. var quOverP = q / p * angle;
  39643. var cs = Math.cos(quOverP);
  39644. var tx = radius * (2 + cs) * 0.5 * cu;
  39645. var ty = radius * (2 + cs) * su * 0.5;
  39646. var tz = radius * Math.sin(quOverP) * 0.5;
  39647. return new BABYLON.Vector3(tx, ty, tz);
  39648. };
  39649. // Vertices
  39650. var i;
  39651. var j;
  39652. for (i = 0; i <= radialSegments; i++) {
  39653. var modI = i % radialSegments;
  39654. var u = modI / radialSegments * 2 * p * Math.PI;
  39655. var p1 = getPos(u);
  39656. var p2 = getPos(u + 0.01);
  39657. var tang = p2.subtract(p1);
  39658. var n = p2.add(p1);
  39659. var bitan = BABYLON.Vector3.Cross(tang, n);
  39660. n = BABYLON.Vector3.Cross(bitan, tang);
  39661. bitan.normalize();
  39662. n.normalize();
  39663. for (j = 0; j < tubularSegments; j++) {
  39664. var modJ = j % tubularSegments;
  39665. var v = modJ / tubularSegments * 2 * Math.PI;
  39666. var cx = -tube * Math.cos(v);
  39667. var cy = tube * Math.sin(v);
  39668. positions.push(p1.x + cx * n.x + cy * bitan.x);
  39669. positions.push(p1.y + cx * n.y + cy * bitan.y);
  39670. positions.push(p1.z + cx * n.z + cy * bitan.z);
  39671. uvs.push(i / radialSegments);
  39672. uvs.push(j / tubularSegments);
  39673. }
  39674. }
  39675. for (i = 0; i < radialSegments; i++) {
  39676. for (j = 0; j < tubularSegments; j++) {
  39677. var jNext = (j + 1) % tubularSegments;
  39678. var a = i * tubularSegments + j;
  39679. var b = (i + 1) * tubularSegments + j;
  39680. var c = (i + 1) * tubularSegments + jNext;
  39681. var d = i * tubularSegments + jNext;
  39682. indices.push(d);
  39683. indices.push(b);
  39684. indices.push(a);
  39685. indices.push(d);
  39686. indices.push(c);
  39687. indices.push(b);
  39688. }
  39689. }
  39690. // Normals
  39691. VertexData.ComputeNormals(positions, indices, normals);
  39692. // Sides
  39693. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  39694. // Result
  39695. var vertexData = new VertexData();
  39696. vertexData.indices = indices;
  39697. vertexData.positions = positions;
  39698. vertexData.normals = normals;
  39699. vertexData.uvs = uvs;
  39700. return vertexData;
  39701. };
  39702. // Tools
  39703. /**
  39704. * Compute normals for given positions and indices
  39705. * @param positions an array of vertex positions, [...., x, y, z, ......]
  39706. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  39707. * @param normals an array of vertex normals, [...., x, y, z, ......]
  39708. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  39709. * * facetNormals : optional array of facet normals (vector3)
  39710. * * facetPositions : optional array of facet positions (vector3)
  39711. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  39712. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  39713. * * bInfo : optional bounding info, required for facetPartitioning computation
  39714. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  39715. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  39716. * * useRightHandedSystem: optional boolean to for right handed system computation
  39717. * * depthSort : optional boolean to enable the facet depth sort computation
  39718. * * distanceTo : optional Vector3 to compute the facet depth from this location
  39719. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  39720. */
  39721. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  39722. // temporary scalar variables
  39723. var index = 0; // facet index
  39724. var p1p2x = 0.0; // p1p2 vector x coordinate
  39725. var p1p2y = 0.0; // p1p2 vector y coordinate
  39726. var p1p2z = 0.0; // p1p2 vector z coordinate
  39727. var p3p2x = 0.0; // p3p2 vector x coordinate
  39728. var p3p2y = 0.0; // p3p2 vector y coordinate
  39729. var p3p2z = 0.0; // p3p2 vector z coordinate
  39730. var faceNormalx = 0.0; // facet normal x coordinate
  39731. var faceNormaly = 0.0; // facet normal y coordinate
  39732. var faceNormalz = 0.0; // facet normal z coordinate
  39733. var length = 0.0; // facet normal length before normalization
  39734. var v1x = 0; // vector1 x index in the positions array
  39735. var v1y = 0; // vector1 y index in the positions array
  39736. var v1z = 0; // vector1 z index in the positions array
  39737. var v2x = 0; // vector2 x index in the positions array
  39738. var v2y = 0; // vector2 y index in the positions array
  39739. var v2z = 0; // vector2 z index in the positions array
  39740. var v3x = 0; // vector3 x index in the positions array
  39741. var v3y = 0; // vector3 y index in the positions array
  39742. var v3z = 0; // vector3 z index in the positions array
  39743. var computeFacetNormals = false;
  39744. var computeFacetPositions = false;
  39745. var computeFacetPartitioning = false;
  39746. var computeDepthSort = false;
  39747. var faceNormalSign = 1;
  39748. var ratio = 0;
  39749. var distanceTo = null;
  39750. if (options) {
  39751. computeFacetNormals = (options.facetNormals) ? true : false;
  39752. computeFacetPositions = (options.facetPositions) ? true : false;
  39753. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  39754. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  39755. ratio = options.ratio || 0;
  39756. computeDepthSort = (options.depthSort) ? true : false;
  39757. distanceTo = (options.distanceTo);
  39758. if (computeDepthSort) {
  39759. if (distanceTo === undefined) {
  39760. distanceTo = BABYLON.Vector3.Zero();
  39761. }
  39762. var depthSortedFacets = options.depthSortedFacets;
  39763. }
  39764. }
  39765. // facetPartitioning reinit if needed
  39766. var xSubRatio = 0;
  39767. var ySubRatio = 0;
  39768. var zSubRatio = 0;
  39769. var subSq = 0;
  39770. if (computeFacetPartitioning && options && options.bbSize) {
  39771. var ox = 0; // X partitioning index for facet position
  39772. var oy = 0; // Y partinioning index for facet position
  39773. var oz = 0; // Z partinioning index for facet position
  39774. var b1x = 0; // X partitioning index for facet v1 vertex
  39775. var b1y = 0; // Y partitioning index for facet v1 vertex
  39776. var b1z = 0; // z partitioning index for facet v1 vertex
  39777. var b2x = 0; // X partitioning index for facet v2 vertex
  39778. var b2y = 0; // Y partitioning index for facet v2 vertex
  39779. var b2z = 0; // Z partitioning index for facet v2 vertex
  39780. var b3x = 0; // X partitioning index for facet v3 vertex
  39781. var b3y = 0; // Y partitioning index for facet v3 vertex
  39782. var b3z = 0; // Z partitioning index for facet v3 vertex
  39783. var block_idx_o = 0; // facet barycenter block index
  39784. var block_idx_v1 = 0; // v1 vertex block index
  39785. var block_idx_v2 = 0; // v2 vertex block index
  39786. var block_idx_v3 = 0; // v3 vertex block index
  39787. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  39788. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  39789. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  39790. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  39791. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  39792. subSq = options.subDiv.max * options.subDiv.max;
  39793. options.facetPartitioning.length = 0;
  39794. }
  39795. // reset the normals
  39796. for (index = 0; index < positions.length; index++) {
  39797. normals[index] = 0.0;
  39798. }
  39799. // Loop : 1 indice triplet = 1 facet
  39800. var nbFaces = (indices.length / 3) | 0;
  39801. for (index = 0; index < nbFaces; index++) {
  39802. // get the indexes of the coordinates of each vertex of the facet
  39803. v1x = indices[index * 3] * 3;
  39804. v1y = v1x + 1;
  39805. v1z = v1x + 2;
  39806. v2x = indices[index * 3 + 1] * 3;
  39807. v2y = v2x + 1;
  39808. v2z = v2x + 2;
  39809. v3x = indices[index * 3 + 2] * 3;
  39810. v3y = v3x + 1;
  39811. v3z = v3x + 2;
  39812. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  39813. p1p2y = positions[v1y] - positions[v2y];
  39814. p1p2z = positions[v1z] - positions[v2z];
  39815. p3p2x = positions[v3x] - positions[v2x];
  39816. p3p2y = positions[v3y] - positions[v2y];
  39817. p3p2z = positions[v3z] - positions[v2z];
  39818. // compute the face normal with the cross product
  39819. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  39820. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39821. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39822. // normalize this normal and store it in the array facetData
  39823. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39824. length = (length === 0) ? 1.0 : length;
  39825. faceNormalx /= length;
  39826. faceNormaly /= length;
  39827. faceNormalz /= length;
  39828. if (computeFacetNormals && options) {
  39829. options.facetNormals[index].x = faceNormalx;
  39830. options.facetNormals[index].y = faceNormaly;
  39831. options.facetNormals[index].z = faceNormalz;
  39832. }
  39833. if (computeFacetPositions && options) {
  39834. // compute and the facet barycenter coordinates in the array facetPositions
  39835. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39836. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39837. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39838. }
  39839. if (computeFacetPartitioning && options) {
  39840. // store the facet indexes in arrays in the main facetPartitioning array :
  39841. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39842. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39843. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39844. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39845. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39846. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39847. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39848. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39849. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39850. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39851. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39852. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39853. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39854. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39855. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39856. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39857. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39858. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39859. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39860. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39861. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39862. // push each facet index in each block containing the vertex
  39863. options.facetPartitioning[block_idx_v1].push(index);
  39864. if (block_idx_v2 != block_idx_v1) {
  39865. options.facetPartitioning[block_idx_v2].push(index);
  39866. }
  39867. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39868. options.facetPartitioning[block_idx_v3].push(index);
  39869. }
  39870. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39871. options.facetPartitioning[block_idx_o].push(index);
  39872. }
  39873. }
  39874. if (computeDepthSort && options && options.facetPositions) {
  39875. var dsf = depthSortedFacets[index];
  39876. dsf.ind = index * 3;
  39877. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39878. }
  39879. // compute the normals anyway
  39880. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39881. normals[v1y] += faceNormaly;
  39882. normals[v1z] += faceNormalz;
  39883. normals[v2x] += faceNormalx;
  39884. normals[v2y] += faceNormaly;
  39885. normals[v2z] += faceNormalz;
  39886. normals[v3x] += faceNormalx;
  39887. normals[v3y] += faceNormaly;
  39888. normals[v3z] += faceNormalz;
  39889. }
  39890. // last normalization of each normal
  39891. for (index = 0; index < normals.length / 3; index++) {
  39892. faceNormalx = normals[index * 3];
  39893. faceNormaly = normals[index * 3 + 1];
  39894. faceNormalz = normals[index * 3 + 2];
  39895. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39896. length = (length === 0) ? 1.0 : length;
  39897. faceNormalx /= length;
  39898. faceNormaly /= length;
  39899. faceNormalz /= length;
  39900. normals[index * 3] = faceNormalx;
  39901. normals[index * 3 + 1] = faceNormaly;
  39902. normals[index * 3 + 2] = faceNormalz;
  39903. }
  39904. };
  39905. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39906. var li = indices.length;
  39907. var ln = normals.length;
  39908. var i;
  39909. var n;
  39910. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39911. switch (sideOrientation) {
  39912. case BABYLON.Mesh.FRONTSIDE:
  39913. // nothing changed
  39914. break;
  39915. case BABYLON.Mesh.BACKSIDE:
  39916. var tmp;
  39917. // indices
  39918. for (i = 0; i < li; i += 3) {
  39919. tmp = indices[i];
  39920. indices[i] = indices[i + 2];
  39921. indices[i + 2] = tmp;
  39922. }
  39923. // normals
  39924. for (n = 0; n < ln; n++) {
  39925. normals[n] = -normals[n];
  39926. }
  39927. break;
  39928. case BABYLON.Mesh.DOUBLESIDE:
  39929. // positions
  39930. var lp = positions.length;
  39931. var l = lp / 3;
  39932. for (var p = 0; p < lp; p++) {
  39933. positions[lp + p] = positions[p];
  39934. }
  39935. // indices
  39936. for (i = 0; i < li; i += 3) {
  39937. indices[i + li] = indices[i + 2] + l;
  39938. indices[i + 1 + li] = indices[i + 1] + l;
  39939. indices[i + 2 + li] = indices[i] + l;
  39940. }
  39941. // normals
  39942. for (n = 0; n < ln; n++) {
  39943. normals[ln + n] = -normals[n];
  39944. }
  39945. // uvs
  39946. var lu = uvs.length;
  39947. var u = 0;
  39948. for (u = 0; u < lu; u++) {
  39949. uvs[u + lu] = uvs[u];
  39950. }
  39951. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39952. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39953. u = 0;
  39954. for (i = 0; i < lu / 2; i++) {
  39955. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39956. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39957. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39958. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39959. u += 2;
  39960. }
  39961. break;
  39962. }
  39963. };
  39964. /**
  39965. * Applies VertexData created from the imported parameters to the geometry
  39966. * @param parsedVertexData the parsed data from an imported file
  39967. * @param geometry the geometry to apply the VertexData to
  39968. */
  39969. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39970. var vertexData = new VertexData();
  39971. // positions
  39972. var positions = parsedVertexData.positions;
  39973. if (positions) {
  39974. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39975. }
  39976. // normals
  39977. var normals = parsedVertexData.normals;
  39978. if (normals) {
  39979. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39980. }
  39981. // tangents
  39982. var tangents = parsedVertexData.tangents;
  39983. if (tangents) {
  39984. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39985. }
  39986. // uvs
  39987. var uvs = parsedVertexData.uvs;
  39988. if (uvs) {
  39989. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39990. }
  39991. // uv2s
  39992. var uv2s = parsedVertexData.uv2s;
  39993. if (uv2s) {
  39994. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39995. }
  39996. // uv3s
  39997. var uv3s = parsedVertexData.uv3s;
  39998. if (uv3s) {
  39999. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  40000. }
  40001. // uv4s
  40002. var uv4s = parsedVertexData.uv4s;
  40003. if (uv4s) {
  40004. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  40005. }
  40006. // uv5s
  40007. var uv5s = parsedVertexData.uv5s;
  40008. if (uv5s) {
  40009. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  40010. }
  40011. // uv6s
  40012. var uv6s = parsedVertexData.uv6s;
  40013. if (uv6s) {
  40014. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  40015. }
  40016. // colors
  40017. var colors = parsedVertexData.colors;
  40018. if (colors) {
  40019. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  40020. }
  40021. // matricesIndices
  40022. var matricesIndices = parsedVertexData.matricesIndices;
  40023. if (matricesIndices) {
  40024. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  40025. }
  40026. // matricesWeights
  40027. var matricesWeights = parsedVertexData.matricesWeights;
  40028. if (matricesWeights) {
  40029. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  40030. }
  40031. // indices
  40032. var indices = parsedVertexData.indices;
  40033. if (indices) {
  40034. vertexData.indices = indices;
  40035. }
  40036. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  40037. };
  40038. return VertexData;
  40039. }());
  40040. BABYLON.VertexData = VertexData;
  40041. })(BABYLON || (BABYLON = {}));
  40042. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  40043. var BABYLON;
  40044. (function (BABYLON) {
  40045. /**
  40046. * Class used to store geometry data (vertex buffers + index buffer)
  40047. */
  40048. var Geometry = /** @class */ (function () {
  40049. /**
  40050. * Creates a new geometry
  40051. * @param id defines the unique ID
  40052. * @param scene defines the hosting scene
  40053. * @param vertexData defines the VertexData used to get geometry data
  40054. * @param updatable defines if geometry must be updatable (false by default)
  40055. * @param mesh defines the mesh that will be associated with the geometry
  40056. */
  40057. function Geometry(id, scene, vertexData, updatable, mesh) {
  40058. if (updatable === void 0) { updatable = false; }
  40059. if (mesh === void 0) { mesh = null; }
  40060. /**
  40061. * Gets the delay loading state of the geometry (none by default which means not delayed)
  40062. */
  40063. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40064. this._totalVertices = 0;
  40065. this._isDisposed = false;
  40066. this._indexBufferIsUpdatable = false;
  40067. this.id = id;
  40068. this._engine = scene.getEngine();
  40069. this._meshes = [];
  40070. this._scene = scene;
  40071. //Init vertex buffer cache
  40072. this._vertexBuffers = {};
  40073. this._indices = [];
  40074. this._updatable = updatable;
  40075. // vertexData
  40076. if (vertexData) {
  40077. this.setAllVerticesData(vertexData, updatable);
  40078. }
  40079. else {
  40080. this._totalVertices = 0;
  40081. this._indices = [];
  40082. }
  40083. if (this._engine.getCaps().vertexArrayObject) {
  40084. this._vertexArrayObjects = {};
  40085. }
  40086. // applyToMesh
  40087. if (mesh) {
  40088. if (mesh.getClassName() === "LinesMesh") {
  40089. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  40090. this._updateExtend();
  40091. }
  40092. this.applyToMesh(mesh);
  40093. mesh.computeWorldMatrix(true);
  40094. }
  40095. }
  40096. Object.defineProperty(Geometry.prototype, "boundingBias", {
  40097. /**
  40098. * 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
  40099. */
  40100. get: function () {
  40101. return this._boundingBias;
  40102. },
  40103. /**
  40104. * 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
  40105. */
  40106. set: function (value) {
  40107. if (this._boundingBias) {
  40108. if (this._boundingBias.equals(value)) {
  40109. return;
  40110. }
  40111. this._boundingBias.copyFrom(value);
  40112. }
  40113. else {
  40114. this._boundingBias = value.clone();
  40115. }
  40116. this._updateBoundingInfo(true, null);
  40117. },
  40118. enumerable: true,
  40119. configurable: true
  40120. });
  40121. /**
  40122. * Static function used to attach a new empty geometry to a mesh
  40123. * @param mesh defines the mesh to attach the geometry to
  40124. * @returns the new Geometry
  40125. */
  40126. Geometry.CreateGeometryForMesh = function (mesh) {
  40127. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  40128. geometry.applyToMesh(mesh);
  40129. return geometry;
  40130. };
  40131. Object.defineProperty(Geometry.prototype, "extend", {
  40132. /**
  40133. * Gets the current extend of the geometry
  40134. */
  40135. get: function () {
  40136. return this._extend;
  40137. },
  40138. enumerable: true,
  40139. configurable: true
  40140. });
  40141. /**
  40142. * Gets the hosting scene
  40143. * @returns the hosting Scene
  40144. */
  40145. Geometry.prototype.getScene = function () {
  40146. return this._scene;
  40147. };
  40148. /**
  40149. * Gets the hosting engine
  40150. * @returns the hosting Engine
  40151. */
  40152. Geometry.prototype.getEngine = function () {
  40153. return this._engine;
  40154. };
  40155. /**
  40156. * Defines if the geometry is ready to use
  40157. * @returns true if the geometry is ready to be used
  40158. */
  40159. Geometry.prototype.isReady = function () {
  40160. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  40161. };
  40162. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  40163. /**
  40164. * Gets a value indicating that the geometry should not be serialized
  40165. */
  40166. get: function () {
  40167. for (var index = 0; index < this._meshes.length; index++) {
  40168. if (!this._meshes[index].doNotSerialize) {
  40169. return false;
  40170. }
  40171. }
  40172. return true;
  40173. },
  40174. enumerable: true,
  40175. configurable: true
  40176. });
  40177. /** @hidden */
  40178. Geometry.prototype._rebuild = function () {
  40179. if (this._vertexArrayObjects) {
  40180. this._vertexArrayObjects = {};
  40181. }
  40182. // Index buffer
  40183. if (this._meshes.length !== 0 && this._indices) {
  40184. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40185. }
  40186. // Vertex buffers
  40187. for (var key in this._vertexBuffers) {
  40188. var vertexBuffer = this._vertexBuffers[key];
  40189. vertexBuffer._rebuild();
  40190. }
  40191. };
  40192. /**
  40193. * Affects all geometry data in one call
  40194. * @param vertexData defines the geometry data
  40195. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  40196. */
  40197. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40198. vertexData.applyToGeometry(this, updatable);
  40199. this.notifyUpdate();
  40200. };
  40201. /**
  40202. * Set specific vertex data
  40203. * @param kind defines the data kind (Position, normal, etc...)
  40204. * @param data defines the vertex data to use
  40205. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  40206. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  40207. */
  40208. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  40209. if (updatable === void 0) { updatable = false; }
  40210. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  40211. this.setVerticesBuffer(buffer);
  40212. };
  40213. /**
  40214. * Removes a specific vertex data
  40215. * @param kind defines the data kind (Position, normal, etc...)
  40216. */
  40217. Geometry.prototype.removeVerticesData = function (kind) {
  40218. if (this._vertexBuffers[kind]) {
  40219. this._vertexBuffers[kind].dispose();
  40220. delete this._vertexBuffers[kind];
  40221. }
  40222. };
  40223. /**
  40224. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  40225. * @param buffer defines the vertex buffer to use
  40226. * @param totalVertices defines the total number of vertices for position kind (could be null)
  40227. */
  40228. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  40229. if (totalVertices === void 0) { totalVertices = null; }
  40230. var kind = buffer.getKind();
  40231. if (this._vertexBuffers[kind]) {
  40232. this._vertexBuffers[kind].dispose();
  40233. }
  40234. this._vertexBuffers[kind] = buffer;
  40235. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40236. var data = buffer.getData();
  40237. if (totalVertices != null) {
  40238. this._totalVertices = totalVertices;
  40239. }
  40240. else {
  40241. if (data != null) {
  40242. this._totalVertices = data.length / (buffer.byteStride / 4);
  40243. }
  40244. }
  40245. this._updateExtend(data);
  40246. this._resetPointsArrayCache();
  40247. var meshes = this._meshes;
  40248. var numOfMeshes = meshes.length;
  40249. for (var index = 0; index < numOfMeshes; index++) {
  40250. var mesh = meshes[index];
  40251. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40252. mesh._createGlobalSubMesh(false);
  40253. mesh.computeWorldMatrix(true);
  40254. }
  40255. }
  40256. this.notifyUpdate(kind);
  40257. if (this._vertexArrayObjects) {
  40258. this._disposeVertexArrayObjects();
  40259. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  40260. }
  40261. };
  40262. /**
  40263. * Update a specific vertex buffer
  40264. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  40265. * It will do nothing if the buffer is not updatable
  40266. * @param kind defines the data kind (Position, normal, etc...)
  40267. * @param data defines the data to use
  40268. * @param offset defines the offset in the target buffer where to store the data
  40269. * @param useBytes set to true if the offset is in bytes
  40270. */
  40271. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  40272. if (useBytes === void 0) { useBytes = false; }
  40273. var vertexBuffer = this.getVertexBuffer(kind);
  40274. if (!vertexBuffer) {
  40275. return;
  40276. }
  40277. vertexBuffer.updateDirectly(data, offset, useBytes);
  40278. this.notifyUpdate(kind);
  40279. };
  40280. /**
  40281. * Update a specific vertex buffer
  40282. * This function will create a new buffer if the current one is not updatable
  40283. * @param kind defines the data kind (Position, normal, etc...)
  40284. * @param data defines the data to use
  40285. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  40286. */
  40287. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  40288. if (updateExtends === void 0) { updateExtends = false; }
  40289. var vertexBuffer = this.getVertexBuffer(kind);
  40290. if (!vertexBuffer) {
  40291. return;
  40292. }
  40293. vertexBuffer.update(data);
  40294. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40295. this._updateBoundingInfo(updateExtends, data);
  40296. }
  40297. this.notifyUpdate(kind);
  40298. };
  40299. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  40300. if (updateExtends) {
  40301. this._updateExtend(data);
  40302. }
  40303. var meshes = this._meshes;
  40304. var numOfMeshes = meshes.length;
  40305. this._resetPointsArrayCache();
  40306. for (var index = 0; index < numOfMeshes; index++) {
  40307. var mesh = meshes[index];
  40308. if (updateExtends) {
  40309. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40310. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  40311. var subMesh = mesh.subMeshes[subIndex];
  40312. subMesh.refreshBoundingInfo();
  40313. }
  40314. }
  40315. }
  40316. };
  40317. /** @hidden */
  40318. Geometry.prototype._bind = function (effect, indexToBind) {
  40319. if (!effect) {
  40320. return;
  40321. }
  40322. if (indexToBind === undefined) {
  40323. indexToBind = this._indexBuffer;
  40324. }
  40325. var vbs = this.getVertexBuffers();
  40326. if (!vbs) {
  40327. return;
  40328. }
  40329. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  40330. this._engine.bindBuffers(vbs, indexToBind, effect);
  40331. return;
  40332. }
  40333. // Using VAO
  40334. if (!this._vertexArrayObjects[effect.key]) {
  40335. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  40336. }
  40337. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  40338. };
  40339. /**
  40340. * Gets total number of vertices
  40341. * @returns the total number of vertices
  40342. */
  40343. Geometry.prototype.getTotalVertices = function () {
  40344. if (!this.isReady()) {
  40345. return 0;
  40346. }
  40347. return this._totalVertices;
  40348. };
  40349. /**
  40350. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  40351. * @param kind defines the data kind (Position, normal, etc...)
  40352. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40353. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40354. * @returns a float array containing vertex data
  40355. */
  40356. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  40357. var vertexBuffer = this.getVertexBuffer(kind);
  40358. if (!vertexBuffer) {
  40359. return null;
  40360. }
  40361. var data = vertexBuffer.getData();
  40362. if (!data) {
  40363. return null;
  40364. }
  40365. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  40366. var count = this._totalVertices * vertexBuffer.getSize();
  40367. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  40368. var copy_1 = new Array(count);
  40369. vertexBuffer.forEach(count, function (value, index) {
  40370. copy_1[index] = value;
  40371. });
  40372. return copy_1;
  40373. }
  40374. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  40375. if (data instanceof Array) {
  40376. var offset = vertexBuffer.byteOffset / 4;
  40377. return BABYLON.Tools.Slice(data, offset, offset + count);
  40378. }
  40379. else if (data instanceof ArrayBuffer) {
  40380. return new Float32Array(data, vertexBuffer.byteOffset, count);
  40381. }
  40382. else {
  40383. var offset = data.byteOffset + vertexBuffer.byteOffset;
  40384. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40385. var result = new Float32Array(count);
  40386. var source = new Float32Array(data.buffer, offset, count);
  40387. result.set(source);
  40388. return result;
  40389. }
  40390. return new Float32Array(data.buffer, offset, count);
  40391. }
  40392. }
  40393. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  40394. return BABYLON.Tools.Slice(data);
  40395. }
  40396. return data;
  40397. };
  40398. /**
  40399. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  40400. * @param kind defines the data kind (Position, normal, etc...)
  40401. * @returns true if the vertex buffer with the specified kind is updatable
  40402. */
  40403. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  40404. var vb = this._vertexBuffers[kind];
  40405. if (!vb) {
  40406. return false;
  40407. }
  40408. return vb.isUpdatable();
  40409. };
  40410. /**
  40411. * Gets a specific vertex buffer
  40412. * @param kind defines the data kind (Position, normal, etc...)
  40413. * @returns a VertexBuffer
  40414. */
  40415. Geometry.prototype.getVertexBuffer = function (kind) {
  40416. if (!this.isReady()) {
  40417. return null;
  40418. }
  40419. return this._vertexBuffers[kind];
  40420. };
  40421. /**
  40422. * Returns all vertex buffers
  40423. * @return an object holding all vertex buffers indexed by kind
  40424. */
  40425. Geometry.prototype.getVertexBuffers = function () {
  40426. if (!this.isReady()) {
  40427. return null;
  40428. }
  40429. return this._vertexBuffers;
  40430. };
  40431. /**
  40432. * Gets a boolean indicating if specific vertex buffer is present
  40433. * @param kind defines the data kind (Position, normal, etc...)
  40434. * @returns true if data is present
  40435. */
  40436. Geometry.prototype.isVerticesDataPresent = function (kind) {
  40437. if (!this._vertexBuffers) {
  40438. if (this._delayInfo) {
  40439. return this._delayInfo.indexOf(kind) !== -1;
  40440. }
  40441. return false;
  40442. }
  40443. return this._vertexBuffers[kind] !== undefined;
  40444. };
  40445. /**
  40446. * Gets a list of all attached data kinds (Position, normal, etc...)
  40447. * @returns a list of string containing all kinds
  40448. */
  40449. Geometry.prototype.getVerticesDataKinds = function () {
  40450. var result = [];
  40451. var kind;
  40452. if (!this._vertexBuffers && this._delayInfo) {
  40453. for (kind in this._delayInfo) {
  40454. result.push(kind);
  40455. }
  40456. }
  40457. else {
  40458. for (kind in this._vertexBuffers) {
  40459. result.push(kind);
  40460. }
  40461. }
  40462. return result;
  40463. };
  40464. /**
  40465. * Update index buffer
  40466. * @param indices defines the indices to store in the index buffer
  40467. * @param offset defines the offset in the target buffer where to store the data
  40468. */
  40469. Geometry.prototype.updateIndices = function (indices, offset) {
  40470. if (!this._indexBuffer) {
  40471. return;
  40472. }
  40473. if (!this._indexBufferIsUpdatable) {
  40474. this.setIndices(indices, null, true);
  40475. }
  40476. else {
  40477. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  40478. }
  40479. };
  40480. /**
  40481. * Creates a new index buffer
  40482. * @param indices defines the indices to store in the index buffer
  40483. * @param totalVertices defines the total number of vertices (could be null)
  40484. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  40485. */
  40486. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  40487. if (totalVertices === void 0) { totalVertices = null; }
  40488. if (updatable === void 0) { updatable = false; }
  40489. if (this._indexBuffer) {
  40490. this._engine._releaseBuffer(this._indexBuffer);
  40491. }
  40492. this._disposeVertexArrayObjects();
  40493. this._indices = indices;
  40494. this._indexBufferIsUpdatable = updatable;
  40495. if (this._meshes.length !== 0 && this._indices) {
  40496. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  40497. }
  40498. if (totalVertices != undefined) { // including null and undefined
  40499. this._totalVertices = totalVertices;
  40500. }
  40501. var meshes = this._meshes;
  40502. var numOfMeshes = meshes.length;
  40503. for (var index = 0; index < numOfMeshes; index++) {
  40504. meshes[index]._createGlobalSubMesh(true);
  40505. }
  40506. this.notifyUpdate();
  40507. };
  40508. /**
  40509. * Return the total number of indices
  40510. * @returns the total number of indices
  40511. */
  40512. Geometry.prototype.getTotalIndices = function () {
  40513. if (!this.isReady()) {
  40514. return 0;
  40515. }
  40516. return this._indices.length;
  40517. };
  40518. /**
  40519. * Gets the index buffer array
  40520. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  40521. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  40522. * @returns the index buffer array
  40523. */
  40524. Geometry.prototype.getIndices = function (copyWhenShared, forceCopy) {
  40525. if (!this.isReady()) {
  40526. return null;
  40527. }
  40528. var orig = this._indices;
  40529. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  40530. return orig;
  40531. }
  40532. else {
  40533. var len = orig.length;
  40534. var copy = [];
  40535. for (var i = 0; i < len; i++) {
  40536. copy.push(orig[i]);
  40537. }
  40538. return copy;
  40539. }
  40540. };
  40541. /**
  40542. * Gets the index buffer
  40543. * @return the index buffer
  40544. */
  40545. Geometry.prototype.getIndexBuffer = function () {
  40546. if (!this.isReady()) {
  40547. return null;
  40548. }
  40549. return this._indexBuffer;
  40550. };
  40551. /** @hidden */
  40552. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  40553. if (effect === void 0) { effect = null; }
  40554. if (!effect || !this._vertexArrayObjects) {
  40555. return;
  40556. }
  40557. if (this._vertexArrayObjects[effect.key]) {
  40558. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  40559. delete this._vertexArrayObjects[effect.key];
  40560. }
  40561. };
  40562. /**
  40563. * Release the associated resources for a specific mesh
  40564. * @param mesh defines the source mesh
  40565. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  40566. */
  40567. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  40568. var meshes = this._meshes;
  40569. var index = meshes.indexOf(mesh);
  40570. if (index === -1) {
  40571. return;
  40572. }
  40573. meshes.splice(index, 1);
  40574. mesh._geometry = null;
  40575. if (meshes.length === 0 && shouldDispose) {
  40576. this.dispose();
  40577. }
  40578. };
  40579. /**
  40580. * Apply current geometry to a given mesh
  40581. * @param mesh defines the mesh to apply geometry to
  40582. */
  40583. Geometry.prototype.applyToMesh = function (mesh) {
  40584. if (mesh._geometry === this) {
  40585. return;
  40586. }
  40587. var previousGeometry = mesh._geometry;
  40588. if (previousGeometry) {
  40589. previousGeometry.releaseForMesh(mesh);
  40590. }
  40591. var meshes = this._meshes;
  40592. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  40593. mesh._geometry = this;
  40594. this._scene.pushGeometry(this);
  40595. meshes.push(mesh);
  40596. if (this.isReady()) {
  40597. this._applyToMesh(mesh);
  40598. }
  40599. else {
  40600. mesh._boundingInfo = this._boundingInfo;
  40601. }
  40602. };
  40603. Geometry.prototype._updateExtend = function (data) {
  40604. if (data === void 0) { data = null; }
  40605. if (!data) {
  40606. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40607. }
  40608. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  40609. };
  40610. Geometry.prototype._applyToMesh = function (mesh) {
  40611. var numOfMeshes = this._meshes.length;
  40612. // vertexBuffers
  40613. for (var kind in this._vertexBuffers) {
  40614. if (numOfMeshes === 1) {
  40615. this._vertexBuffers[kind].create();
  40616. }
  40617. var buffer = this._vertexBuffers[kind].getBuffer();
  40618. if (buffer)
  40619. buffer.references = numOfMeshes;
  40620. if (kind === BABYLON.VertexBuffer.PositionKind) {
  40621. if (!this._extend) {
  40622. this._updateExtend();
  40623. }
  40624. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40625. mesh._createGlobalSubMesh(false);
  40626. //bounding info was just created again, world matrix should be applied again.
  40627. mesh._updateBoundingInfo();
  40628. }
  40629. }
  40630. // indexBuffer
  40631. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  40632. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  40633. }
  40634. if (this._indexBuffer) {
  40635. this._indexBuffer.references = numOfMeshes;
  40636. }
  40637. };
  40638. Geometry.prototype.notifyUpdate = function (kind) {
  40639. if (this.onGeometryUpdated) {
  40640. this.onGeometryUpdated(this, kind);
  40641. }
  40642. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  40643. var mesh = _a[_i];
  40644. mesh._markSubMeshesAsAttributesDirty();
  40645. }
  40646. };
  40647. /**
  40648. * Load the geometry if it was flagged as delay loaded
  40649. * @param scene defines the hosting scene
  40650. * @param onLoaded defines a callback called when the geometry is loaded
  40651. */
  40652. Geometry.prototype.load = function (scene, onLoaded) {
  40653. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  40654. return;
  40655. }
  40656. if (this.isReady()) {
  40657. if (onLoaded) {
  40658. onLoaded();
  40659. }
  40660. return;
  40661. }
  40662. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  40663. this._queueLoad(scene, onLoaded);
  40664. };
  40665. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  40666. var _this = this;
  40667. if (!this.delayLoadingFile) {
  40668. return;
  40669. }
  40670. scene._addPendingData(this);
  40671. scene._loadFile(this.delayLoadingFile, function (data) {
  40672. if (!_this._delayLoadingFunction) {
  40673. return;
  40674. }
  40675. _this._delayLoadingFunction(JSON.parse(data), _this);
  40676. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  40677. _this._delayInfo = [];
  40678. scene._removePendingData(_this);
  40679. var meshes = _this._meshes;
  40680. var numOfMeshes = meshes.length;
  40681. for (var index = 0; index < numOfMeshes; index++) {
  40682. _this._applyToMesh(meshes[index]);
  40683. }
  40684. if (onLoaded) {
  40685. onLoaded();
  40686. }
  40687. }, undefined, true);
  40688. };
  40689. /**
  40690. * Invert the geometry to move from a right handed system to a left handed one.
  40691. */
  40692. Geometry.prototype.toLeftHanded = function () {
  40693. // Flip faces
  40694. var tIndices = this.getIndices(false);
  40695. if (tIndices != null && tIndices.length > 0) {
  40696. for (var i = 0; i < tIndices.length; i += 3) {
  40697. var tTemp = tIndices[i + 0];
  40698. tIndices[i + 0] = tIndices[i + 2];
  40699. tIndices[i + 2] = tTemp;
  40700. }
  40701. this.setIndices(tIndices);
  40702. }
  40703. // Negate position.z
  40704. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  40705. if (tPositions != null && tPositions.length > 0) {
  40706. for (var i = 0; i < tPositions.length; i += 3) {
  40707. tPositions[i + 2] = -tPositions[i + 2];
  40708. }
  40709. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  40710. }
  40711. // Negate normal.z
  40712. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  40713. if (tNormals != null && tNormals.length > 0) {
  40714. for (var i = 0; i < tNormals.length; i += 3) {
  40715. tNormals[i + 2] = -tNormals[i + 2];
  40716. }
  40717. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  40718. }
  40719. };
  40720. // Cache
  40721. /** @hidden */
  40722. Geometry.prototype._resetPointsArrayCache = function () {
  40723. this._positions = null;
  40724. };
  40725. /** @hidden */
  40726. Geometry.prototype._generatePointsArray = function () {
  40727. if (this._positions)
  40728. return true;
  40729. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40730. if (!data || data.length === 0) {
  40731. return false;
  40732. }
  40733. this._positions = [];
  40734. for (var index = 0; index < data.length; index += 3) {
  40735. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  40736. }
  40737. return true;
  40738. };
  40739. /**
  40740. * Gets a value indicating if the geometry is disposed
  40741. * @returns true if the geometry was disposed
  40742. */
  40743. Geometry.prototype.isDisposed = function () {
  40744. return this._isDisposed;
  40745. };
  40746. Geometry.prototype._disposeVertexArrayObjects = function () {
  40747. if (this._vertexArrayObjects) {
  40748. for (var kind in this._vertexArrayObjects) {
  40749. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  40750. }
  40751. this._vertexArrayObjects = {};
  40752. }
  40753. };
  40754. /**
  40755. * Free all associated resources
  40756. */
  40757. Geometry.prototype.dispose = function () {
  40758. var meshes = this._meshes;
  40759. var numOfMeshes = meshes.length;
  40760. var index;
  40761. for (index = 0; index < numOfMeshes; index++) {
  40762. this.releaseForMesh(meshes[index]);
  40763. }
  40764. this._meshes = [];
  40765. this._disposeVertexArrayObjects();
  40766. for (var kind in this._vertexBuffers) {
  40767. this._vertexBuffers[kind].dispose();
  40768. }
  40769. this._vertexBuffers = {};
  40770. this._totalVertices = 0;
  40771. if (this._indexBuffer) {
  40772. this._engine._releaseBuffer(this._indexBuffer);
  40773. }
  40774. this._indexBuffer = null;
  40775. this._indices = [];
  40776. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  40777. this.delayLoadingFile = null;
  40778. this._delayLoadingFunction = null;
  40779. this._delayInfo = [];
  40780. this._boundingInfo = null;
  40781. this._scene.removeGeometry(this);
  40782. this._isDisposed = true;
  40783. };
  40784. /**
  40785. * Clone the current geometry into a new geometry
  40786. * @param id defines the unique ID of the new geometry
  40787. * @returns a new geometry object
  40788. */
  40789. Geometry.prototype.copy = function (id) {
  40790. var vertexData = new BABYLON.VertexData();
  40791. vertexData.indices = [];
  40792. var indices = this.getIndices();
  40793. if (indices) {
  40794. for (var index = 0; index < indices.length; index++) {
  40795. vertexData.indices.push(indices[index]);
  40796. }
  40797. }
  40798. var updatable = false;
  40799. var stopChecking = false;
  40800. var kind;
  40801. for (kind in this._vertexBuffers) {
  40802. // using slice() to make a copy of the array and not just reference it
  40803. var data = this.getVerticesData(kind);
  40804. if (data instanceof Float32Array) {
  40805. vertexData.set(new Float32Array(data), kind);
  40806. }
  40807. else {
  40808. vertexData.set(data.slice(0), kind);
  40809. }
  40810. if (!stopChecking) {
  40811. var vb = this.getVertexBuffer(kind);
  40812. if (vb) {
  40813. updatable = vb.isUpdatable();
  40814. stopChecking = !updatable;
  40815. }
  40816. }
  40817. }
  40818. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  40819. geometry.delayLoadState = this.delayLoadState;
  40820. geometry.delayLoadingFile = this.delayLoadingFile;
  40821. geometry._delayLoadingFunction = this._delayLoadingFunction;
  40822. for (kind in this._delayInfo) {
  40823. geometry._delayInfo = geometry._delayInfo || [];
  40824. geometry._delayInfo.push(kind);
  40825. }
  40826. // Bounding info
  40827. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  40828. return geometry;
  40829. };
  40830. /**
  40831. * Serialize the current geometry info (and not the vertices data) into a JSON object
  40832. * @return a JSON representation of the current geometry data (without the vertices data)
  40833. */
  40834. Geometry.prototype.serialize = function () {
  40835. var serializationObject = {};
  40836. serializationObject.id = this.id;
  40837. serializationObject.updatable = this._updatable;
  40838. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40839. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40840. }
  40841. return serializationObject;
  40842. };
  40843. Geometry.prototype.toNumberArray = function (origin) {
  40844. if (Array.isArray(origin)) {
  40845. return origin;
  40846. }
  40847. else {
  40848. return Array.prototype.slice.call(origin);
  40849. }
  40850. };
  40851. /**
  40852. * Serialize all vertices data into a JSON oject
  40853. * @returns a JSON representation of the current geometry data
  40854. */
  40855. Geometry.prototype.serializeVerticeData = function () {
  40856. var serializationObject = this.serialize();
  40857. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40858. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40859. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40860. serializationObject.positions._updatable = true;
  40861. }
  40862. }
  40863. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40864. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40865. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40866. serializationObject.normals._updatable = true;
  40867. }
  40868. }
  40869. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40870. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40871. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40872. serializationObject.tangets._updatable = true;
  40873. }
  40874. }
  40875. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40876. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40877. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40878. serializationObject.uvs._updatable = true;
  40879. }
  40880. }
  40881. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40882. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40883. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40884. serializationObject.uv2s._updatable = true;
  40885. }
  40886. }
  40887. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40888. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40889. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40890. serializationObject.uv3s._updatable = true;
  40891. }
  40892. }
  40893. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40894. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40895. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40896. serializationObject.uv4s._updatable = true;
  40897. }
  40898. }
  40899. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40900. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40901. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40902. serializationObject.uv5s._updatable = true;
  40903. }
  40904. }
  40905. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40906. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40907. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40908. serializationObject.uv6s._updatable = true;
  40909. }
  40910. }
  40911. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40912. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40913. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40914. serializationObject.colors._updatable = true;
  40915. }
  40916. }
  40917. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40918. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40919. serializationObject.matricesIndices._isExpanded = true;
  40920. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40921. serializationObject.matricesIndices._updatable = true;
  40922. }
  40923. }
  40924. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40925. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40926. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40927. serializationObject.matricesWeights._updatable = true;
  40928. }
  40929. }
  40930. serializationObject.indices = this.toNumberArray(this.getIndices());
  40931. return serializationObject;
  40932. };
  40933. // Statics
  40934. /**
  40935. * Extracts a clone of a mesh geometry
  40936. * @param mesh defines the source mesh
  40937. * @param id defines the unique ID of the new geometry object
  40938. * @returns the new geometry object
  40939. */
  40940. Geometry.ExtractFromMesh = function (mesh, id) {
  40941. var geometry = mesh._geometry;
  40942. if (!geometry) {
  40943. return null;
  40944. }
  40945. return geometry.copy(id);
  40946. };
  40947. /**
  40948. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40949. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40950. * Be aware Math.random() could cause collisions, but:
  40951. * "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"
  40952. * @returns a string containing a new GUID
  40953. */
  40954. Geometry.RandomId = function () {
  40955. return BABYLON.Tools.RandomId();
  40956. };
  40957. /** @hidden */
  40958. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40959. var scene = mesh.getScene();
  40960. // Geometry
  40961. var geometryId = parsedGeometry.geometryId;
  40962. if (geometryId) {
  40963. var geometry = scene.getGeometryByID(geometryId);
  40964. if (geometry) {
  40965. geometry.applyToMesh(mesh);
  40966. }
  40967. }
  40968. else if (parsedGeometry instanceof ArrayBuffer) {
  40969. var binaryInfo = mesh._binaryInfo;
  40970. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40971. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40972. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40973. }
  40974. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40975. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40976. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40977. }
  40978. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40979. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40980. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40981. }
  40982. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40983. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40984. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40985. }
  40986. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40987. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40988. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40989. }
  40990. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40991. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40992. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40993. }
  40994. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40995. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40996. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40997. }
  40998. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40999. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  41000. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  41001. }
  41002. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  41003. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  41004. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  41005. }
  41006. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  41007. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  41008. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  41009. }
  41010. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  41011. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  41012. var floatIndices = [];
  41013. for (var i = 0; i < matricesIndicesData.length; i++) {
  41014. var index = matricesIndicesData[i];
  41015. floatIndices.push(index & 0x000000FF);
  41016. floatIndices.push((index & 0x0000FF00) >> 8);
  41017. floatIndices.push((index & 0x00FF0000) >> 16);
  41018. floatIndices.push(index >> 24);
  41019. }
  41020. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  41021. }
  41022. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  41023. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  41024. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  41025. }
  41026. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  41027. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  41028. mesh.setIndices(indicesData, null);
  41029. }
  41030. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  41031. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  41032. mesh.subMeshes = [];
  41033. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  41034. var materialIndex = subMeshesData[(i * 5) + 0];
  41035. var verticesStart = subMeshesData[(i * 5) + 1];
  41036. var verticesCount = subMeshesData[(i * 5) + 2];
  41037. var indexStart = subMeshesData[(i * 5) + 3];
  41038. var indexCount = subMeshesData[(i * 5) + 4];
  41039. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  41040. }
  41041. }
  41042. }
  41043. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  41044. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  41045. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  41046. if (parsedGeometry.tangents) {
  41047. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  41048. }
  41049. if (parsedGeometry.uvs) {
  41050. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  41051. }
  41052. if (parsedGeometry.uvs2) {
  41053. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  41054. }
  41055. if (parsedGeometry.uvs3) {
  41056. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  41057. }
  41058. if (parsedGeometry.uvs4) {
  41059. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  41060. }
  41061. if (parsedGeometry.uvs5) {
  41062. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  41063. }
  41064. if (parsedGeometry.uvs6) {
  41065. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  41066. }
  41067. if (parsedGeometry.colors) {
  41068. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  41069. }
  41070. if (parsedGeometry.matricesIndices) {
  41071. if (!parsedGeometry.matricesIndices._isExpanded) {
  41072. var floatIndices = [];
  41073. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  41074. var matricesIndex = parsedGeometry.matricesIndices[i];
  41075. floatIndices.push(matricesIndex & 0x000000FF);
  41076. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41077. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41078. floatIndices.push(matricesIndex >> 24);
  41079. }
  41080. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  41081. }
  41082. else {
  41083. delete parsedGeometry.matricesIndices._isExpanded;
  41084. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  41085. }
  41086. }
  41087. if (parsedGeometry.matricesIndicesExtra) {
  41088. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  41089. var floatIndices = [];
  41090. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  41091. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  41092. floatIndices.push(matricesIndex & 0x000000FF);
  41093. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  41094. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  41095. floatIndices.push(matricesIndex >> 24);
  41096. }
  41097. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  41098. }
  41099. else {
  41100. delete parsedGeometry.matricesIndices._isExpanded;
  41101. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  41102. }
  41103. }
  41104. if (parsedGeometry.matricesWeights) {
  41105. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  41106. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  41107. }
  41108. if (parsedGeometry.matricesWeightsExtra) {
  41109. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  41110. }
  41111. mesh.setIndices(parsedGeometry.indices, null);
  41112. }
  41113. // SubMeshes
  41114. if (parsedGeometry.subMeshes) {
  41115. mesh.subMeshes = [];
  41116. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  41117. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  41118. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  41119. }
  41120. }
  41121. // Flat shading
  41122. if (mesh._shouldGenerateFlatShading) {
  41123. mesh.convertToFlatShadedMesh();
  41124. delete mesh._shouldGenerateFlatShading;
  41125. }
  41126. // Update
  41127. mesh.computeWorldMatrix(true);
  41128. scene.onMeshImportedObservable.notifyObservers(mesh);
  41129. };
  41130. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  41131. var epsilon = 1e-3;
  41132. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  41133. return;
  41134. }
  41135. var noInfluenceBoneIndex = 0.0;
  41136. if (parsedGeometry.skeletonId > -1) {
  41137. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  41138. if (!skeleton) {
  41139. return;
  41140. }
  41141. noInfluenceBoneIndex = skeleton.bones.length;
  41142. }
  41143. else {
  41144. return;
  41145. }
  41146. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  41147. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41148. var matricesWeights = parsedGeometry.matricesWeights;
  41149. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  41150. var influencers = parsedGeometry.numBoneInfluencer;
  41151. var size = matricesWeights.length;
  41152. for (var i = 0; i < size; i += 4) {
  41153. var weight = 0.0;
  41154. var firstZeroWeight = -1;
  41155. for (var j = 0; j < 4; j++) {
  41156. var w = matricesWeights[i + j];
  41157. weight += w;
  41158. if (w < epsilon && firstZeroWeight < 0) {
  41159. firstZeroWeight = j;
  41160. }
  41161. }
  41162. if (matricesWeightsExtra) {
  41163. for (var j = 0; j < 4; j++) {
  41164. var w = matricesWeightsExtra[i + j];
  41165. weight += w;
  41166. if (w < epsilon && firstZeroWeight < 0) {
  41167. firstZeroWeight = j + 4;
  41168. }
  41169. }
  41170. }
  41171. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  41172. firstZeroWeight = influencers - 1;
  41173. }
  41174. if (weight > epsilon) {
  41175. var mweight = 1.0 / weight;
  41176. for (var j = 0; j < 4; j++) {
  41177. matricesWeights[i + j] *= mweight;
  41178. }
  41179. if (matricesWeightsExtra) {
  41180. for (var j = 0; j < 4; j++) {
  41181. matricesWeightsExtra[i + j] *= mweight;
  41182. }
  41183. }
  41184. }
  41185. else {
  41186. if (firstZeroWeight >= 4) {
  41187. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  41188. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  41189. }
  41190. else {
  41191. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  41192. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  41193. }
  41194. }
  41195. }
  41196. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  41197. if (parsedGeometry.matricesWeightsExtra) {
  41198. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  41199. }
  41200. };
  41201. /**
  41202. * Create a new geometry from persisted data (Using .babylon file format)
  41203. * @param parsedVertexData defines the persisted data
  41204. * @param scene defines the hosting scene
  41205. * @param rootUrl defines the root url to use to load assets (like delayed data)
  41206. * @returns the new geometry object
  41207. */
  41208. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  41209. if (scene.getGeometryByID(parsedVertexData.id)) {
  41210. return null; // null since geometry could be something else than a box...
  41211. }
  41212. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  41213. if (BABYLON.Tags) {
  41214. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  41215. }
  41216. if (parsedVertexData.delayLoadingFile) {
  41217. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41218. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  41219. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  41220. geometry._delayInfo = [];
  41221. if (parsedVertexData.hasUVs) {
  41222. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  41223. }
  41224. if (parsedVertexData.hasUVs2) {
  41225. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  41226. }
  41227. if (parsedVertexData.hasUVs3) {
  41228. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  41229. }
  41230. if (parsedVertexData.hasUVs4) {
  41231. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  41232. }
  41233. if (parsedVertexData.hasUVs5) {
  41234. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  41235. }
  41236. if (parsedVertexData.hasUVs6) {
  41237. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  41238. }
  41239. if (parsedVertexData.hasColors) {
  41240. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  41241. }
  41242. if (parsedVertexData.hasMatricesIndices) {
  41243. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41244. }
  41245. if (parsedVertexData.hasMatricesWeights) {
  41246. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41247. }
  41248. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  41249. }
  41250. else {
  41251. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  41252. }
  41253. scene.pushGeometry(geometry, true);
  41254. return geometry;
  41255. };
  41256. return Geometry;
  41257. }());
  41258. BABYLON.Geometry = Geometry;
  41259. // Primitives
  41260. /// Abstract class
  41261. /**
  41262. * Abstract class used to provide common services for all typed geometries
  41263. * @hidden
  41264. */
  41265. var _PrimitiveGeometry = /** @class */ (function (_super) {
  41266. __extends(_PrimitiveGeometry, _super);
  41267. /**
  41268. * Creates a new typed geometry
  41269. * @param id defines the unique ID of the geometry
  41270. * @param scene defines the hosting scene
  41271. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41272. * @param mesh defines the hosting mesh (can be null)
  41273. */
  41274. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  41275. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  41276. if (mesh === void 0) { mesh = null; }
  41277. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  41278. _this._canBeRegenerated = _canBeRegenerated;
  41279. _this._beingRegenerated = true;
  41280. _this.regenerate();
  41281. _this._beingRegenerated = false;
  41282. return _this;
  41283. }
  41284. /**
  41285. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  41286. * @returns true if the geometry can be regenerated
  41287. */
  41288. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  41289. return this._canBeRegenerated;
  41290. };
  41291. /**
  41292. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  41293. */
  41294. _PrimitiveGeometry.prototype.regenerate = function () {
  41295. if (!this._canBeRegenerated) {
  41296. return;
  41297. }
  41298. this._beingRegenerated = true;
  41299. this.setAllVerticesData(this._regenerateVertexData(), false);
  41300. this._beingRegenerated = false;
  41301. };
  41302. /**
  41303. * Clone the geometry
  41304. * @param id defines the unique ID of the new geometry
  41305. * @returns the new geometry
  41306. */
  41307. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  41308. return _super.prototype.copy.call(this, id);
  41309. };
  41310. // overrides
  41311. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  41312. if (!this._beingRegenerated) {
  41313. return;
  41314. }
  41315. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  41316. };
  41317. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  41318. if (!this._beingRegenerated) {
  41319. return;
  41320. }
  41321. _super.prototype.setVerticesData.call(this, kind, data, false);
  41322. };
  41323. // to override
  41324. /** @hidden */
  41325. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  41326. throw new Error("Abstract method");
  41327. };
  41328. _PrimitiveGeometry.prototype.copy = function (id) {
  41329. throw new Error("Must be overriden in sub-classes.");
  41330. };
  41331. _PrimitiveGeometry.prototype.serialize = function () {
  41332. var serializationObject = _super.prototype.serialize.call(this);
  41333. serializationObject.canBeRegenerated = this.canBeRegenerated();
  41334. return serializationObject;
  41335. };
  41336. return _PrimitiveGeometry;
  41337. }(Geometry));
  41338. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  41339. /**
  41340. * Creates a ribbon geometry
  41341. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  41342. */
  41343. var RibbonGeometry = /** @class */ (function (_super) {
  41344. __extends(RibbonGeometry, _super);
  41345. /**
  41346. * Creates a ribbon geometry
  41347. * @param id defines the unique ID of the geometry
  41348. * @param scene defines the hosting scene
  41349. * @param pathArray defines the array of paths to use
  41350. * @param closeArray defines if the last path and the first path must be joined
  41351. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  41352. * @param offset defines the offset between points
  41353. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41354. * @param mesh defines the hosting mesh (can be null)
  41355. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41356. */
  41357. function RibbonGeometry(id, scene,
  41358. /**
  41359. * Defines the array of paths to use
  41360. */
  41361. pathArray,
  41362. /**
  41363. * Defines if the last and first points of each path in your pathArray must be joined
  41364. */
  41365. closeArray,
  41366. /**
  41367. * Defines if the last and first points of each path in your pathArray must be joined
  41368. */
  41369. closePath,
  41370. /**
  41371. * Defines the offset between points
  41372. */
  41373. offset, canBeRegenerated, mesh,
  41374. /**
  41375. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41376. */
  41377. side) {
  41378. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41379. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41380. _this.pathArray = pathArray;
  41381. _this.closeArray = closeArray;
  41382. _this.closePath = closePath;
  41383. _this.offset = offset;
  41384. _this.side = side;
  41385. return _this;
  41386. }
  41387. /** @hidden */
  41388. RibbonGeometry.prototype._regenerateVertexData = function () {
  41389. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  41390. };
  41391. RibbonGeometry.prototype.copy = function (id) {
  41392. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  41393. };
  41394. return RibbonGeometry;
  41395. }(_PrimitiveGeometry));
  41396. BABYLON.RibbonGeometry = RibbonGeometry;
  41397. /**
  41398. * Creates a box geometry
  41399. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  41400. */
  41401. var BoxGeometry = /** @class */ (function (_super) {
  41402. __extends(BoxGeometry, _super);
  41403. /**
  41404. * Creates a box geometry
  41405. * @param id defines the unique ID of the geometry
  41406. * @param scene defines the hosting scene
  41407. * @param size defines the zise of the box (width, height and depth are the same)
  41408. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41409. * @param mesh defines the hosting mesh (can be null)
  41410. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41411. */
  41412. function BoxGeometry(id, scene,
  41413. /**
  41414. * Defines the zise of the box (width, height and depth are the same)
  41415. */
  41416. size, canBeRegenerated, mesh,
  41417. /**
  41418. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41419. */
  41420. side) {
  41421. if (mesh === void 0) { mesh = null; }
  41422. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41423. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41424. _this.size = size;
  41425. _this.side = side;
  41426. return _this;
  41427. }
  41428. /** @hidden */
  41429. BoxGeometry.prototype._regenerateVertexData = function () {
  41430. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  41431. };
  41432. BoxGeometry.prototype.copy = function (id) {
  41433. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  41434. };
  41435. BoxGeometry.prototype.serialize = function () {
  41436. var serializationObject = _super.prototype.serialize.call(this);
  41437. serializationObject.size = this.size;
  41438. return serializationObject;
  41439. };
  41440. BoxGeometry.Parse = function (parsedBox, scene) {
  41441. if (scene.getGeometryByID(parsedBox.id)) {
  41442. return null; // null since geometry could be something else than a box...
  41443. }
  41444. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  41445. if (BABYLON.Tags) {
  41446. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  41447. }
  41448. scene.pushGeometry(box, true);
  41449. return box;
  41450. };
  41451. return BoxGeometry;
  41452. }(_PrimitiveGeometry));
  41453. BABYLON.BoxGeometry = BoxGeometry;
  41454. /**
  41455. * Creates a sphere geometry
  41456. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  41457. */
  41458. var SphereGeometry = /** @class */ (function (_super) {
  41459. __extends(SphereGeometry, _super);
  41460. /**
  41461. * Create a new sphere geometry
  41462. * @param id defines the unique ID of the geometry
  41463. * @param scene defines the hosting scene
  41464. * @param segments defines the number of segments to use to create the sphere
  41465. * @param diameter defines the diameter of the sphere
  41466. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41467. * @param mesh defines the hosting mesh (can be null)
  41468. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41469. */
  41470. function SphereGeometry(id, scene,
  41471. /**
  41472. * Defines the number of segments to use to create the sphere
  41473. */
  41474. segments,
  41475. /**
  41476. * Defines the diameter of the sphere
  41477. */
  41478. diameter, canBeRegenerated, mesh,
  41479. /**
  41480. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41481. */
  41482. side) {
  41483. if (mesh === void 0) { mesh = null; }
  41484. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41485. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41486. _this.segments = segments;
  41487. _this.diameter = diameter;
  41488. _this.side = side;
  41489. return _this;
  41490. }
  41491. /** @hidden */
  41492. SphereGeometry.prototype._regenerateVertexData = function () {
  41493. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  41494. };
  41495. SphereGeometry.prototype.copy = function (id) {
  41496. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  41497. };
  41498. SphereGeometry.prototype.serialize = function () {
  41499. var serializationObject = _super.prototype.serialize.call(this);
  41500. serializationObject.segments = this.segments;
  41501. serializationObject.diameter = this.diameter;
  41502. return serializationObject;
  41503. };
  41504. SphereGeometry.Parse = function (parsedSphere, scene) {
  41505. if (scene.getGeometryByID(parsedSphere.id)) {
  41506. return null; // null since geometry could be something else than a sphere...
  41507. }
  41508. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  41509. if (BABYLON.Tags) {
  41510. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  41511. }
  41512. scene.pushGeometry(sphere, true);
  41513. return sphere;
  41514. };
  41515. return SphereGeometry;
  41516. }(_PrimitiveGeometry));
  41517. BABYLON.SphereGeometry = SphereGeometry;
  41518. /**
  41519. * Creates a disc geometry
  41520. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  41521. */
  41522. var DiscGeometry = /** @class */ (function (_super) {
  41523. __extends(DiscGeometry, _super);
  41524. /**
  41525. * Creates a new disc geometry
  41526. * @param id defines the unique ID of the geometry
  41527. * @param scene defines the hosting scene
  41528. * @param radius defines the radius of the disc
  41529. * @param tessellation defines the tesselation factor to apply to the disc
  41530. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41531. * @param mesh defines the hosting mesh (can be null)
  41532. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41533. */
  41534. function DiscGeometry(id, scene,
  41535. /**
  41536. * Defines the radius of the disc
  41537. */
  41538. radius,
  41539. /**
  41540. * Defines the tesselation factor to apply to the disc
  41541. */
  41542. tessellation, canBeRegenerated, mesh,
  41543. /**
  41544. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41545. */
  41546. side) {
  41547. if (mesh === void 0) { mesh = null; }
  41548. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41549. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41550. _this.radius = radius;
  41551. _this.tessellation = tessellation;
  41552. _this.side = side;
  41553. return _this;
  41554. }
  41555. /** @hidden */
  41556. DiscGeometry.prototype._regenerateVertexData = function () {
  41557. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  41558. };
  41559. DiscGeometry.prototype.copy = function (id) {
  41560. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  41561. };
  41562. return DiscGeometry;
  41563. }(_PrimitiveGeometry));
  41564. BABYLON.DiscGeometry = DiscGeometry;
  41565. /**
  41566. * Creates a new cylinder geometry
  41567. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  41568. */
  41569. var CylinderGeometry = /** @class */ (function (_super) {
  41570. __extends(CylinderGeometry, _super);
  41571. /**
  41572. * Creates a new cylinder geometry
  41573. * @param id defines the unique ID of the geometry
  41574. * @param scene defines the hosting scene
  41575. * @param height defines the height of the cylinder
  41576. * @param diameterTop defines the diameter of the cylinder's top cap
  41577. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  41578. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  41579. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  41580. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41581. * @param mesh defines the hosting mesh (can be null)
  41582. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41583. */
  41584. function CylinderGeometry(id, scene,
  41585. /**
  41586. * Defines the height of the cylinder
  41587. */
  41588. height,
  41589. /**
  41590. * Defines the diameter of the cylinder's top cap
  41591. */
  41592. diameterTop,
  41593. /**
  41594. * Defines the diameter of the cylinder's bottom cap
  41595. */
  41596. diameterBottom,
  41597. /**
  41598. * Defines the tessellation factor to apply to the cylinder
  41599. */
  41600. tessellation,
  41601. /**
  41602. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  41603. */
  41604. subdivisions, canBeRegenerated, mesh,
  41605. /**
  41606. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41607. */
  41608. side) {
  41609. if (subdivisions === void 0) { subdivisions = 1; }
  41610. if (mesh === void 0) { mesh = null; }
  41611. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41612. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41613. _this.height = height;
  41614. _this.diameterTop = diameterTop;
  41615. _this.diameterBottom = diameterBottom;
  41616. _this.tessellation = tessellation;
  41617. _this.subdivisions = subdivisions;
  41618. _this.side = side;
  41619. return _this;
  41620. }
  41621. /** @hidden */
  41622. CylinderGeometry.prototype._regenerateVertexData = function () {
  41623. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  41624. };
  41625. CylinderGeometry.prototype.copy = function (id) {
  41626. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  41627. };
  41628. CylinderGeometry.prototype.serialize = function () {
  41629. var serializationObject = _super.prototype.serialize.call(this);
  41630. serializationObject.height = this.height;
  41631. serializationObject.diameterTop = this.diameterTop;
  41632. serializationObject.diameterBottom = this.diameterBottom;
  41633. serializationObject.tessellation = this.tessellation;
  41634. return serializationObject;
  41635. };
  41636. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  41637. if (scene.getGeometryByID(parsedCylinder.id)) {
  41638. return null; // null since geometry could be something else than a cylinder...
  41639. }
  41640. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  41641. if (BABYLON.Tags) {
  41642. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  41643. }
  41644. scene.pushGeometry(cylinder, true);
  41645. return cylinder;
  41646. };
  41647. return CylinderGeometry;
  41648. }(_PrimitiveGeometry));
  41649. BABYLON.CylinderGeometry = CylinderGeometry;
  41650. /**
  41651. * Creates a new torus geometry
  41652. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  41653. */
  41654. var TorusGeometry = /** @class */ (function (_super) {
  41655. __extends(TorusGeometry, _super);
  41656. /**
  41657. * Creates a new torus geometry
  41658. * @param id defines the unique ID of the geometry
  41659. * @param scene defines the hosting scene
  41660. * @param diameter defines the diameter of the torus
  41661. * @param thickness defines the thickness of the torus (ie. internal diameter)
  41662. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  41663. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41664. * @param mesh defines the hosting mesh (can be null)
  41665. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41666. */
  41667. function TorusGeometry(id, scene,
  41668. /**
  41669. * Defines the diameter of the torus
  41670. */
  41671. diameter,
  41672. /**
  41673. * Defines the thickness of the torus (ie. internal diameter)
  41674. */
  41675. thickness,
  41676. /**
  41677. * Defines the tesselation factor to apply to the torus
  41678. */
  41679. tessellation, canBeRegenerated, mesh,
  41680. /**
  41681. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41682. */
  41683. side) {
  41684. if (mesh === void 0) { mesh = null; }
  41685. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41686. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41687. _this.diameter = diameter;
  41688. _this.thickness = thickness;
  41689. _this.tessellation = tessellation;
  41690. _this.side = side;
  41691. return _this;
  41692. }
  41693. /** @hidden */
  41694. TorusGeometry.prototype._regenerateVertexData = function () {
  41695. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  41696. };
  41697. TorusGeometry.prototype.copy = function (id) {
  41698. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  41699. };
  41700. TorusGeometry.prototype.serialize = function () {
  41701. var serializationObject = _super.prototype.serialize.call(this);
  41702. serializationObject.diameter = this.diameter;
  41703. serializationObject.thickness = this.thickness;
  41704. serializationObject.tessellation = this.tessellation;
  41705. return serializationObject;
  41706. };
  41707. TorusGeometry.Parse = function (parsedTorus, scene) {
  41708. if (scene.getGeometryByID(parsedTorus.id)) {
  41709. return null; // null since geometry could be something else than a torus...
  41710. }
  41711. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  41712. if (BABYLON.Tags) {
  41713. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  41714. }
  41715. scene.pushGeometry(torus, true);
  41716. return torus;
  41717. };
  41718. return TorusGeometry;
  41719. }(_PrimitiveGeometry));
  41720. BABYLON.TorusGeometry = TorusGeometry;
  41721. /**
  41722. * Creates a new ground geometry
  41723. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  41724. */
  41725. var GroundGeometry = /** @class */ (function (_super) {
  41726. __extends(GroundGeometry, _super);
  41727. /**
  41728. * Creates a new ground geometry
  41729. * @param id defines the unique ID of the geometry
  41730. * @param scene defines the hosting scene
  41731. * @param width defines the width of the ground
  41732. * @param height defines the height of the ground
  41733. * @param subdivisions defines the subdivisions to apply to the ground
  41734. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41735. * @param mesh defines the hosting mesh (can be null)
  41736. */
  41737. function GroundGeometry(id, scene,
  41738. /**
  41739. * Defines the width of the ground
  41740. */
  41741. width,
  41742. /**
  41743. * Defines the height of the ground
  41744. */
  41745. height,
  41746. /**
  41747. * Defines the subdivisions to apply to the ground
  41748. */
  41749. subdivisions, canBeRegenerated, mesh) {
  41750. if (mesh === void 0) { mesh = null; }
  41751. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41752. _this.width = width;
  41753. _this.height = height;
  41754. _this.subdivisions = subdivisions;
  41755. return _this;
  41756. }
  41757. /** @hidden */
  41758. GroundGeometry.prototype._regenerateVertexData = function () {
  41759. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  41760. };
  41761. GroundGeometry.prototype.copy = function (id) {
  41762. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  41763. };
  41764. GroundGeometry.prototype.serialize = function () {
  41765. var serializationObject = _super.prototype.serialize.call(this);
  41766. serializationObject.width = this.width;
  41767. serializationObject.height = this.height;
  41768. serializationObject.subdivisions = this.subdivisions;
  41769. return serializationObject;
  41770. };
  41771. GroundGeometry.Parse = function (parsedGround, scene) {
  41772. if (scene.getGeometryByID(parsedGround.id)) {
  41773. return null; // null since geometry could be something else than a ground...
  41774. }
  41775. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  41776. if (BABYLON.Tags) {
  41777. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  41778. }
  41779. scene.pushGeometry(ground, true);
  41780. return ground;
  41781. };
  41782. return GroundGeometry;
  41783. }(_PrimitiveGeometry));
  41784. BABYLON.GroundGeometry = GroundGeometry;
  41785. /**
  41786. * Creates a tiled ground geometry
  41787. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  41788. */
  41789. var TiledGroundGeometry = /** @class */ (function (_super) {
  41790. __extends(TiledGroundGeometry, _super);
  41791. /**
  41792. * Creates a tiled ground geometry
  41793. * @param id defines the unique ID of the geometry
  41794. * @param scene defines the hosting scene
  41795. * @param xmin defines the minimum value on X axis
  41796. * @param zmin defines the minimum value on Z axis
  41797. * @param xmax defines the maximum value on X axis
  41798. * @param zmax defines the maximum value on Z axis
  41799. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  41800. * @param precision defines the precision to use when computing the tiles
  41801. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41802. * @param mesh defines the hosting mesh (can be null)
  41803. */
  41804. function TiledGroundGeometry(id, scene,
  41805. /**
  41806. * Defines the minimum value on X axis
  41807. */
  41808. xmin,
  41809. /**
  41810. * Defines the minimum value on Z axis
  41811. */
  41812. zmin,
  41813. /**
  41814. * Defines the maximum value on X axis
  41815. */
  41816. xmax,
  41817. /**
  41818. * Defines the maximum value on Z axis
  41819. */
  41820. zmax,
  41821. /**
  41822. * Defines the subdivisions to apply to the ground
  41823. */
  41824. subdivisions,
  41825. /**
  41826. * Defines the precision to use when computing the tiles
  41827. */
  41828. precision, canBeRegenerated, mesh) {
  41829. if (mesh === void 0) { mesh = null; }
  41830. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41831. _this.xmin = xmin;
  41832. _this.zmin = zmin;
  41833. _this.xmax = xmax;
  41834. _this.zmax = zmax;
  41835. _this.subdivisions = subdivisions;
  41836. _this.precision = precision;
  41837. return _this;
  41838. }
  41839. /** @hidden */
  41840. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41841. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41842. };
  41843. TiledGroundGeometry.prototype.copy = function (id) {
  41844. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41845. };
  41846. return TiledGroundGeometry;
  41847. }(_PrimitiveGeometry));
  41848. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41849. /**
  41850. * Creates a plane geometry
  41851. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41852. */
  41853. var PlaneGeometry = /** @class */ (function (_super) {
  41854. __extends(PlaneGeometry, _super);
  41855. /**
  41856. * Creates a plane geometry
  41857. * @param id defines the unique ID of the geometry
  41858. * @param scene defines the hosting scene
  41859. * @param size defines the size of the plane (width === height)
  41860. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41861. * @param mesh defines the hosting mesh (can be null)
  41862. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41863. */
  41864. function PlaneGeometry(id, scene,
  41865. /**
  41866. * Defines the size of the plane (width === height)
  41867. */
  41868. size, canBeRegenerated, mesh,
  41869. /**
  41870. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41871. */
  41872. side) {
  41873. if (mesh === void 0) { mesh = null; }
  41874. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41875. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41876. _this.size = size;
  41877. _this.side = side;
  41878. return _this;
  41879. }
  41880. /** @hidden */
  41881. PlaneGeometry.prototype._regenerateVertexData = function () {
  41882. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41883. };
  41884. PlaneGeometry.prototype.copy = function (id) {
  41885. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41886. };
  41887. PlaneGeometry.prototype.serialize = function () {
  41888. var serializationObject = _super.prototype.serialize.call(this);
  41889. serializationObject.size = this.size;
  41890. return serializationObject;
  41891. };
  41892. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41893. if (scene.getGeometryByID(parsedPlane.id)) {
  41894. return null; // null since geometry could be something else than a ground...
  41895. }
  41896. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41897. if (BABYLON.Tags) {
  41898. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41899. }
  41900. scene.pushGeometry(plane, true);
  41901. return plane;
  41902. };
  41903. return PlaneGeometry;
  41904. }(_PrimitiveGeometry));
  41905. BABYLON.PlaneGeometry = PlaneGeometry;
  41906. /**
  41907. * Creates a torus knot geometry
  41908. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41909. */
  41910. var TorusKnotGeometry = /** @class */ (function (_super) {
  41911. __extends(TorusKnotGeometry, _super);
  41912. /**
  41913. * Creates a torus knot geometry
  41914. * @param id defines the unique ID of the geometry
  41915. * @param scene defines the hosting scene
  41916. * @param radius defines the radius of the torus knot
  41917. * @param tube defines the thickness of the torus knot tube
  41918. * @param radialSegments defines the number of radial segments
  41919. * @param tubularSegments defines the number of tubular segments
  41920. * @param p defines the first number of windings
  41921. * @param q defines the second number of windings
  41922. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41923. * @param mesh defines the hosting mesh (can be null)
  41924. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41925. */
  41926. function TorusKnotGeometry(id, scene,
  41927. /**
  41928. * Defines the radius of the torus knot
  41929. */
  41930. radius,
  41931. /**
  41932. * Defines the thickness of the torus knot tube
  41933. */
  41934. tube,
  41935. /**
  41936. * Defines the number of radial segments
  41937. */
  41938. radialSegments,
  41939. /**
  41940. * Defines the number of tubular segments
  41941. */
  41942. tubularSegments,
  41943. /**
  41944. * Defines the first number of windings
  41945. */
  41946. p,
  41947. /**
  41948. * Defines the second number of windings
  41949. */
  41950. q, canBeRegenerated, mesh,
  41951. /**
  41952. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41953. */
  41954. side) {
  41955. if (mesh === void 0) { mesh = null; }
  41956. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41957. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41958. _this.radius = radius;
  41959. _this.tube = tube;
  41960. _this.radialSegments = radialSegments;
  41961. _this.tubularSegments = tubularSegments;
  41962. _this.p = p;
  41963. _this.q = q;
  41964. _this.side = side;
  41965. return _this;
  41966. }
  41967. /** @hidden */
  41968. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41969. 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 });
  41970. };
  41971. TorusKnotGeometry.prototype.copy = function (id) {
  41972. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41973. };
  41974. TorusKnotGeometry.prototype.serialize = function () {
  41975. var serializationObject = _super.prototype.serialize.call(this);
  41976. serializationObject.radius = this.radius;
  41977. serializationObject.tube = this.tube;
  41978. serializationObject.radialSegments = this.radialSegments;
  41979. serializationObject.tubularSegments = this.tubularSegments;
  41980. serializationObject.p = this.p;
  41981. serializationObject.q = this.q;
  41982. return serializationObject;
  41983. };
  41984. ;
  41985. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41986. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41987. return null; // null since geometry could be something else than a ground...
  41988. }
  41989. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41990. if (BABYLON.Tags) {
  41991. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41992. }
  41993. scene.pushGeometry(torusKnot, true);
  41994. return torusKnot;
  41995. };
  41996. return TorusKnotGeometry;
  41997. }(_PrimitiveGeometry));
  41998. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41999. //}
  42000. })(BABYLON || (BABYLON = {}));
  42001. //# sourceMappingURL=babylon.geometry.js.map
  42002. var BABYLON;
  42003. (function (BABYLON) {
  42004. /**
  42005. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  42006. */
  42007. var PerformanceMonitor = /** @class */ (function () {
  42008. /**
  42009. * constructor
  42010. * @param frameSampleSize The number of samples required to saturate the sliding window
  42011. */
  42012. function PerformanceMonitor(frameSampleSize) {
  42013. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  42014. this._enabled = true;
  42015. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  42016. }
  42017. /**
  42018. * Samples current frame
  42019. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  42020. */
  42021. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  42022. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  42023. if (!this._enabled)
  42024. return;
  42025. if (this._lastFrameTimeMs != null) {
  42026. var dt = timeMs - this._lastFrameTimeMs;
  42027. this._rollingFrameTime.add(dt);
  42028. }
  42029. this._lastFrameTimeMs = timeMs;
  42030. };
  42031. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  42032. /**
  42033. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42034. */
  42035. get: function () {
  42036. return this._rollingFrameTime.average;
  42037. },
  42038. enumerable: true,
  42039. configurable: true
  42040. });
  42041. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  42042. /**
  42043. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  42044. */
  42045. get: function () {
  42046. return this._rollingFrameTime.variance;
  42047. },
  42048. enumerable: true,
  42049. configurable: true
  42050. });
  42051. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  42052. /**
  42053. * Returns the frame time of the most recent frame
  42054. */
  42055. get: function () {
  42056. return this._rollingFrameTime.history(0);
  42057. },
  42058. enumerable: true,
  42059. configurable: true
  42060. });
  42061. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  42062. /**
  42063. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  42064. */
  42065. get: function () {
  42066. return 1000.0 / this._rollingFrameTime.average;
  42067. },
  42068. enumerable: true,
  42069. configurable: true
  42070. });
  42071. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  42072. /**
  42073. * Returns the average framerate in frames per second using the most recent frame time
  42074. */
  42075. get: function () {
  42076. var history = this._rollingFrameTime.history(0);
  42077. if (history === 0) {
  42078. return 0;
  42079. }
  42080. return 1000.0 / history;
  42081. },
  42082. enumerable: true,
  42083. configurable: true
  42084. });
  42085. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  42086. /**
  42087. * Returns true if enough samples have been taken to completely fill the sliding window
  42088. */
  42089. get: function () {
  42090. return this._rollingFrameTime.isSaturated();
  42091. },
  42092. enumerable: true,
  42093. configurable: true
  42094. });
  42095. /**
  42096. * Enables contributions to the sliding window sample set
  42097. */
  42098. PerformanceMonitor.prototype.enable = function () {
  42099. this._enabled = true;
  42100. };
  42101. /**
  42102. * Disables contributions to the sliding window sample set
  42103. * Samples will not be interpolated over the disabled period
  42104. */
  42105. PerformanceMonitor.prototype.disable = function () {
  42106. this._enabled = false;
  42107. //clear last sample to avoid interpolating over the disabled period when next enabled
  42108. this._lastFrameTimeMs = null;
  42109. };
  42110. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  42111. /**
  42112. * Returns true if sampling is enabled
  42113. */
  42114. get: function () {
  42115. return this._enabled;
  42116. },
  42117. enumerable: true,
  42118. configurable: true
  42119. });
  42120. /**
  42121. * Resets performance monitor
  42122. */
  42123. PerformanceMonitor.prototype.reset = function () {
  42124. //clear last sample to avoid interpolating over the disabled period when next enabled
  42125. this._lastFrameTimeMs = null;
  42126. //wipe record
  42127. this._rollingFrameTime.reset();
  42128. };
  42129. return PerformanceMonitor;
  42130. }());
  42131. BABYLON.PerformanceMonitor = PerformanceMonitor;
  42132. /**
  42133. * RollingAverage
  42134. *
  42135. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  42136. */
  42137. var RollingAverage = /** @class */ (function () {
  42138. /**
  42139. * constructor
  42140. * @param length The number of samples required to saturate the sliding window
  42141. */
  42142. function RollingAverage(length) {
  42143. this._samples = new Array(length);
  42144. this.reset();
  42145. }
  42146. /**
  42147. * Adds a sample to the sample set
  42148. * @param v The sample value
  42149. */
  42150. RollingAverage.prototype.add = function (v) {
  42151. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  42152. var delta;
  42153. //we need to check if we've already wrapped round
  42154. if (this.isSaturated()) {
  42155. //remove bottom of stack from mean
  42156. var bottomValue = this._samples[this._pos];
  42157. delta = bottomValue - this.average;
  42158. this.average -= delta / (this._sampleCount - 1);
  42159. this._m2 -= delta * (bottomValue - this.average);
  42160. }
  42161. else {
  42162. this._sampleCount++;
  42163. }
  42164. //add new value to mean
  42165. delta = v - this.average;
  42166. this.average += delta / (this._sampleCount);
  42167. this._m2 += delta * (v - this.average);
  42168. //set the new variance
  42169. this.variance = this._m2 / (this._sampleCount - 1);
  42170. this._samples[this._pos] = v;
  42171. this._pos++;
  42172. this._pos %= this._samples.length; //positive wrap around
  42173. };
  42174. /**
  42175. * Returns previously added values or null if outside of history or outside the sliding window domain
  42176. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  42177. * @return Value previously recorded with add() or null if outside of range
  42178. */
  42179. RollingAverage.prototype.history = function (i) {
  42180. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  42181. return 0;
  42182. }
  42183. var i0 = this._wrapPosition(this._pos - 1.0);
  42184. return this._samples[this._wrapPosition(i0 - i)];
  42185. };
  42186. /**
  42187. * Returns true if enough samples have been taken to completely fill the sliding window
  42188. * @return true if sample-set saturated
  42189. */
  42190. RollingAverage.prototype.isSaturated = function () {
  42191. return this._sampleCount >= this._samples.length;
  42192. };
  42193. /**
  42194. * Resets the rolling average (equivalent to 0 samples taken so far)
  42195. */
  42196. RollingAverage.prototype.reset = function () {
  42197. this.average = 0;
  42198. this.variance = 0;
  42199. this._sampleCount = 0;
  42200. this._pos = 0;
  42201. this._m2 = 0;
  42202. };
  42203. /**
  42204. * Wraps a value around the sample range boundaries
  42205. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  42206. * @return Wrapped position in sample range
  42207. */
  42208. RollingAverage.prototype._wrapPosition = function (i) {
  42209. var max = this._samples.length;
  42210. return ((i % max) + max) % max;
  42211. };
  42212. return RollingAverage;
  42213. }());
  42214. BABYLON.RollingAverage = RollingAverage;
  42215. })(BABYLON || (BABYLON = {}));
  42216. //# sourceMappingURL=babylon.performanceMonitor.js.map
  42217. var BABYLON;
  42218. (function (BABYLON) {
  42219. /**
  42220. * "Static Class" containing the most commonly used helper while dealing with material for
  42221. * rendering purpose.
  42222. *
  42223. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42224. *
  42225. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42226. */
  42227. var MaterialHelper = /** @class */ (function () {
  42228. function MaterialHelper() {
  42229. }
  42230. /**
  42231. * Bind the current view position to an effect.
  42232. * @param effect The effect to be bound
  42233. * @param scene The scene the eyes position is used from
  42234. */
  42235. MaterialHelper.BindEyePosition = function (effect, scene) {
  42236. if (scene._forcedViewPosition) {
  42237. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42238. return;
  42239. }
  42240. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42241. };
  42242. /**
  42243. * Helps preparing the defines values about the UVs in used in the effect.
  42244. * UVs are shared as much as we can accross channels in the shaders.
  42245. * @param texture The texture we are preparing the UVs for
  42246. * @param defines The defines to update
  42247. * @param key The channel key "diffuse", "specular"... used in the shader
  42248. */
  42249. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42250. defines._needUVs = true;
  42251. defines[key] = true;
  42252. if (texture.getTextureMatrix().isIdentity(true)) {
  42253. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42254. if (texture.coordinatesIndex === 0) {
  42255. defines["MAINUV1"] = true;
  42256. }
  42257. else {
  42258. defines["MAINUV2"] = true;
  42259. }
  42260. }
  42261. else {
  42262. defines[key + "DIRECTUV"] = 0;
  42263. }
  42264. };
  42265. /**
  42266. * Binds a texture matrix value to its corrsponding uniform
  42267. * @param texture The texture to bind the matrix for
  42268. * @param uniformBuffer The uniform buffer receivin the data
  42269. * @param key The channel key "diffuse", "specular"... used in the shader
  42270. */
  42271. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42272. var matrix = texture.getTextureMatrix();
  42273. if (!matrix.isIdentity(true)) {
  42274. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42275. }
  42276. };
  42277. /**
  42278. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42279. * @param mesh defines the current mesh
  42280. * @param scene defines the current scene
  42281. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42282. * @param pointsCloud defines if point cloud rendering has to be turned on
  42283. * @param fogEnabled defines if fog has to be turned on
  42284. * @param alphaTest defines if alpha testing has to be turned on
  42285. * @param defines defines the current list of defines
  42286. */
  42287. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42288. if (defines._areMiscDirty) {
  42289. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42290. defines["POINTSIZE"] = pointsCloud;
  42291. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42292. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42293. defines["ALPHATEST"] = alphaTest;
  42294. }
  42295. };
  42296. /**
  42297. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42298. * @param scene defines the current scene
  42299. * @param engine defines the current engine
  42300. * @param defines specifies the list of active defines
  42301. * @param useInstances defines if instances have to be turned on
  42302. * @param useClipPlane defines if clip plane have to be turned on
  42303. */
  42304. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42305. if (useClipPlane === void 0) { useClipPlane = null; }
  42306. var changed = false;
  42307. var useClipPlane1 = false;
  42308. var useClipPlane2 = false;
  42309. var useClipPlane3 = false;
  42310. var useClipPlane4 = false;
  42311. useClipPlane1 = useClipPlane == null ? (scene.clipPlane !== undefined && scene.clipPlane !== null) : useClipPlane;
  42312. useClipPlane2 = useClipPlane == null ? (scene.clipPlane2 !== undefined && scene.clipPlane2 !== null) : useClipPlane;
  42313. useClipPlane3 = useClipPlane == null ? (scene.clipPlane3 !== undefined && scene.clipPlane3 !== null) : useClipPlane;
  42314. useClipPlane4 = useClipPlane == null ? (scene.clipPlane4 !== undefined && scene.clipPlane4 !== null) : useClipPlane;
  42315. if (defines["CLIPPLANE"] !== useClipPlane1) {
  42316. defines["CLIPPLANE"] = useClipPlane1;
  42317. changed = true;
  42318. }
  42319. if (defines["CLIPPLANE2"] !== useClipPlane2) {
  42320. defines["CLIPPLANE2"] = useClipPlane2;
  42321. changed = true;
  42322. }
  42323. if (defines["CLIPPLANE3"] !== useClipPlane3) {
  42324. defines["CLIPPLANE3"] = useClipPlane3;
  42325. changed = true;
  42326. }
  42327. if (defines["CLIPPLANE4"] !== useClipPlane4) {
  42328. defines["CLIPPLANE4"] = useClipPlane4;
  42329. changed = true;
  42330. }
  42331. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42332. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42333. changed = true;
  42334. }
  42335. if (defines["INSTANCES"] !== useInstances) {
  42336. defines["INSTANCES"] = useInstances;
  42337. changed = true;
  42338. }
  42339. if (changed) {
  42340. defines.markAsUnprocessed();
  42341. }
  42342. };
  42343. /**
  42344. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42345. * @param mesh The mesh containing the geometry data we will draw
  42346. * @param defines The defines to update
  42347. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42348. * @param useBones Precise whether bones should be used or not (override mesh info)
  42349. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42350. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42351. * @returns false if defines are considered not dirty and have not been checked
  42352. */
  42353. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42354. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42355. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42356. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42357. return false;
  42358. }
  42359. defines._normals = defines._needNormals;
  42360. defines._uvs = defines._needUVs;
  42361. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42362. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42363. defines["TANGENT"] = true;
  42364. }
  42365. if (defines._needUVs) {
  42366. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42367. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42368. }
  42369. else {
  42370. defines["UV1"] = false;
  42371. defines["UV2"] = false;
  42372. }
  42373. if (useVertexColor) {
  42374. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42375. defines["VERTEXCOLOR"] = hasVertexColors;
  42376. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42377. }
  42378. if (useBones) {
  42379. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42380. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42381. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42382. }
  42383. else {
  42384. defines["NUM_BONE_INFLUENCERS"] = 0;
  42385. defines["BonesPerMesh"] = 0;
  42386. }
  42387. }
  42388. if (useMorphTargets) {
  42389. var manager = mesh.morphTargetManager;
  42390. if (manager) {
  42391. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42392. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42393. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42394. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42395. }
  42396. else {
  42397. defines["MORPHTARGETS_TANGENT"] = false;
  42398. defines["MORPHTARGETS_NORMAL"] = false;
  42399. defines["MORPHTARGETS"] = false;
  42400. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42401. }
  42402. }
  42403. return true;
  42404. };
  42405. /**
  42406. * Prepares the defines related to the light information passed in parameter
  42407. * @param scene The scene we are intending to draw
  42408. * @param mesh The mesh the effect is compiling for
  42409. * @param defines The defines to update
  42410. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42411. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42412. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42413. * @returns true if normals will be required for the rest of the effect
  42414. */
  42415. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42416. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42417. if (disableLighting === void 0) { disableLighting = false; }
  42418. if (!defines._areLightsDirty) {
  42419. return defines._needNormals;
  42420. }
  42421. var lightIndex = 0;
  42422. var needNormals = false;
  42423. var needRebuild = false;
  42424. var lightmapMode = false;
  42425. var shadowEnabled = false;
  42426. var specularEnabled = false;
  42427. if (scene.lightsEnabled && !disableLighting) {
  42428. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42429. var light = _a[_i];
  42430. needNormals = true;
  42431. if (defines["LIGHT" + lightIndex] === undefined) {
  42432. needRebuild = true;
  42433. }
  42434. defines["LIGHT" + lightIndex] = true;
  42435. defines["SPOTLIGHT" + lightIndex] = false;
  42436. defines["HEMILIGHT" + lightIndex] = false;
  42437. defines["POINTLIGHT" + lightIndex] = false;
  42438. defines["DIRLIGHT" + lightIndex] = false;
  42439. light.prepareLightSpecificDefines(defines, lightIndex);
  42440. // FallOff.
  42441. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = false;
  42442. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = false;
  42443. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = false;
  42444. switch (light.falloffType) {
  42445. case BABYLON.Light.FALLOFF_GLTF:
  42446. defines["LIGHT_FALLOFF_GLTF" + lightIndex] = true;
  42447. break;
  42448. case BABYLON.Light.FALLOFF_PHYSICAL:
  42449. defines["LIGHT_FALLOFF_PHYSICAL" + lightIndex] = true;
  42450. break;
  42451. case BABYLON.Light.FALLOFF_STANDARD:
  42452. defines["LIGHT_FALLOFF_STANDARD" + lightIndex] = true;
  42453. break;
  42454. }
  42455. // Specular
  42456. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42457. specularEnabled = true;
  42458. }
  42459. // Shadows
  42460. defines["SHADOW" + lightIndex] = false;
  42461. defines["SHADOWPCF" + lightIndex] = false;
  42462. defines["SHADOWPCSS" + lightIndex] = false;
  42463. defines["SHADOWPOISSON" + lightIndex] = false;
  42464. defines["SHADOWESM" + lightIndex] = false;
  42465. defines["SHADOWCUBE" + lightIndex] = false;
  42466. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42467. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42468. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42469. var shadowGenerator = light.getShadowGenerator();
  42470. if (shadowGenerator) {
  42471. var shadowMap = shadowGenerator.getShadowMap();
  42472. if (shadowMap) {
  42473. if (shadowMap.renderList && shadowMap.renderList.length > 0) {
  42474. shadowEnabled = true;
  42475. shadowGenerator.prepareDefines(defines, lightIndex);
  42476. }
  42477. }
  42478. }
  42479. }
  42480. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42481. lightmapMode = true;
  42482. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42483. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42484. }
  42485. else {
  42486. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42487. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42488. }
  42489. lightIndex++;
  42490. if (lightIndex === maxSimultaneousLights)
  42491. break;
  42492. }
  42493. }
  42494. defines["SPECULARTERM"] = specularEnabled;
  42495. defines["SHADOWS"] = shadowEnabled;
  42496. // Resetting all other lights if any
  42497. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42498. if (defines["LIGHT" + index] !== undefined) {
  42499. defines["LIGHT" + index] = false;
  42500. defines["HEMILIGHT" + lightIndex] = false;
  42501. defines["POINTLIGHT" + lightIndex] = false;
  42502. defines["DIRLIGHT" + lightIndex] = false;
  42503. defines["SPOTLIGHT" + lightIndex] = false;
  42504. defines["SHADOW" + lightIndex] = false;
  42505. }
  42506. }
  42507. var caps = scene.getEngine().getCaps();
  42508. if (defines["SHADOWFLOAT"] === undefined) {
  42509. needRebuild = true;
  42510. }
  42511. defines["SHADOWFLOAT"] = shadowEnabled &&
  42512. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42513. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42514. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42515. if (needRebuild) {
  42516. defines.rebuild();
  42517. }
  42518. return needNormals;
  42519. };
  42520. /**
  42521. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42522. * that won t be acctive due to defines being turned off.
  42523. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42524. * @param samplersList The samplers list
  42525. * @param defines The defines helping in the list generation
  42526. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42527. */
  42528. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42529. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42530. var uniformsList;
  42531. var uniformBuffersList = null;
  42532. if (uniformsListOrOptions.uniformsNames) {
  42533. var options = uniformsListOrOptions;
  42534. uniformsList = options.uniformsNames;
  42535. uniformBuffersList = options.uniformBuffersNames;
  42536. samplersList = options.samplers;
  42537. defines = options.defines;
  42538. maxSimultaneousLights = options.maxSimultaneousLights;
  42539. }
  42540. else {
  42541. uniformsList = uniformsListOrOptions;
  42542. if (!samplersList) {
  42543. samplersList = [];
  42544. }
  42545. }
  42546. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42547. if (!defines["LIGHT" + lightIndex]) {
  42548. break;
  42549. }
  42550. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightFalloff" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42551. if (uniformBuffersList) {
  42552. uniformBuffersList.push("Light" + lightIndex);
  42553. }
  42554. samplersList.push("shadowSampler" + lightIndex);
  42555. samplersList.push("depthSampler" + lightIndex);
  42556. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42557. samplersList.push("projectionLightSampler" + lightIndex);
  42558. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42559. }
  42560. }
  42561. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42562. uniformsList.push("morphTargetInfluences");
  42563. }
  42564. };
  42565. /**
  42566. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42567. * @param defines The defines to update while falling back
  42568. * @param fallbacks The authorized effect fallbacks
  42569. * @param maxSimultaneousLights The maximum number of lights allowed
  42570. * @param rank the current rank of the Effect
  42571. * @returns The newly affected rank
  42572. */
  42573. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42574. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42575. if (rank === void 0) { rank = 0; }
  42576. var lightFallbackRank = 0;
  42577. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42578. if (!defines["LIGHT" + lightIndex]) {
  42579. break;
  42580. }
  42581. if (lightIndex > 0) {
  42582. lightFallbackRank = rank + lightIndex;
  42583. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42584. }
  42585. if (!defines["SHADOWS"]) {
  42586. if (defines["SHADOW" + lightIndex]) {
  42587. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42588. }
  42589. if (defines["SHADOWPCF" + lightIndex]) {
  42590. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42591. }
  42592. if (defines["SHADOWPCSS" + lightIndex]) {
  42593. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42594. }
  42595. if (defines["SHADOWPOISSON" + lightIndex]) {
  42596. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42597. }
  42598. if (defines["SHADOWESM" + lightIndex]) {
  42599. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42600. }
  42601. }
  42602. }
  42603. return lightFallbackRank++;
  42604. };
  42605. /**
  42606. * Prepares the list of attributes required for morph targets according to the effect defines.
  42607. * @param attribs The current list of supported attribs
  42608. * @param mesh The mesh to prepare the morph targets attributes for
  42609. * @param defines The current Defines of the effect
  42610. */
  42611. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42612. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42613. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42614. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42615. var manager = mesh.morphTargetManager;
  42616. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42617. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42618. for (var index = 0; index < influencers; index++) {
  42619. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42620. if (normal) {
  42621. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42622. }
  42623. if (tangent) {
  42624. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42625. }
  42626. if (attribs.length > maxAttributesCount) {
  42627. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42628. }
  42629. }
  42630. }
  42631. };
  42632. /**
  42633. * Prepares the list of attributes required for bones according to the effect defines.
  42634. * @param attribs The current list of supported attribs
  42635. * @param mesh The mesh to prepare the bones attributes for
  42636. * @param defines The current Defines of the effect
  42637. * @param fallbacks The current efffect fallback strategy
  42638. */
  42639. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42640. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42641. fallbacks.addCPUSkinningFallback(0, mesh);
  42642. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42643. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42644. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42645. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42646. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42647. }
  42648. }
  42649. };
  42650. /**
  42651. * Prepares the list of attributes required for instances according to the effect defines.
  42652. * @param attribs The current list of supported attribs
  42653. * @param defines The current Defines of the effect
  42654. */
  42655. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42656. if (defines["INSTANCES"]) {
  42657. attribs.push("world0");
  42658. attribs.push("world1");
  42659. attribs.push("world2");
  42660. attribs.push("world3");
  42661. }
  42662. };
  42663. /**
  42664. * Binds the light shadow information to the effect for the given mesh.
  42665. * @param light The light containing the generator
  42666. * @param scene The scene the lights belongs to
  42667. * @param mesh The mesh we are binding the information to render
  42668. * @param lightIndex The light index in the effect used to render the mesh
  42669. * @param effect The effect we are binding the data to
  42670. */
  42671. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42672. if (light.shadowEnabled && mesh.receiveShadows) {
  42673. var shadowGenerator = light.getShadowGenerator();
  42674. if (shadowGenerator) {
  42675. shadowGenerator.bindShadowLight(lightIndex, effect);
  42676. }
  42677. }
  42678. };
  42679. /**
  42680. * Binds the light information to the effect.
  42681. * @param light The light containing the generator
  42682. * @param effect The effect we are binding the data to
  42683. * @param lightIndex The light index in the effect used to render
  42684. */
  42685. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42686. light.transferToEffect(effect, lightIndex + "");
  42687. };
  42688. /**
  42689. * Binds the lights information from the scene to the effect for the given mesh.
  42690. * @param scene The scene the lights belongs to
  42691. * @param mesh The mesh we are binding the information to render
  42692. * @param effect The effect we are binding the data to
  42693. * @param defines The generated defines for the effect
  42694. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42695. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42696. */
  42697. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42698. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42699. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42700. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42701. for (var i = 0; i < len; i++) {
  42702. var light = mesh._lightSources[i];
  42703. var iAsString = i.toString();
  42704. var scaledIntensity = light.getScaledIntensity();
  42705. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42706. MaterialHelper.BindLightProperties(light, effect, i);
  42707. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42708. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42709. if (defines["SPECULARTERM"]) {
  42710. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42711. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42712. }
  42713. // Shadows
  42714. if (scene.shadowsEnabled) {
  42715. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42716. }
  42717. light._uniformBuffer.update();
  42718. }
  42719. };
  42720. /**
  42721. * Binds the fog information from the scene to the effect for the given mesh.
  42722. * @param scene The scene the lights belongs to
  42723. * @param mesh The mesh we are binding the information to render
  42724. * @param effect The effect we are binding the data to
  42725. * @param linearSpace Defines if the fog effect is applied in linear space
  42726. */
  42727. MaterialHelper.BindFogParameters = function (scene, mesh, effect, linearSpace) {
  42728. if (linearSpace === void 0) { linearSpace = false; }
  42729. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42730. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42731. // Convert fog color to linear space if used in a linear space computed shader.
  42732. if (linearSpace) {
  42733. scene.fogColor.toLinearSpaceToRef(this._tempFogColor);
  42734. effect.setColor3("vFogColor", this._tempFogColor);
  42735. }
  42736. else {
  42737. effect.setColor3("vFogColor", scene.fogColor);
  42738. }
  42739. }
  42740. };
  42741. /**
  42742. * Binds the bones information from the mesh to the effect.
  42743. * @param mesh The mesh we are binding the information to render
  42744. * @param effect The effect we are binding the data to
  42745. */
  42746. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42747. if (!effect || !mesh) {
  42748. return;
  42749. }
  42750. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42751. mesh.computeBonesUsingShaders = false;
  42752. }
  42753. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42754. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42755. if (matrices) {
  42756. effect.setMatrices("mBones", matrices);
  42757. }
  42758. }
  42759. };
  42760. /**
  42761. * Binds the morph targets information from the mesh to the effect.
  42762. * @param abstractMesh The mesh we are binding the information to render
  42763. * @param effect The effect we are binding the data to
  42764. */
  42765. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42766. var manager = abstractMesh.morphTargetManager;
  42767. if (!abstractMesh || !manager) {
  42768. return;
  42769. }
  42770. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42771. };
  42772. /**
  42773. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42774. * @param defines The generated defines used in the effect
  42775. * @param effect The effect we are binding the data to
  42776. * @param scene The scene we are willing to render with logarithmic scale for
  42777. */
  42778. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42779. if (defines["LOGARITHMICDEPTH"]) {
  42780. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42781. }
  42782. };
  42783. /**
  42784. * Binds the clip plane information from the scene to the effect.
  42785. * @param scene The scene the clip plane information are extracted from
  42786. * @param effect The effect we are binding the data to
  42787. */
  42788. MaterialHelper.BindClipPlane = function (effect, scene) {
  42789. if (scene.clipPlane) {
  42790. var clipPlane = scene.clipPlane;
  42791. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42792. }
  42793. if (scene.clipPlane2) {
  42794. var clipPlane = scene.clipPlane2;
  42795. effect.setFloat4("vClipPlane2", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42796. }
  42797. if (scene.clipPlane3) {
  42798. var clipPlane = scene.clipPlane3;
  42799. effect.setFloat4("vClipPlane3", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42800. }
  42801. if (scene.clipPlane4) {
  42802. var clipPlane = scene.clipPlane4;
  42803. effect.setFloat4("vClipPlane4", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42804. }
  42805. };
  42806. MaterialHelper._tempFogColor = BABYLON.Color3.Black();
  42807. return MaterialHelper;
  42808. }());
  42809. BABYLON.MaterialHelper = MaterialHelper;
  42810. })(BABYLON || (BABYLON = {}));
  42811. //# sourceMappingURL=babylon.materialHelper.js.map
  42812. var BABYLON;
  42813. (function (BABYLON) {
  42814. /**
  42815. * Base class of materials working in push mode in babylon JS
  42816. * @hidden
  42817. */
  42818. var PushMaterial = /** @class */ (function (_super) {
  42819. __extends(PushMaterial, _super);
  42820. function PushMaterial(name, scene) {
  42821. var _this = _super.call(this, name, scene) || this;
  42822. _this._normalMatrix = new BABYLON.Matrix();
  42823. _this.storeEffectOnSubMeshes = true;
  42824. return _this;
  42825. }
  42826. PushMaterial.prototype.getEffect = function () {
  42827. return this._activeEffect;
  42828. };
  42829. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42830. if (!mesh) {
  42831. return false;
  42832. }
  42833. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42834. return true;
  42835. }
  42836. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42837. };
  42838. /**
  42839. * Binds the given world matrix to the active effect
  42840. *
  42841. * @param world the matrix to bind
  42842. */
  42843. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42844. this._activeEffect.setMatrix("world", world);
  42845. };
  42846. /**
  42847. * Binds the given normal matrix to the active effect
  42848. *
  42849. * @param normalMatrix the matrix to bind
  42850. */
  42851. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42852. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42853. };
  42854. PushMaterial.prototype.bind = function (world, mesh) {
  42855. if (!mesh) {
  42856. return;
  42857. }
  42858. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42859. };
  42860. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42861. if (effect === void 0) { effect = null; }
  42862. _super.prototype._afterBind.call(this, mesh);
  42863. this.getScene()._cachedEffect = effect;
  42864. };
  42865. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42866. if (visibility === void 0) { visibility = 1; }
  42867. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42868. };
  42869. return PushMaterial;
  42870. }(BABYLON.Material));
  42871. BABYLON.PushMaterial = PushMaterial;
  42872. })(BABYLON || (BABYLON = {}));
  42873. //# sourceMappingURL=babylon.pushMaterial.js.map
  42874. var BABYLON;
  42875. (function (BABYLON) {
  42876. /** @hidden */
  42877. var StandardMaterialDefines = /** @class */ (function (_super) {
  42878. __extends(StandardMaterialDefines, _super);
  42879. function StandardMaterialDefines() {
  42880. var _this = _super.call(this) || this;
  42881. _this.MAINUV1 = false;
  42882. _this.MAINUV2 = false;
  42883. _this.DIFFUSE = false;
  42884. _this.DIFFUSEDIRECTUV = 0;
  42885. _this.AMBIENT = false;
  42886. _this.AMBIENTDIRECTUV = 0;
  42887. _this.OPACITY = false;
  42888. _this.OPACITYDIRECTUV = 0;
  42889. _this.OPACITYRGB = false;
  42890. _this.REFLECTION = false;
  42891. _this.EMISSIVE = false;
  42892. _this.EMISSIVEDIRECTUV = 0;
  42893. _this.SPECULAR = false;
  42894. _this.SPECULARDIRECTUV = 0;
  42895. _this.BUMP = false;
  42896. _this.BUMPDIRECTUV = 0;
  42897. _this.PARALLAX = false;
  42898. _this.PARALLAXOCCLUSION = false;
  42899. _this.SPECULAROVERALPHA = false;
  42900. _this.CLIPPLANE = false;
  42901. _this.CLIPPLANE2 = false;
  42902. _this.CLIPPLANE3 = false;
  42903. _this.CLIPPLANE4 = false;
  42904. _this.ALPHATEST = false;
  42905. _this.DEPTHPREPASS = false;
  42906. _this.ALPHAFROMDIFFUSE = false;
  42907. _this.POINTSIZE = false;
  42908. _this.FOG = false;
  42909. _this.SPECULARTERM = false;
  42910. _this.DIFFUSEFRESNEL = false;
  42911. _this.OPACITYFRESNEL = false;
  42912. _this.REFLECTIONFRESNEL = false;
  42913. _this.REFRACTIONFRESNEL = false;
  42914. _this.EMISSIVEFRESNEL = false;
  42915. _this.FRESNEL = false;
  42916. _this.NORMAL = false;
  42917. _this.UV1 = false;
  42918. _this.UV2 = false;
  42919. _this.VERTEXCOLOR = false;
  42920. _this.VERTEXALPHA = false;
  42921. _this.NUM_BONE_INFLUENCERS = 0;
  42922. _this.BonesPerMesh = 0;
  42923. _this.INSTANCES = false;
  42924. _this.GLOSSINESS = false;
  42925. _this.ROUGHNESS = false;
  42926. _this.EMISSIVEASILLUMINATION = false;
  42927. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42928. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42929. _this.LIGHTMAP = false;
  42930. _this.LIGHTMAPDIRECTUV = 0;
  42931. _this.OBJECTSPACE_NORMALMAP = false;
  42932. _this.USELIGHTMAPASSHADOWMAP = false;
  42933. _this.REFLECTIONMAP_3D = false;
  42934. _this.REFLECTIONMAP_SPHERICAL = false;
  42935. _this.REFLECTIONMAP_PLANAR = false;
  42936. _this.REFLECTIONMAP_CUBIC = false;
  42937. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42938. _this.REFLECTIONMAP_PROJECTION = false;
  42939. _this.REFLECTIONMAP_SKYBOX = false;
  42940. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  42941. _this.REFLECTIONMAP_EXPLICIT = false;
  42942. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42943. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42944. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42945. _this.INVERTCUBICMAP = false;
  42946. _this.LOGARITHMICDEPTH = false;
  42947. _this.REFRACTION = false;
  42948. _this.REFRACTIONMAP_3D = false;
  42949. _this.REFLECTIONOVERALPHA = false;
  42950. _this.TWOSIDEDLIGHTING = false;
  42951. _this.SHADOWFLOAT = false;
  42952. _this.MORPHTARGETS = false;
  42953. _this.MORPHTARGETS_NORMAL = false;
  42954. _this.MORPHTARGETS_TANGENT = false;
  42955. _this.NUM_MORPH_INFLUENCERS = 0;
  42956. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42957. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42958. _this.IMAGEPROCESSING = false;
  42959. _this.VIGNETTE = false;
  42960. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42961. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42962. _this.TONEMAPPING = false;
  42963. _this.TONEMAPPING_ACES = false;
  42964. _this.CONTRAST = false;
  42965. _this.COLORCURVES = false;
  42966. _this.COLORGRADING = false;
  42967. _this.COLORGRADING3D = false;
  42968. _this.SAMPLER3DGREENDEPTH = false;
  42969. _this.SAMPLER3DBGRMAP = false;
  42970. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42971. /**
  42972. * If the reflection texture on this material is in linear color space
  42973. * @hidden
  42974. */
  42975. _this.IS_REFLECTION_LINEAR = false;
  42976. /**
  42977. * If the refraction texture on this material is in linear color space
  42978. * @hidden
  42979. */
  42980. _this.IS_REFRACTION_LINEAR = false;
  42981. _this.EXPOSURE = false;
  42982. _this.rebuild();
  42983. return _this;
  42984. }
  42985. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42986. var modes = [
  42987. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42988. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42989. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42990. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42991. ];
  42992. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42993. var mode = modes_1[_i];
  42994. this[mode] = (mode === modeToEnable);
  42995. }
  42996. };
  42997. return StandardMaterialDefines;
  42998. }(BABYLON.MaterialDefines));
  42999. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  43000. /**
  43001. * This is the default material used in Babylon. It is the best trade off between quality
  43002. * and performances.
  43003. * @see http://doc.babylonjs.com/babylon101/materials
  43004. */
  43005. var StandardMaterial = /** @class */ (function (_super) {
  43006. __extends(StandardMaterial, _super);
  43007. /**
  43008. * Instantiates a new standard material.
  43009. * This is the default material used in Babylon. It is the best trade off between quality
  43010. * and performances.
  43011. * @see http://doc.babylonjs.com/babylon101/materials
  43012. * @param name Define the name of the material in the scene
  43013. * @param scene Define the scene the material belong to
  43014. */
  43015. function StandardMaterial(name, scene) {
  43016. var _this = _super.call(this, name, scene) || this;
  43017. /**
  43018. * The color of the material lit by the environmental background lighting.
  43019. * @see http://doc.babylonjs.com/babylon101/materials#ambient-color-example
  43020. */
  43021. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  43022. /**
  43023. * The basic color of the material as viewed under a light.
  43024. */
  43025. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  43026. /**
  43027. * Define how the color and intensity of the highlight given by the light in the material.
  43028. */
  43029. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  43030. /**
  43031. * Define the color of the material as if self lit.
  43032. * This will be mixed in the final result even in the absence of light.
  43033. */
  43034. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  43035. /**
  43036. * Defines how sharp are the highlights in the material.
  43037. * The bigger the value the sharper giving a more glossy feeling to the result.
  43038. * Reversely, the smaller the value the blurrier giving a more rough feeling to the result.
  43039. */
  43040. _this.specularPower = 64;
  43041. _this._useAlphaFromDiffuseTexture = false;
  43042. _this._useEmissiveAsIllumination = false;
  43043. _this._linkEmissiveWithDiffuse = false;
  43044. _this._useSpecularOverAlpha = false;
  43045. _this._useReflectionOverAlpha = false;
  43046. _this._disableLighting = false;
  43047. _this._useObjectSpaceNormalMap = false;
  43048. _this._useParallax = false;
  43049. _this._useParallaxOcclusion = false;
  43050. /**
  43051. * 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.
  43052. */
  43053. _this.parallaxScaleBias = 0.05;
  43054. _this._roughness = 0;
  43055. /**
  43056. * In case of refraction, define the value of the indice of refraction.
  43057. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43058. */
  43059. _this.indexOfRefraction = 0.98;
  43060. /**
  43061. * Invert the refraction texture alongside the y axis.
  43062. * It can be usefull with procedural textures or probe for instance.
  43063. * @see http://doc.babylonjs.com/how_to/reflect#how-to-obtain-reflections-and-refractions
  43064. */
  43065. _this.invertRefractionY = true;
  43066. /**
  43067. * Defines the alpha limits in alpha test mode.
  43068. */
  43069. _this.alphaCutOff = 0.4;
  43070. _this._useLightmapAsShadowmap = false;
  43071. _this._useReflectionFresnelFromSpecular = false;
  43072. _this._useGlossinessFromSpecularMapAlpha = false;
  43073. _this._maxSimultaneousLights = 4;
  43074. _this._invertNormalMapX = false;
  43075. _this._invertNormalMapY = false;
  43076. _this._twoSidedLighting = false;
  43077. _this._renderTargets = new BABYLON.SmartArray(16);
  43078. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  43079. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43080. // Setup the default processing configuration to the scene.
  43081. _this._attachImageProcessingConfiguration(null);
  43082. _this.getRenderTargetTextures = function () {
  43083. _this._renderTargets.reset();
  43084. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43085. _this._renderTargets.push(_this._reflectionTexture);
  43086. }
  43087. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43088. _this._renderTargets.push(_this._refractionTexture);
  43089. }
  43090. return _this._renderTargets;
  43091. };
  43092. return _this;
  43093. }
  43094. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43095. /**
  43096. * Gets the image processing configuration used either in this material.
  43097. */
  43098. get: function () {
  43099. return this._imageProcessingConfiguration;
  43100. },
  43101. /**
  43102. * Sets the Default image processing configuration used either in the this material.
  43103. *
  43104. * If sets to null, the scene one is in use.
  43105. */
  43106. set: function (value) {
  43107. this._attachImageProcessingConfiguration(value);
  43108. // Ensure the effect will be rebuilt.
  43109. this._markAllSubMeshesAsTexturesDirty();
  43110. },
  43111. enumerable: true,
  43112. configurable: true
  43113. });
  43114. /**
  43115. * Attaches a new image processing configuration to the Standard Material.
  43116. * @param configuration
  43117. */
  43118. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43119. var _this = this;
  43120. if (configuration === this._imageProcessingConfiguration) {
  43121. return;
  43122. }
  43123. // Detaches observer.
  43124. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43125. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43126. }
  43127. // Pick the scene configuration if needed.
  43128. if (!configuration) {
  43129. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43130. }
  43131. else {
  43132. this._imageProcessingConfiguration = configuration;
  43133. }
  43134. // Attaches observer.
  43135. if (this._imageProcessingConfiguration) {
  43136. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43137. _this._markAllSubMeshesAsImageProcessingDirty();
  43138. });
  43139. }
  43140. };
  43141. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43142. /**
  43143. * Gets wether the color curves effect is enabled.
  43144. */
  43145. get: function () {
  43146. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43147. },
  43148. /**
  43149. * Sets wether the color curves effect is enabled.
  43150. */
  43151. set: function (value) {
  43152. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43153. },
  43154. enumerable: true,
  43155. configurable: true
  43156. });
  43157. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43158. /**
  43159. * Gets wether the color grading effect is enabled.
  43160. */
  43161. get: function () {
  43162. return this.imageProcessingConfiguration.colorGradingEnabled;
  43163. },
  43164. /**
  43165. * Gets wether the color grading effect is enabled.
  43166. */
  43167. set: function (value) {
  43168. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43169. },
  43170. enumerable: true,
  43171. configurable: true
  43172. });
  43173. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43174. /**
  43175. * Gets wether tonemapping is enabled or not.
  43176. */
  43177. get: function () {
  43178. return this._imageProcessingConfiguration.toneMappingEnabled;
  43179. },
  43180. /**
  43181. * Sets wether tonemapping is enabled or not
  43182. */
  43183. set: function (value) {
  43184. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43185. },
  43186. enumerable: true,
  43187. configurable: true
  43188. });
  43189. ;
  43190. ;
  43191. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43192. /**
  43193. * The camera exposure used on this material.
  43194. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43195. * This corresponds to a photographic exposure.
  43196. */
  43197. get: function () {
  43198. return this._imageProcessingConfiguration.exposure;
  43199. },
  43200. /**
  43201. * The camera exposure used on this material.
  43202. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43203. * This corresponds to a photographic exposure.
  43204. */
  43205. set: function (value) {
  43206. this._imageProcessingConfiguration.exposure = value;
  43207. },
  43208. enumerable: true,
  43209. configurable: true
  43210. });
  43211. ;
  43212. ;
  43213. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43214. /**
  43215. * Gets The camera contrast used on this material.
  43216. */
  43217. get: function () {
  43218. return this._imageProcessingConfiguration.contrast;
  43219. },
  43220. /**
  43221. * Sets The camera contrast used on this material.
  43222. */
  43223. set: function (value) {
  43224. this._imageProcessingConfiguration.contrast = value;
  43225. },
  43226. enumerable: true,
  43227. configurable: true
  43228. });
  43229. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43230. /**
  43231. * Gets the Color Grading 2D Lookup Texture.
  43232. */
  43233. get: function () {
  43234. return this._imageProcessingConfiguration.colorGradingTexture;
  43235. },
  43236. /**
  43237. * Sets the Color Grading 2D Lookup Texture.
  43238. */
  43239. set: function (value) {
  43240. this._imageProcessingConfiguration.colorGradingTexture = value;
  43241. },
  43242. enumerable: true,
  43243. configurable: true
  43244. });
  43245. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43246. /**
  43247. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43248. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43249. * 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;
  43250. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43251. */
  43252. get: function () {
  43253. return this._imageProcessingConfiguration.colorCurves;
  43254. },
  43255. /**
  43256. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43257. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43258. * 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;
  43259. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43260. */
  43261. set: function (value) {
  43262. this._imageProcessingConfiguration.colorCurves = value;
  43263. },
  43264. enumerable: true,
  43265. configurable: true
  43266. });
  43267. Object.defineProperty(StandardMaterial.prototype, "hasRenderTargetTextures", {
  43268. /**
  43269. * Gets a boolean indicating that current material needs to register RTT
  43270. */
  43271. get: function () {
  43272. if (StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43273. return true;
  43274. }
  43275. if (StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43276. return true;
  43277. }
  43278. return false;
  43279. },
  43280. enumerable: true,
  43281. configurable: true
  43282. });
  43283. /**
  43284. * Gets the current class name of the material e.g. "StandardMaterial"
  43285. * Mainly use in serialization.
  43286. * @returns the class name
  43287. */
  43288. StandardMaterial.prototype.getClassName = function () {
  43289. return "StandardMaterial";
  43290. };
  43291. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43292. /**
  43293. * In case the depth buffer does not allow enough depth precision for your scene (might be the case in large scenes)
  43294. * You can try switching to logarithmic depth.
  43295. * @see http://doc.babylonjs.com/how_to/using_logarithmic_depth_buffer
  43296. */
  43297. get: function () {
  43298. return this._useLogarithmicDepth;
  43299. },
  43300. set: function (value) {
  43301. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43302. this._markAllSubMeshesAsMiscDirty();
  43303. },
  43304. enumerable: true,
  43305. configurable: true
  43306. });
  43307. /**
  43308. * Specifies if the material will require alpha blending
  43309. * @returns a boolean specifying if alpha blending is needed
  43310. */
  43311. StandardMaterial.prototype.needAlphaBlending = function () {
  43312. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43313. };
  43314. /**
  43315. * Specifies if this material should be rendered in alpha test mode
  43316. * @returns a boolean specifying if an alpha test is needed.
  43317. */
  43318. StandardMaterial.prototype.needAlphaTesting = function () {
  43319. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43320. };
  43321. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43322. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43323. };
  43324. /**
  43325. * Get the texture used for alpha test purpose.
  43326. * @returns the diffuse texture in case of the standard material.
  43327. */
  43328. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43329. return this._diffuseTexture;
  43330. };
  43331. /**
  43332. * Get if the submesh is ready to be used and all its information available.
  43333. * Child classes can use it to update shaders
  43334. * @param mesh defines the mesh to check
  43335. * @param subMesh defines which submesh to check
  43336. * @param useInstances specifies that instances should be used
  43337. * @returns a boolean indicating that the submesh is ready or not
  43338. */
  43339. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43340. if (useInstances === void 0) { useInstances = false; }
  43341. if (subMesh.effect && this.isFrozen) {
  43342. if (this._wasPreviouslyReady) {
  43343. return true;
  43344. }
  43345. }
  43346. if (!subMesh._materialDefines) {
  43347. subMesh._materialDefines = new StandardMaterialDefines();
  43348. }
  43349. var scene = this.getScene();
  43350. var defines = subMesh._materialDefines;
  43351. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43352. if (defines._renderId === scene.getRenderId()) {
  43353. return true;
  43354. }
  43355. }
  43356. var engine = scene.getEngine();
  43357. // Lights
  43358. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43359. // Textures
  43360. if (defines._areTexturesDirty) {
  43361. defines._needUVs = false;
  43362. defines.MAINUV1 = false;
  43363. defines.MAINUV2 = false;
  43364. if (scene.texturesEnabled) {
  43365. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43366. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43367. return false;
  43368. }
  43369. else {
  43370. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43371. }
  43372. }
  43373. else {
  43374. defines.DIFFUSE = false;
  43375. }
  43376. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43377. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43378. return false;
  43379. }
  43380. else {
  43381. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43382. }
  43383. }
  43384. else {
  43385. defines.AMBIENT = false;
  43386. }
  43387. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43388. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43389. return false;
  43390. }
  43391. else {
  43392. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43393. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43394. }
  43395. }
  43396. else {
  43397. defines.OPACITY = false;
  43398. }
  43399. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43400. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43401. return false;
  43402. }
  43403. else {
  43404. defines._needNormals = true;
  43405. defines.REFLECTION = true;
  43406. defines.ROUGHNESS = (this._roughness > 0);
  43407. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43408. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43409. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43410. switch (this._reflectionTexture.coordinatesMode) {
  43411. case BABYLON.Texture.EXPLICIT_MODE:
  43412. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43413. break;
  43414. case BABYLON.Texture.PLANAR_MODE:
  43415. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43416. break;
  43417. case BABYLON.Texture.PROJECTION_MODE:
  43418. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43419. break;
  43420. case BABYLON.Texture.SKYBOX_MODE:
  43421. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43422. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !this._reflectionTexture.getReflectionTextureMatrix().isIdentity();
  43423. break;
  43424. case BABYLON.Texture.SPHERICAL_MODE:
  43425. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43426. break;
  43427. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43428. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43429. break;
  43430. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43431. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43432. break;
  43433. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43434. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43435. break;
  43436. case BABYLON.Texture.CUBIC_MODE:
  43437. case BABYLON.Texture.INVCUBIC_MODE:
  43438. default:
  43439. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43440. break;
  43441. }
  43442. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43443. }
  43444. }
  43445. else {
  43446. defines.REFLECTION = false;
  43447. }
  43448. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43449. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43450. return false;
  43451. }
  43452. else {
  43453. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43454. }
  43455. }
  43456. else {
  43457. defines.EMISSIVE = false;
  43458. }
  43459. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43460. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43461. return false;
  43462. }
  43463. else {
  43464. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43465. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43466. }
  43467. }
  43468. else {
  43469. defines.LIGHTMAP = false;
  43470. }
  43471. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43472. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43473. return false;
  43474. }
  43475. else {
  43476. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43477. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43478. }
  43479. }
  43480. else {
  43481. defines.SPECULAR = false;
  43482. }
  43483. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43484. // Bump texure can not be not blocking.
  43485. if (!this._bumpTexture.isReady()) {
  43486. return false;
  43487. }
  43488. else {
  43489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43490. defines.PARALLAX = this._useParallax;
  43491. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43492. }
  43493. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43494. }
  43495. else {
  43496. defines.BUMP = false;
  43497. }
  43498. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43499. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43500. return false;
  43501. }
  43502. else {
  43503. defines._needUVs = true;
  43504. defines.REFRACTION = true;
  43505. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43506. }
  43507. }
  43508. else {
  43509. defines.REFRACTION = false;
  43510. }
  43511. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43512. }
  43513. else {
  43514. defines.DIFFUSE = false;
  43515. defines.AMBIENT = false;
  43516. defines.OPACITY = false;
  43517. defines.REFLECTION = false;
  43518. defines.EMISSIVE = false;
  43519. defines.LIGHTMAP = false;
  43520. defines.BUMP = false;
  43521. defines.REFRACTION = false;
  43522. }
  43523. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43524. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43525. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43526. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43527. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43528. }
  43529. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  43530. if (!this._imageProcessingConfiguration.isReady()) {
  43531. return false;
  43532. }
  43533. this._imageProcessingConfiguration.prepareDefines(defines);
  43534. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43535. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43536. }
  43537. if (defines._areFresnelDirty) {
  43538. if (StandardMaterial.FresnelEnabled) {
  43539. // Fresnel
  43540. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43541. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43542. this._reflectionFresnelParameters) {
  43543. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43544. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43545. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43546. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43547. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43548. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43549. defines._needNormals = true;
  43550. defines.FRESNEL = true;
  43551. }
  43552. }
  43553. else {
  43554. defines.FRESNEL = false;
  43555. }
  43556. }
  43557. // Misc.
  43558. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43559. // Attribs
  43560. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43561. // Values that need to be evaluated on every frame
  43562. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43563. // Get correct effect
  43564. if (defines.isDirty) {
  43565. defines.markAsProcessed();
  43566. scene.resetCachedMaterial();
  43567. // Fallbacks
  43568. var fallbacks = new BABYLON.EffectFallbacks();
  43569. if (defines.REFLECTION) {
  43570. fallbacks.addFallback(0, "REFLECTION");
  43571. }
  43572. if (defines.SPECULAR) {
  43573. fallbacks.addFallback(0, "SPECULAR");
  43574. }
  43575. if (defines.BUMP) {
  43576. fallbacks.addFallback(0, "BUMP");
  43577. }
  43578. if (defines.PARALLAX) {
  43579. fallbacks.addFallback(1, "PARALLAX");
  43580. }
  43581. if (defines.PARALLAXOCCLUSION) {
  43582. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43583. }
  43584. if (defines.SPECULAROVERALPHA) {
  43585. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43586. }
  43587. if (defines.FOG) {
  43588. fallbacks.addFallback(1, "FOG");
  43589. }
  43590. if (defines.POINTSIZE) {
  43591. fallbacks.addFallback(0, "POINTSIZE");
  43592. }
  43593. if (defines.LOGARITHMICDEPTH) {
  43594. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43595. }
  43596. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43597. if (defines.SPECULARTERM) {
  43598. fallbacks.addFallback(0, "SPECULARTERM");
  43599. }
  43600. if (defines.DIFFUSEFRESNEL) {
  43601. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43602. }
  43603. if (defines.OPACITYFRESNEL) {
  43604. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43605. }
  43606. if (defines.REFLECTIONFRESNEL) {
  43607. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43608. }
  43609. if (defines.EMISSIVEFRESNEL) {
  43610. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43611. }
  43612. if (defines.FRESNEL) {
  43613. fallbacks.addFallback(4, "FRESNEL");
  43614. }
  43615. //Attributes
  43616. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43617. if (defines.NORMAL) {
  43618. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43619. }
  43620. if (defines.UV1) {
  43621. attribs.push(BABYLON.VertexBuffer.UVKind);
  43622. }
  43623. if (defines.UV2) {
  43624. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43625. }
  43626. if (defines.VERTEXCOLOR) {
  43627. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43628. }
  43629. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43630. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43631. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43632. var shaderName = "default";
  43633. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43634. "vFogInfos", "vFogColor", "pointSize",
  43635. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43636. "mBones",
  43637. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43638. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43639. "vReflectionPosition", "vReflectionSize",
  43640. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43641. ];
  43642. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43643. var uniformBuffers = ["Material", "Scene"];
  43644. if (BABYLON.ImageProcessingConfiguration) {
  43645. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43646. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43647. }
  43648. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43649. uniformsNames: uniforms,
  43650. uniformBuffersNames: uniformBuffers,
  43651. samplers: samplers,
  43652. defines: defines,
  43653. maxSimultaneousLights: this._maxSimultaneousLights
  43654. });
  43655. if (this.customShaderNameResolve) {
  43656. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43657. }
  43658. var join = defines.toString();
  43659. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43660. attributes: attribs,
  43661. uniformsNames: uniforms,
  43662. uniformBuffersNames: uniformBuffers,
  43663. samplers: samplers,
  43664. defines: join,
  43665. fallbacks: fallbacks,
  43666. onCompiled: this.onCompiled,
  43667. onError: this.onError,
  43668. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43669. }, engine), defines);
  43670. this.buildUniformLayout();
  43671. }
  43672. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43673. return false;
  43674. }
  43675. defines._renderId = scene.getRenderId();
  43676. this._wasPreviouslyReady = true;
  43677. return true;
  43678. };
  43679. /**
  43680. * Builds the material UBO layouts.
  43681. * Used internally during the effect preparation.
  43682. */
  43683. StandardMaterial.prototype.buildUniformLayout = function () {
  43684. // Order is important !
  43685. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43686. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43687. this._uniformBuffer.addUniform("opacityParts", 4);
  43688. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43689. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43690. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43691. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43692. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43693. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43694. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43695. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43696. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43697. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43698. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43699. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43700. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43701. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43702. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43703. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43704. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43705. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43706. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43707. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43708. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43709. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43710. this._uniformBuffer.addUniform("specularMatrix", 16);
  43711. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43712. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43713. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43714. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43715. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43716. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43717. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43718. this._uniformBuffer.addUniform("pointSize", 1);
  43719. this._uniformBuffer.create();
  43720. };
  43721. /**
  43722. * Unbinds the material from the mesh
  43723. */
  43724. StandardMaterial.prototype.unbind = function () {
  43725. if (this._activeEffect) {
  43726. var needFlag = false;
  43727. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43728. this._activeEffect.setTexture("reflection2DSampler", null);
  43729. needFlag = true;
  43730. }
  43731. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43732. this._activeEffect.setTexture("refraction2DSampler", null);
  43733. needFlag = true;
  43734. }
  43735. if (needFlag) {
  43736. this._markAllSubMeshesAsTexturesDirty();
  43737. }
  43738. }
  43739. _super.prototype.unbind.call(this);
  43740. };
  43741. /**
  43742. * Binds the submesh to this material by preparing the effect and shader to draw
  43743. * @param world defines the world transformation matrix
  43744. * @param mesh defines the mesh containing the submesh
  43745. * @param subMesh defines the submesh to bind the material to
  43746. */
  43747. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43748. var scene = this.getScene();
  43749. var defines = subMesh._materialDefines;
  43750. if (!defines) {
  43751. return;
  43752. }
  43753. var effect = subMesh.effect;
  43754. if (!effect) {
  43755. return;
  43756. }
  43757. this._activeEffect = effect;
  43758. // Matrices
  43759. this.bindOnlyWorldMatrix(world);
  43760. // Normal Matrix
  43761. if (defines.OBJECTSPACE_NORMALMAP) {
  43762. world.toNormalMatrix(this._normalMatrix);
  43763. this.bindOnlyNormalMatrix(this._normalMatrix);
  43764. }
  43765. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43766. // Bones
  43767. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43768. if (mustRebind) {
  43769. this._uniformBuffer.bindToEffect(effect, "Material");
  43770. this.bindViewProjection(effect);
  43771. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43772. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43773. // Fresnel
  43774. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43775. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43776. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43777. }
  43778. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43779. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43780. }
  43781. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43782. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43783. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43784. }
  43785. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43786. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43787. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43788. }
  43789. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43790. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43791. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43792. }
  43793. }
  43794. // Textures
  43795. if (scene.texturesEnabled) {
  43796. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43797. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43798. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43799. if (this._diffuseTexture.hasAlpha) {
  43800. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43801. }
  43802. }
  43803. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43804. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43805. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43806. }
  43807. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43808. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43809. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43810. }
  43811. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43812. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43813. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43814. if (this._reflectionTexture.boundingBoxSize) {
  43815. var cubeTexture = this._reflectionTexture;
  43816. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43817. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43818. }
  43819. }
  43820. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43821. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43822. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43823. }
  43824. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43825. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43826. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43827. }
  43828. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43829. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43830. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43831. }
  43832. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43833. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43834. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43835. if (scene._mirroredCameraPosition) {
  43836. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43837. }
  43838. else {
  43839. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43840. }
  43841. }
  43842. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43843. var depth = 1.0;
  43844. if (!this._refractionTexture.isCube) {
  43845. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43846. if (this._refractionTexture.depth) {
  43847. depth = this._refractionTexture.depth;
  43848. }
  43849. }
  43850. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43851. }
  43852. }
  43853. // Point size
  43854. if (this.pointsCloud) {
  43855. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43856. }
  43857. if (defines.SPECULARTERM) {
  43858. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43859. }
  43860. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43861. // Diffuse
  43862. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43863. }
  43864. // Textures
  43865. if (scene.texturesEnabled) {
  43866. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43867. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43868. }
  43869. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43870. effect.setTexture("ambientSampler", this._ambientTexture);
  43871. }
  43872. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43873. effect.setTexture("opacitySampler", this._opacityTexture);
  43874. }
  43875. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43876. if (this._reflectionTexture.isCube) {
  43877. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43878. }
  43879. else {
  43880. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43881. }
  43882. }
  43883. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43884. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43885. }
  43886. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43887. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43888. }
  43889. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43890. effect.setTexture("specularSampler", this._specularTexture);
  43891. }
  43892. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43893. effect.setTexture("bumpSampler", this._bumpTexture);
  43894. }
  43895. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43896. var depth = 1.0;
  43897. if (this._refractionTexture.isCube) {
  43898. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43899. }
  43900. else {
  43901. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43902. }
  43903. }
  43904. }
  43905. // Clip plane
  43906. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43907. // Colors
  43908. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43909. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43910. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43911. }
  43912. if (mustRebind || !this.isFrozen) {
  43913. // Lights
  43914. if (scene.lightsEnabled && !this._disableLighting) {
  43915. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43916. }
  43917. // View
  43918. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43919. this.bindView(effect);
  43920. }
  43921. // Fog
  43922. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43923. // Morph targets
  43924. if (defines.NUM_MORPH_INFLUENCERS) {
  43925. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43926. }
  43927. // Log. depth
  43928. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43929. // image processing
  43930. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  43931. this._imageProcessingConfiguration.bind(this._activeEffect);
  43932. }
  43933. }
  43934. this._uniformBuffer.update();
  43935. this._afterBind(mesh, this._activeEffect);
  43936. };
  43937. /**
  43938. * Get the list of animatables in the material.
  43939. * @returns the list of animatables object used in the material
  43940. */
  43941. StandardMaterial.prototype.getAnimatables = function () {
  43942. var results = [];
  43943. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43944. results.push(this._diffuseTexture);
  43945. }
  43946. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43947. results.push(this._ambientTexture);
  43948. }
  43949. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43950. results.push(this._opacityTexture);
  43951. }
  43952. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43953. results.push(this._reflectionTexture);
  43954. }
  43955. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43956. results.push(this._emissiveTexture);
  43957. }
  43958. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43959. results.push(this._specularTexture);
  43960. }
  43961. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43962. results.push(this._bumpTexture);
  43963. }
  43964. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43965. results.push(this._lightmapTexture);
  43966. }
  43967. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43968. results.push(this._refractionTexture);
  43969. }
  43970. return results;
  43971. };
  43972. /**
  43973. * Gets the active textures from the material
  43974. * @returns an array of textures
  43975. */
  43976. StandardMaterial.prototype.getActiveTextures = function () {
  43977. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43978. if (this._diffuseTexture) {
  43979. activeTextures.push(this._diffuseTexture);
  43980. }
  43981. if (this._ambientTexture) {
  43982. activeTextures.push(this._ambientTexture);
  43983. }
  43984. if (this._opacityTexture) {
  43985. activeTextures.push(this._opacityTexture);
  43986. }
  43987. if (this._reflectionTexture) {
  43988. activeTextures.push(this._reflectionTexture);
  43989. }
  43990. if (this._emissiveTexture) {
  43991. activeTextures.push(this._emissiveTexture);
  43992. }
  43993. if (this._specularTexture) {
  43994. activeTextures.push(this._specularTexture);
  43995. }
  43996. if (this._bumpTexture) {
  43997. activeTextures.push(this._bumpTexture);
  43998. }
  43999. if (this._lightmapTexture) {
  44000. activeTextures.push(this._lightmapTexture);
  44001. }
  44002. if (this._refractionTexture) {
  44003. activeTextures.push(this._refractionTexture);
  44004. }
  44005. return activeTextures;
  44006. };
  44007. /**
  44008. * Specifies if the material uses a texture
  44009. * @param texture defines the texture to check against the material
  44010. * @returns a boolean specifying if the material uses the texture
  44011. */
  44012. StandardMaterial.prototype.hasTexture = function (texture) {
  44013. if (_super.prototype.hasTexture.call(this, texture)) {
  44014. return true;
  44015. }
  44016. if (this._diffuseTexture === texture) {
  44017. return true;
  44018. }
  44019. if (this._ambientTexture === texture) {
  44020. return true;
  44021. }
  44022. if (this._opacityTexture === texture) {
  44023. return true;
  44024. }
  44025. if (this._reflectionTexture === texture) {
  44026. return true;
  44027. }
  44028. if (this._emissiveTexture === texture) {
  44029. return true;
  44030. }
  44031. if (this._specularTexture === texture) {
  44032. return true;
  44033. }
  44034. if (this._bumpTexture === texture) {
  44035. return true;
  44036. }
  44037. if (this._lightmapTexture === texture) {
  44038. return true;
  44039. }
  44040. if (this._refractionTexture === texture) {
  44041. return true;
  44042. }
  44043. return false;
  44044. };
  44045. /**
  44046. * Disposes the material
  44047. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  44048. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  44049. */
  44050. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44051. if (forceDisposeTextures) {
  44052. if (this._diffuseTexture) {
  44053. this._diffuseTexture.dispose();
  44054. }
  44055. if (this._ambientTexture) {
  44056. this._ambientTexture.dispose();
  44057. }
  44058. if (this._opacityTexture) {
  44059. this._opacityTexture.dispose();
  44060. }
  44061. if (this._reflectionTexture) {
  44062. this._reflectionTexture.dispose();
  44063. }
  44064. if (this._emissiveTexture) {
  44065. this._emissiveTexture.dispose();
  44066. }
  44067. if (this._specularTexture) {
  44068. this._specularTexture.dispose();
  44069. }
  44070. if (this._bumpTexture) {
  44071. this._bumpTexture.dispose();
  44072. }
  44073. if (this._lightmapTexture) {
  44074. this._lightmapTexture.dispose();
  44075. }
  44076. if (this._refractionTexture) {
  44077. this._refractionTexture.dispose();
  44078. }
  44079. }
  44080. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44081. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44082. }
  44083. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44084. };
  44085. /**
  44086. * Makes a duplicate of the material, and gives it a new name
  44087. * @param name defines the new name for the duplicated material
  44088. * @returns the cloned material
  44089. */
  44090. StandardMaterial.prototype.clone = function (name) {
  44091. var _this = this;
  44092. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  44093. result.name = name;
  44094. result.id = name;
  44095. return result;
  44096. };
  44097. /**
  44098. * Serializes this material in a JSON representation
  44099. * @returns the serialized material object
  44100. */
  44101. StandardMaterial.prototype.serialize = function () {
  44102. return BABYLON.SerializationHelper.Serialize(this);
  44103. };
  44104. /**
  44105. * Creates a standard material from parsed material data
  44106. * @param source defines the JSON represnetation of the material
  44107. * @param scene defines the hosting scene
  44108. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  44109. * @returns a new material
  44110. */
  44111. StandardMaterial.Parse = function (source, scene, rootUrl) {
  44112. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  44113. };
  44114. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  44115. /**
  44116. * Are diffuse textures enabled in the application.
  44117. */
  44118. get: function () {
  44119. return StandardMaterial._DiffuseTextureEnabled;
  44120. },
  44121. set: function (value) {
  44122. if (StandardMaterial._DiffuseTextureEnabled === value) {
  44123. return;
  44124. }
  44125. StandardMaterial._DiffuseTextureEnabled = value;
  44126. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44127. },
  44128. enumerable: true,
  44129. configurable: true
  44130. });
  44131. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  44132. /**
  44133. * Are ambient textures enabled in the application.
  44134. */
  44135. get: function () {
  44136. return StandardMaterial._AmbientTextureEnabled;
  44137. },
  44138. set: function (value) {
  44139. if (StandardMaterial._AmbientTextureEnabled === value) {
  44140. return;
  44141. }
  44142. StandardMaterial._AmbientTextureEnabled = value;
  44143. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44144. },
  44145. enumerable: true,
  44146. configurable: true
  44147. });
  44148. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  44149. /**
  44150. * Are opacity textures enabled in the application.
  44151. */
  44152. get: function () {
  44153. return StandardMaterial._OpacityTextureEnabled;
  44154. },
  44155. set: function (value) {
  44156. if (StandardMaterial._OpacityTextureEnabled === value) {
  44157. return;
  44158. }
  44159. StandardMaterial._OpacityTextureEnabled = value;
  44160. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44161. },
  44162. enumerable: true,
  44163. configurable: true
  44164. });
  44165. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  44166. /**
  44167. * Are reflection textures enabled in the application.
  44168. */
  44169. get: function () {
  44170. return StandardMaterial._ReflectionTextureEnabled;
  44171. },
  44172. set: function (value) {
  44173. if (StandardMaterial._ReflectionTextureEnabled === value) {
  44174. return;
  44175. }
  44176. StandardMaterial._ReflectionTextureEnabled = value;
  44177. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44178. },
  44179. enumerable: true,
  44180. configurable: true
  44181. });
  44182. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  44183. /**
  44184. * Are emissive textures enabled in the application.
  44185. */
  44186. get: function () {
  44187. return StandardMaterial._EmissiveTextureEnabled;
  44188. },
  44189. set: function (value) {
  44190. if (StandardMaterial._EmissiveTextureEnabled === value) {
  44191. return;
  44192. }
  44193. StandardMaterial._EmissiveTextureEnabled = value;
  44194. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44195. },
  44196. enumerable: true,
  44197. configurable: true
  44198. });
  44199. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44200. /**
  44201. * Are specular textures enabled in the application.
  44202. */
  44203. get: function () {
  44204. return StandardMaterial._SpecularTextureEnabled;
  44205. },
  44206. set: function (value) {
  44207. if (StandardMaterial._SpecularTextureEnabled === value) {
  44208. return;
  44209. }
  44210. StandardMaterial._SpecularTextureEnabled = value;
  44211. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44212. },
  44213. enumerable: true,
  44214. configurable: true
  44215. });
  44216. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44217. /**
  44218. * Are bump textures enabled in the application.
  44219. */
  44220. get: function () {
  44221. return StandardMaterial._BumpTextureEnabled;
  44222. },
  44223. set: function (value) {
  44224. if (StandardMaterial._BumpTextureEnabled === value) {
  44225. return;
  44226. }
  44227. StandardMaterial._BumpTextureEnabled = value;
  44228. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44229. },
  44230. enumerable: true,
  44231. configurable: true
  44232. });
  44233. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44234. /**
  44235. * Are lightmap textures enabled in the application.
  44236. */
  44237. get: function () {
  44238. return StandardMaterial._LightmapTextureEnabled;
  44239. },
  44240. set: function (value) {
  44241. if (StandardMaterial._LightmapTextureEnabled === value) {
  44242. return;
  44243. }
  44244. StandardMaterial._LightmapTextureEnabled = value;
  44245. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44246. },
  44247. enumerable: true,
  44248. configurable: true
  44249. });
  44250. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44251. /**
  44252. * Are refraction textures enabled in the application.
  44253. */
  44254. get: function () {
  44255. return StandardMaterial._RefractionTextureEnabled;
  44256. },
  44257. set: function (value) {
  44258. if (StandardMaterial._RefractionTextureEnabled === value) {
  44259. return;
  44260. }
  44261. StandardMaterial._RefractionTextureEnabled = value;
  44262. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44263. },
  44264. enumerable: true,
  44265. configurable: true
  44266. });
  44267. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44268. /**
  44269. * Are color grading textures enabled in the application.
  44270. */
  44271. get: function () {
  44272. return StandardMaterial._ColorGradingTextureEnabled;
  44273. },
  44274. set: function (value) {
  44275. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44276. return;
  44277. }
  44278. StandardMaterial._ColorGradingTextureEnabled = value;
  44279. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44280. },
  44281. enumerable: true,
  44282. configurable: true
  44283. });
  44284. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44285. /**
  44286. * Are fresnels enabled in the application.
  44287. */
  44288. get: function () {
  44289. return StandardMaterial._FresnelEnabled;
  44290. },
  44291. set: function (value) {
  44292. if (StandardMaterial._FresnelEnabled === value) {
  44293. return;
  44294. }
  44295. StandardMaterial._FresnelEnabled = value;
  44296. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44297. },
  44298. enumerable: true,
  44299. configurable: true
  44300. });
  44301. // Flags used to enable or disable a type of texture for all Standard Materials
  44302. StandardMaterial._DiffuseTextureEnabled = true;
  44303. StandardMaterial._AmbientTextureEnabled = true;
  44304. StandardMaterial._OpacityTextureEnabled = true;
  44305. StandardMaterial._ReflectionTextureEnabled = true;
  44306. StandardMaterial._EmissiveTextureEnabled = true;
  44307. StandardMaterial._SpecularTextureEnabled = true;
  44308. StandardMaterial._BumpTextureEnabled = true;
  44309. StandardMaterial._LightmapTextureEnabled = true;
  44310. StandardMaterial._RefractionTextureEnabled = true;
  44311. StandardMaterial._ColorGradingTextureEnabled = true;
  44312. StandardMaterial._FresnelEnabled = true;
  44313. __decorate([
  44314. BABYLON.serializeAsTexture("diffuseTexture")
  44315. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44316. __decorate([
  44317. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44318. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44319. __decorate([
  44320. BABYLON.serializeAsTexture("ambientTexture")
  44321. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44322. __decorate([
  44323. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44324. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44325. __decorate([
  44326. BABYLON.serializeAsTexture("opacityTexture")
  44327. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44328. __decorate([
  44329. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44330. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44331. __decorate([
  44332. BABYLON.serializeAsTexture("reflectionTexture")
  44333. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44334. __decorate([
  44335. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44336. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44337. __decorate([
  44338. BABYLON.serializeAsTexture("emissiveTexture")
  44339. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44340. __decorate([
  44341. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44342. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44343. __decorate([
  44344. BABYLON.serializeAsTexture("specularTexture")
  44345. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44346. __decorate([
  44347. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44348. ], StandardMaterial.prototype, "specularTexture", void 0);
  44349. __decorate([
  44350. BABYLON.serializeAsTexture("bumpTexture")
  44351. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44352. __decorate([
  44353. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44354. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44355. __decorate([
  44356. BABYLON.serializeAsTexture("lightmapTexture")
  44357. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44358. __decorate([
  44359. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44360. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44361. __decorate([
  44362. BABYLON.serializeAsTexture("refractionTexture")
  44363. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44364. __decorate([
  44365. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44366. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44367. __decorate([
  44368. BABYLON.serializeAsColor3("ambient")
  44369. ], StandardMaterial.prototype, "ambientColor", void 0);
  44370. __decorate([
  44371. BABYLON.serializeAsColor3("diffuse")
  44372. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44373. __decorate([
  44374. BABYLON.serializeAsColor3("specular")
  44375. ], StandardMaterial.prototype, "specularColor", void 0);
  44376. __decorate([
  44377. BABYLON.serializeAsColor3("emissive")
  44378. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44379. __decorate([
  44380. BABYLON.serialize()
  44381. ], StandardMaterial.prototype, "specularPower", void 0);
  44382. __decorate([
  44383. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44384. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44385. __decorate([
  44386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44387. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44388. __decorate([
  44389. BABYLON.serialize("useEmissiveAsIllumination")
  44390. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44391. __decorate([
  44392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44393. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44394. __decorate([
  44395. BABYLON.serialize("linkEmissiveWithDiffuse")
  44396. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44397. __decorate([
  44398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44399. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44400. __decorate([
  44401. BABYLON.serialize("useSpecularOverAlpha")
  44402. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44403. __decorate([
  44404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44405. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44406. __decorate([
  44407. BABYLON.serialize("useReflectionOverAlpha")
  44408. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44409. __decorate([
  44410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44411. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44412. __decorate([
  44413. BABYLON.serialize("disableLighting")
  44414. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44415. __decorate([
  44416. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44417. ], StandardMaterial.prototype, "disableLighting", void 0);
  44418. __decorate([
  44419. BABYLON.serialize("useObjectSpaceNormalMap")
  44420. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44421. __decorate([
  44422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44423. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44424. __decorate([
  44425. BABYLON.serialize("useParallax")
  44426. ], StandardMaterial.prototype, "_useParallax", void 0);
  44427. __decorate([
  44428. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44429. ], StandardMaterial.prototype, "useParallax", void 0);
  44430. __decorate([
  44431. BABYLON.serialize("useParallaxOcclusion")
  44432. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44433. __decorate([
  44434. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44435. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44436. __decorate([
  44437. BABYLON.serialize()
  44438. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44439. __decorate([
  44440. BABYLON.serialize("roughness")
  44441. ], StandardMaterial.prototype, "_roughness", void 0);
  44442. __decorate([
  44443. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44444. ], StandardMaterial.prototype, "roughness", void 0);
  44445. __decorate([
  44446. BABYLON.serialize()
  44447. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44448. __decorate([
  44449. BABYLON.serialize()
  44450. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44451. __decorate([
  44452. BABYLON.serialize()
  44453. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44454. __decorate([
  44455. BABYLON.serialize("useLightmapAsShadowmap")
  44456. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44457. __decorate([
  44458. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44459. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44460. __decorate([
  44461. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44462. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44463. __decorate([
  44464. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44465. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44466. __decorate([
  44467. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44468. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44469. __decorate([
  44470. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44471. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44472. __decorate([
  44473. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44474. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44475. __decorate([
  44476. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44477. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44478. __decorate([
  44479. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44480. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44481. __decorate([
  44482. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44483. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44484. __decorate([
  44485. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44486. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44487. __decorate([
  44488. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44489. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44490. __decorate([
  44491. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44492. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44493. __decorate([
  44494. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44495. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44496. __decorate([
  44497. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44498. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44499. __decorate([
  44500. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44501. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44502. __decorate([
  44503. BABYLON.serialize("maxSimultaneousLights")
  44504. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44505. __decorate([
  44506. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44507. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44508. __decorate([
  44509. BABYLON.serialize("invertNormalMapX")
  44510. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44511. __decorate([
  44512. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44513. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44514. __decorate([
  44515. BABYLON.serialize("invertNormalMapY")
  44516. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44517. __decorate([
  44518. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44519. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44520. __decorate([
  44521. BABYLON.serialize("twoSidedLighting")
  44522. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44523. __decorate([
  44524. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44525. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44526. __decorate([
  44527. BABYLON.serialize()
  44528. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44529. return StandardMaterial;
  44530. }(BABYLON.PushMaterial));
  44531. BABYLON.StandardMaterial = StandardMaterial;
  44532. })(BABYLON || (BABYLON = {}));
  44533. //# sourceMappingURL=babylon.standardMaterial.js.map
  44534. var BABYLON;
  44535. (function (BABYLON) {
  44536. /**
  44537. * Class representing spherical polynomial coefficients to the 3rd degree
  44538. */
  44539. var SphericalPolynomial = /** @class */ (function () {
  44540. function SphericalPolynomial() {
  44541. /**
  44542. * The x coefficients of the spherical polynomial
  44543. */
  44544. this.x = BABYLON.Vector3.Zero();
  44545. /**
  44546. * The y coefficients of the spherical polynomial
  44547. */
  44548. this.y = BABYLON.Vector3.Zero();
  44549. /**
  44550. * The z coefficients of the spherical polynomial
  44551. */
  44552. this.z = BABYLON.Vector3.Zero();
  44553. /**
  44554. * The xx coefficients of the spherical polynomial
  44555. */
  44556. this.xx = BABYLON.Vector3.Zero();
  44557. /**
  44558. * The yy coefficients of the spherical polynomial
  44559. */
  44560. this.yy = BABYLON.Vector3.Zero();
  44561. /**
  44562. * The zz coefficients of the spherical polynomial
  44563. */
  44564. this.zz = BABYLON.Vector3.Zero();
  44565. /**
  44566. * The xy coefficients of the spherical polynomial
  44567. */
  44568. this.xy = BABYLON.Vector3.Zero();
  44569. /**
  44570. * The yz coefficients of the spherical polynomial
  44571. */
  44572. this.yz = BABYLON.Vector3.Zero();
  44573. /**
  44574. * The zx coefficients of the spherical polynomial
  44575. */
  44576. this.zx = BABYLON.Vector3.Zero();
  44577. }
  44578. /**
  44579. * Adds an ambient color to the spherical polynomial
  44580. * @param color the color to add
  44581. */
  44582. SphericalPolynomial.prototype.addAmbient = function (color) {
  44583. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44584. this.xx = this.xx.add(colorVector);
  44585. this.yy = this.yy.add(colorVector);
  44586. this.zz = this.zz.add(colorVector);
  44587. };
  44588. /**
  44589. * Scales the spherical polynomial by the given amount
  44590. * @param scale the amount to scale
  44591. */
  44592. SphericalPolynomial.prototype.scale = function (scale) {
  44593. this.x = this.x.scale(scale);
  44594. this.y = this.y.scale(scale);
  44595. this.z = this.z.scale(scale);
  44596. this.xx = this.xx.scale(scale);
  44597. this.yy = this.yy.scale(scale);
  44598. this.zz = this.zz.scale(scale);
  44599. this.yz = this.yz.scale(scale);
  44600. this.zx = this.zx.scale(scale);
  44601. this.xy = this.xy.scale(scale);
  44602. };
  44603. /**
  44604. * Gets the spherical polynomial from harmonics
  44605. * @param harmonics the spherical harmonics
  44606. * @returns the spherical polynomial
  44607. */
  44608. SphericalPolynomial.FromHarmonics = function (harmonics) {
  44609. var result = new SphericalPolynomial();
  44610. result.x = harmonics.l11.scale(1.02333);
  44611. result.y = harmonics.l1_1.scale(1.02333);
  44612. result.z = harmonics.l10.scale(1.02333);
  44613. result.xx = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).add(harmonics.lL22.scale(0.429043));
  44614. result.yy = harmonics.l00.scale(0.886277).subtract(harmonics.l20.scale(0.247708)).subtract(harmonics.lL22.scale(0.429043));
  44615. result.zz = harmonics.l00.scale(0.886277).add(harmonics.l20.scale(0.495417));
  44616. result.yz = harmonics.l2_1.scale(0.858086);
  44617. result.zx = harmonics.l21.scale(0.858086);
  44618. result.xy = harmonics.l2_2.scale(0.858086);
  44619. result.scale(1.0 / Math.PI);
  44620. return result;
  44621. };
  44622. /**
  44623. * Constructs a spherical polynomial from an array.
  44624. * @param data defines the 9x3 coefficients (x, y, z, xx, yy, zz, yz, zx, xy)
  44625. * @returns the spherical polynomial
  44626. */
  44627. SphericalPolynomial.FromArray = function (data) {
  44628. var sp = new SphericalPolynomial();
  44629. BABYLON.Vector3.FromArrayToRef(data[0], 0, sp.x);
  44630. BABYLON.Vector3.FromArrayToRef(data[1], 0, sp.y);
  44631. BABYLON.Vector3.FromArrayToRef(data[2], 0, sp.z);
  44632. BABYLON.Vector3.FromArrayToRef(data[3], 0, sp.xx);
  44633. BABYLON.Vector3.FromArrayToRef(data[4], 0, sp.yy);
  44634. BABYLON.Vector3.FromArrayToRef(data[5], 0, sp.zz);
  44635. BABYLON.Vector3.FromArrayToRef(data[6], 0, sp.yz);
  44636. BABYLON.Vector3.FromArrayToRef(data[7], 0, sp.zx);
  44637. BABYLON.Vector3.FromArrayToRef(data[8], 0, sp.xy);
  44638. return sp;
  44639. };
  44640. return SphericalPolynomial;
  44641. }());
  44642. BABYLON.SphericalPolynomial = SphericalPolynomial;
  44643. /**
  44644. * Class representing spherical harmonics coefficients to the 3rd degree
  44645. */
  44646. var SphericalHarmonics = /** @class */ (function () {
  44647. function SphericalHarmonics() {
  44648. /**
  44649. * The l0,0 coefficients of the spherical harmonics
  44650. */
  44651. this.l00 = BABYLON.Vector3.Zero();
  44652. /**
  44653. * The l1,-1 coefficients of the spherical harmonics
  44654. */
  44655. this.l1_1 = BABYLON.Vector3.Zero();
  44656. /**
  44657. * The l1,0 coefficients of the spherical harmonics
  44658. */
  44659. this.l10 = BABYLON.Vector3.Zero();
  44660. /**
  44661. * The l1,1 coefficients of the spherical harmonics
  44662. */
  44663. this.l11 = BABYLON.Vector3.Zero();
  44664. /**
  44665. * The l2,-2 coefficients of the spherical harmonics
  44666. */
  44667. this.l2_2 = BABYLON.Vector3.Zero();
  44668. /**
  44669. * The l2,-1 coefficients of the spherical harmonics
  44670. */
  44671. this.l2_1 = BABYLON.Vector3.Zero();
  44672. /**
  44673. * The l2,0 coefficients of the spherical harmonics
  44674. */
  44675. this.l20 = BABYLON.Vector3.Zero();
  44676. /**
  44677. * The l2,1 coefficients of the spherical harmonics
  44678. */
  44679. this.l21 = BABYLON.Vector3.Zero();
  44680. /**
  44681. * The l2,2 coefficients of the spherical harmonics
  44682. */
  44683. this.lL22 = BABYLON.Vector3.Zero();
  44684. }
  44685. /**
  44686. * Adds a light to the spherical harmonics
  44687. * @param direction the direction of the light
  44688. * @param color the color of the light
  44689. * @param deltaSolidAngle the delta solid angle of the light
  44690. */
  44691. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  44692. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  44693. var c = colorVector.scale(deltaSolidAngle);
  44694. this.l00 = this.l00.add(c.scale(0.282095));
  44695. this.l1_1 = this.l1_1.add(c.scale(0.488603 * direction.y));
  44696. this.l10 = this.l10.add(c.scale(0.488603 * direction.z));
  44697. this.l11 = this.l11.add(c.scale(0.488603 * direction.x));
  44698. this.l2_2 = this.l2_2.add(c.scale(1.092548 * direction.x * direction.y));
  44699. this.l2_1 = this.l2_1.add(c.scale(1.092548 * direction.y * direction.z));
  44700. this.l21 = this.l21.add(c.scale(1.092548 * direction.x * direction.z));
  44701. this.l20 = this.l20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  44702. this.lL22 = this.lL22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  44703. };
  44704. /**
  44705. * Scales the spherical harmonics by the given amount
  44706. * @param scale the amount to scale
  44707. */
  44708. SphericalHarmonics.prototype.scale = function (scale) {
  44709. this.l00 = this.l00.scale(scale);
  44710. this.l1_1 = this.l1_1.scale(scale);
  44711. this.l10 = this.l10.scale(scale);
  44712. this.l11 = this.l11.scale(scale);
  44713. this.l2_2 = this.l2_2.scale(scale);
  44714. this.l2_1 = this.l2_1.scale(scale);
  44715. this.l20 = this.l20.scale(scale);
  44716. this.l21 = this.l21.scale(scale);
  44717. this.lL22 = this.lL22.scale(scale);
  44718. };
  44719. /**
  44720. * Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  44721. *
  44722. * ```
  44723. * E_lm = A_l * L_lm
  44724. * ```
  44725. *
  44726. * In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  44727. * This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  44728. * the scaling factors are given in equation 9.
  44729. */
  44730. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  44731. // Constant (Band 0)
  44732. this.l00 = this.l00.scale(3.141593);
  44733. // Linear (Band 1)
  44734. this.l1_1 = this.l1_1.scale(2.094395);
  44735. this.l10 = this.l10.scale(2.094395);
  44736. this.l11 = this.l11.scale(2.094395);
  44737. // Quadratic (Band 2)
  44738. this.l2_2 = this.l2_2.scale(0.785398);
  44739. this.l2_1 = this.l2_1.scale(0.785398);
  44740. this.l20 = this.l20.scale(0.785398);
  44741. this.l21 = this.l21.scale(0.785398);
  44742. this.lL22 = this.lL22.scale(0.785398);
  44743. };
  44744. /**
  44745. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  44746. *
  44747. * ```
  44748. * L = (1/pi) * E * rho
  44749. * ```
  44750. *
  44751. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  44752. */
  44753. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  44754. this.scale(1.0 / Math.PI);
  44755. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  44756. // (The pixel shader must apply albedo after texture fetches, etc).
  44757. };
  44758. /**
  44759. * Gets the spherical harmonics from polynomial
  44760. * @param polynomial the spherical polynomial
  44761. * @returns the spherical harmonics
  44762. */
  44763. SphericalHarmonics.FromPolynomial = function (polynomial) {
  44764. var result = new SphericalHarmonics();
  44765. result.l00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  44766. result.l1_1 = polynomial.y.scale(0.977204);
  44767. result.l10 = polynomial.z.scale(0.977204);
  44768. result.l11 = polynomial.x.scale(0.977204);
  44769. result.l2_2 = polynomial.xy.scale(1.16538);
  44770. result.l2_1 = polynomial.yz.scale(1.16538);
  44771. result.l20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  44772. result.l21 = polynomial.zx.scale(1.16538);
  44773. result.lL22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  44774. result.scale(Math.PI);
  44775. return result;
  44776. };
  44777. /**
  44778. * Constructs a spherical harmonics from an array.
  44779. * @param data defines the 9x3 coefficients (l00, l1-1, l10, l11, l2-2, l2-1, l20, l21, l22)
  44780. * @returns the spherical harmonics
  44781. */
  44782. SphericalHarmonics.FromArray = function (data) {
  44783. var sh = new SphericalHarmonics();
  44784. BABYLON.Vector3.FromArrayToRef(data[0], 0, sh.l00);
  44785. BABYLON.Vector3.FromArrayToRef(data[1], 0, sh.l1_1);
  44786. BABYLON.Vector3.FromArrayToRef(data[2], 0, sh.l10);
  44787. BABYLON.Vector3.FromArrayToRef(data[3], 0, sh.l11);
  44788. BABYLON.Vector3.FromArrayToRef(data[4], 0, sh.l2_2);
  44789. BABYLON.Vector3.FromArrayToRef(data[5], 0, sh.l2_1);
  44790. BABYLON.Vector3.FromArrayToRef(data[6], 0, sh.l20);
  44791. BABYLON.Vector3.FromArrayToRef(data[7], 0, sh.l21);
  44792. BABYLON.Vector3.FromArrayToRef(data[8], 0, sh.lL22);
  44793. return sh;
  44794. };
  44795. return SphericalHarmonics;
  44796. }());
  44797. BABYLON.SphericalHarmonics = SphericalHarmonics;
  44798. })(BABYLON || (BABYLON = {}));
  44799. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  44800. var BABYLON;
  44801. (function (BABYLON) {
  44802. var FileFaceOrientation = /** @class */ (function () {
  44803. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  44804. this.name = name;
  44805. this.worldAxisForNormal = worldAxisForNormal;
  44806. this.worldAxisForFileX = worldAxisForFileX;
  44807. this.worldAxisForFileY = worldAxisForFileY;
  44808. }
  44809. return FileFaceOrientation;
  44810. }());
  44811. ;
  44812. /**
  44813. * Helper class dealing with the extraction of spherical polynomial dataArray
  44814. * from a cube map.
  44815. */
  44816. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  44817. function CubeMapToSphericalPolynomialTools() {
  44818. }
  44819. /**
  44820. * Converts a texture to the according Spherical Polynomial data.
  44821. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44822. *
  44823. * @param texture The texture to extract the information from.
  44824. * @return The Spherical Polynomial data.
  44825. */
  44826. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  44827. if (!texture.isCube) {
  44828. // Only supports cube Textures currently.
  44829. return null;
  44830. }
  44831. var size = texture.getSize().width;
  44832. var right = texture.readPixels(0);
  44833. var left = texture.readPixels(1);
  44834. var up;
  44835. var down;
  44836. if (texture.isRenderTarget) {
  44837. up = texture.readPixels(3);
  44838. down = texture.readPixels(2);
  44839. }
  44840. else {
  44841. up = texture.readPixels(2);
  44842. down = texture.readPixels(3);
  44843. }
  44844. var front = texture.readPixels(4);
  44845. var back = texture.readPixels(5);
  44846. var gammaSpace = texture.gammaSpace;
  44847. // Always read as RGBA.
  44848. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  44849. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  44850. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44851. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  44852. }
  44853. var cubeInfo = {
  44854. size: size,
  44855. right: right,
  44856. left: left,
  44857. up: up,
  44858. down: down,
  44859. front: front,
  44860. back: back,
  44861. format: format,
  44862. type: type,
  44863. gammaSpace: gammaSpace,
  44864. };
  44865. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  44866. };
  44867. /**
  44868. * Converts a cubemap to the according Spherical Polynomial data.
  44869. * This extracts the first 3 orders only as they are the only one used in the lighting.
  44870. *
  44871. * @param cubeInfo The Cube map to extract the information from.
  44872. * @return The Spherical Polynomial data.
  44873. */
  44874. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  44875. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  44876. var totalSolidAngle = 0.0;
  44877. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  44878. var du = 2.0 / cubeInfo.size;
  44879. var dv = du;
  44880. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  44881. var minUV = du * 0.5 - 1.0;
  44882. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  44883. var fileFace = this.FileFaces[faceIndex];
  44884. var dataArray = cubeInfo[fileFace.name];
  44885. var v = minUV;
  44886. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  44887. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  44888. // Because SP is still linear, so summation is fine in that basis.
  44889. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  44890. for (var y = 0; y < cubeInfo.size; y++) {
  44891. var u = minUV;
  44892. for (var x = 0; x < cubeInfo.size; x++) {
  44893. // World direction (not normalised)
  44894. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  44895. worldDirection.normalize();
  44896. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  44897. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  44898. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  44899. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  44900. // Handle Integer types.
  44901. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  44902. r /= 255;
  44903. g /= 255;
  44904. b /= 255;
  44905. }
  44906. // Handle Gamma space textures.
  44907. if (cubeInfo.gammaSpace) {
  44908. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  44909. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  44910. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  44911. }
  44912. var color = new BABYLON.Color3(r, g, b);
  44913. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  44914. totalSolidAngle += deltaSolidAngle;
  44915. u += du;
  44916. }
  44917. v += dv;
  44918. }
  44919. }
  44920. // Solid angle for entire sphere is 4*pi
  44921. var sphereSolidAngle = 4.0 * Math.PI;
  44922. // Adjust the solid angle to allow for how many faces we processed.
  44923. var facesProcessed = 6.0;
  44924. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  44925. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  44926. // This is needed because the numerical integration over the cube uses a
  44927. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  44928. // and also to compensate for accumulative error due to float precision in the summation.
  44929. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  44930. sphericalHarmonics.scale(correctionFactor);
  44931. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  44932. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  44933. return BABYLON.SphericalPolynomial.FromHarmonics(sphericalHarmonics);
  44934. };
  44935. CubeMapToSphericalPolynomialTools.FileFaces = [
  44936. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  44937. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  44938. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  44939. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  44940. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  44941. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  44942. ];
  44943. return CubeMapToSphericalPolynomialTools;
  44944. }());
  44945. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  44946. })(BABYLON || (BABYLON = {}));
  44947. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  44948. var BABYLON;
  44949. (function (BABYLON) {
  44950. /**
  44951. * Manages the defines for the PBR Material.
  44952. * @hiddenChildren
  44953. */
  44954. var PBRMaterialDefines = /** @class */ (function (_super) {
  44955. __extends(PBRMaterialDefines, _super);
  44956. /**
  44957. * Initializes the PBR Material defines.
  44958. */
  44959. function PBRMaterialDefines() {
  44960. var _this = _super.call(this) || this;
  44961. _this.PBR = true;
  44962. _this.MAINUV1 = false;
  44963. _this.MAINUV2 = false;
  44964. _this.UV1 = false;
  44965. _this.UV2 = false;
  44966. _this.ALBEDO = false;
  44967. _this.ALBEDODIRECTUV = 0;
  44968. _this.VERTEXCOLOR = false;
  44969. _this.AMBIENT = false;
  44970. _this.AMBIENTDIRECTUV = 0;
  44971. _this.AMBIENTINGRAYSCALE = false;
  44972. _this.OPACITY = false;
  44973. _this.VERTEXALPHA = false;
  44974. _this.OPACITYDIRECTUV = 0;
  44975. _this.OPACITYRGB = false;
  44976. _this.ALPHATEST = false;
  44977. _this.DEPTHPREPASS = false;
  44978. _this.ALPHABLEND = false;
  44979. _this.ALPHAFROMALBEDO = false;
  44980. _this.ALPHATESTVALUE = "0.5";
  44981. _this.SPECULAROVERALPHA = false;
  44982. _this.RADIANCEOVERALPHA = false;
  44983. _this.ALPHAFRESNEL = false;
  44984. _this.LINEARALPHAFRESNEL = false;
  44985. _this.PREMULTIPLYALPHA = false;
  44986. _this.EMISSIVE = false;
  44987. _this.EMISSIVEDIRECTUV = 0;
  44988. _this.REFLECTIVITY = false;
  44989. _this.REFLECTIVITYDIRECTUV = 0;
  44990. _this.SPECULARTERM = false;
  44991. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44992. _this.MICROSURFACEAUTOMATIC = false;
  44993. _this.LODBASEDMICROSFURACE = false;
  44994. _this.MICROSURFACEMAP = false;
  44995. _this.MICROSURFACEMAPDIRECTUV = 0;
  44996. _this.METALLICWORKFLOW = false;
  44997. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44998. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44999. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  45000. _this.AOSTOREINMETALMAPRED = false;
  45001. _this.ENVIRONMENTBRDF = false;
  45002. _this.NORMAL = false;
  45003. _this.TANGENT = false;
  45004. _this.BUMP = false;
  45005. _this.BUMPDIRECTUV = 0;
  45006. _this.OBJECTSPACE_NORMALMAP = false;
  45007. _this.PARALLAX = false;
  45008. _this.PARALLAXOCCLUSION = false;
  45009. _this.NORMALXYSCALE = true;
  45010. _this.LIGHTMAP = false;
  45011. _this.LIGHTMAPDIRECTUV = 0;
  45012. _this.USELIGHTMAPASSHADOWMAP = false;
  45013. _this.GAMMALIGHTMAP = false;
  45014. _this.REFLECTION = false;
  45015. _this.REFLECTIONMAP_3D = false;
  45016. _this.REFLECTIONMAP_SPHERICAL = false;
  45017. _this.REFLECTIONMAP_PLANAR = false;
  45018. _this.REFLECTIONMAP_CUBIC = false;
  45019. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45020. _this.REFLECTIONMAP_PROJECTION = false;
  45021. _this.REFLECTIONMAP_SKYBOX = false;
  45022. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45023. _this.REFLECTIONMAP_EXPLICIT = false;
  45024. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45025. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45026. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45027. _this.INVERTCUBICMAP = false;
  45028. _this.USESPHERICALFROMREFLECTIONMAP = false;
  45029. _this.USESPHERICALINVERTEX = false;
  45030. _this.REFLECTIONMAP_OPPOSITEZ = false;
  45031. _this.LODINREFLECTIONALPHA = false;
  45032. _this.GAMMAREFLECTION = false;
  45033. _this.RGBDREFLECTION = false;
  45034. _this.RADIANCEOCCLUSION = false;
  45035. _this.HORIZONOCCLUSION = false;
  45036. _this.REFRACTION = false;
  45037. _this.REFRACTIONMAP_3D = false;
  45038. _this.REFRACTIONMAP_OPPOSITEZ = false;
  45039. _this.LODINREFRACTIONALPHA = false;
  45040. _this.GAMMAREFRACTION = false;
  45041. _this.RGBDREFRACTION = false;
  45042. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  45043. _this.INSTANCES = false;
  45044. _this.NUM_BONE_INFLUENCERS = 0;
  45045. _this.BonesPerMesh = 0;
  45046. _this.NONUNIFORMSCALING = false;
  45047. _this.MORPHTARGETS = false;
  45048. _this.MORPHTARGETS_NORMAL = false;
  45049. _this.MORPHTARGETS_TANGENT = false;
  45050. _this.NUM_MORPH_INFLUENCERS = 0;
  45051. _this.IMAGEPROCESSING = false;
  45052. _this.VIGNETTE = false;
  45053. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  45054. _this.VIGNETTEBLENDMODEOPAQUE = false;
  45055. _this.TONEMAPPING = false;
  45056. _this.TONEMAPPING_ACES = false;
  45057. _this.CONTRAST = false;
  45058. _this.COLORCURVES = false;
  45059. _this.COLORGRADING = false;
  45060. _this.COLORGRADING3D = false;
  45061. _this.SAMPLER3DGREENDEPTH = false;
  45062. _this.SAMPLER3DBGRMAP = false;
  45063. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  45064. _this.EXPOSURE = false;
  45065. _this.USEPHYSICALLIGHTFALLOFF = false;
  45066. _this.USEGLTFLIGHTFALLOFF = false;
  45067. _this.TWOSIDEDLIGHTING = false;
  45068. _this.SHADOWFLOAT = false;
  45069. _this.CLIPPLANE = false;
  45070. _this.CLIPPLANE2 = false;
  45071. _this.CLIPPLANE3 = false;
  45072. _this.CLIPPLANE4 = false;
  45073. _this.POINTSIZE = false;
  45074. _this.FOG = false;
  45075. _this.LOGARITHMICDEPTH = false;
  45076. _this.FORCENORMALFORWARD = false;
  45077. _this.SPECULARAA = false;
  45078. _this.UNLIT = false;
  45079. _this.rebuild();
  45080. return _this;
  45081. }
  45082. /**
  45083. * Resets the PBR Material defines.
  45084. */
  45085. PBRMaterialDefines.prototype.reset = function () {
  45086. _super.prototype.reset.call(this);
  45087. this.ALPHATESTVALUE = "0.5";
  45088. this.PBR = true;
  45089. };
  45090. return PBRMaterialDefines;
  45091. }(BABYLON.MaterialDefines));
  45092. /**
  45093. * The Physically based material base class of BJS.
  45094. *
  45095. * This offers the main features of a standard PBR material.
  45096. * For more information, please refer to the documentation :
  45097. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45098. */
  45099. var PBRBaseMaterial = /** @class */ (function (_super) {
  45100. __extends(PBRBaseMaterial, _super);
  45101. /**
  45102. * Instantiates a new PBRMaterial instance.
  45103. *
  45104. * @param name The material name
  45105. * @param scene The scene the material will be use in.
  45106. */
  45107. function PBRBaseMaterial(name, scene) {
  45108. var _this = _super.call(this, name, scene) || this;
  45109. /**
  45110. * Intensity of the direct lights e.g. the four lights available in your scene.
  45111. * This impacts both the direct diffuse and specular highlights.
  45112. */
  45113. _this._directIntensity = 1.0;
  45114. /**
  45115. * Intensity of the emissive part of the material.
  45116. * This helps controlling the emissive effect without modifying the emissive color.
  45117. */
  45118. _this._emissiveIntensity = 1.0;
  45119. /**
  45120. * Intensity of the environment e.g. how much the environment will light the object
  45121. * either through harmonics for rough material or through the refelction for shiny ones.
  45122. */
  45123. _this._environmentIntensity = 1.0;
  45124. /**
  45125. * This is a special control allowing the reduction of the specular highlights coming from the
  45126. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45127. */
  45128. _this._specularIntensity = 1.0;
  45129. /**
  45130. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  45131. */
  45132. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  45133. /**
  45134. * Debug Control allowing disabling the bump map on this material.
  45135. */
  45136. _this._disableBumpMap = false;
  45137. /**
  45138. * AKA Occlusion Texture Intensity in other nomenclature.
  45139. */
  45140. _this._ambientTextureStrength = 1.0;
  45141. /**
  45142. * Defines how much the AO map is occluding the analytical lights (point spot...).
  45143. * 1 means it completely occludes it
  45144. * 0 mean it has no impact
  45145. */
  45146. _this._ambientTextureImpactOnAnalyticalLights = BABYLON.PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  45147. /**
  45148. * The color of a material in ambient lighting.
  45149. */
  45150. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  45151. /**
  45152. * AKA Diffuse Color in other nomenclature.
  45153. */
  45154. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  45155. /**
  45156. * AKA Specular Color in other nomenclature.
  45157. */
  45158. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45159. /**
  45160. * The color applied when light is reflected from a material.
  45161. */
  45162. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  45163. /**
  45164. * The color applied when light is emitted from a material.
  45165. */
  45166. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  45167. /**
  45168. * AKA Glossiness in other nomenclature.
  45169. */
  45170. _this._microSurface = 0.9;
  45171. /**
  45172. * source material index of refraction (IOR)' / 'destination material IOR.
  45173. */
  45174. _this._indexOfRefraction = 0.66;
  45175. /**
  45176. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45177. */
  45178. _this._invertRefractionY = false;
  45179. /**
  45180. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45181. * Materials half opaque for instance using refraction could benefit from this control.
  45182. */
  45183. _this._linkRefractionWithTransparency = false;
  45184. /**
  45185. * Specifies that the material will use the light map as a show map.
  45186. */
  45187. _this._useLightmapAsShadowmap = false;
  45188. /**
  45189. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45190. * makes the reflect vector face the model (under horizon).
  45191. */
  45192. _this._useHorizonOcclusion = true;
  45193. /**
  45194. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45195. * too much the area relying on ambient texture to define their ambient occlusion.
  45196. */
  45197. _this._useRadianceOcclusion = true;
  45198. /**
  45199. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45200. */
  45201. _this._useAlphaFromAlbedoTexture = false;
  45202. /**
  45203. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45204. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45205. */
  45206. _this._useSpecularOverAlpha = true;
  45207. /**
  45208. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45209. */
  45210. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  45211. /**
  45212. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45213. */
  45214. _this._useRoughnessFromMetallicTextureAlpha = true;
  45215. /**
  45216. * Specifies if the metallic texture contains the roughness information in its green channel.
  45217. */
  45218. _this._useRoughnessFromMetallicTextureGreen = false;
  45219. /**
  45220. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45221. */
  45222. _this._useMetallnessFromMetallicTextureBlue = false;
  45223. /**
  45224. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45225. */
  45226. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  45227. /**
  45228. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45229. */
  45230. _this._useAmbientInGrayScale = false;
  45231. /**
  45232. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45233. * The material will try to infer what glossiness each pixel should be.
  45234. */
  45235. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  45236. /**
  45237. * Defines the falloff type used in this material.
  45238. * It by default is Physical.
  45239. */
  45240. _this._lightFalloff = PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  45241. /**
  45242. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45243. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45244. */
  45245. _this._useRadianceOverAlpha = true;
  45246. /**
  45247. * Allows using an object space normal map (instead of tangent space).
  45248. */
  45249. _this._useObjectSpaceNormalMap = false;
  45250. /**
  45251. * Allows using the bump map in parallax mode.
  45252. */
  45253. _this._useParallax = false;
  45254. /**
  45255. * Allows using the bump map in parallax occlusion mode.
  45256. */
  45257. _this._useParallaxOcclusion = false;
  45258. /**
  45259. * Controls the scale bias of the parallax mode.
  45260. */
  45261. _this._parallaxScaleBias = 0.05;
  45262. /**
  45263. * If sets to true, disables all the lights affecting the material.
  45264. */
  45265. _this._disableLighting = false;
  45266. /**
  45267. * Number of Simultaneous lights allowed on the material.
  45268. */
  45269. _this._maxSimultaneousLights = 4;
  45270. /**
  45271. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  45272. */
  45273. _this._invertNormalMapX = false;
  45274. /**
  45275. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  45276. */
  45277. _this._invertNormalMapY = false;
  45278. /**
  45279. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45280. */
  45281. _this._twoSidedLighting = false;
  45282. /**
  45283. * Defines the alpha limits in alpha test mode.
  45284. */
  45285. _this._alphaCutOff = 0.4;
  45286. /**
  45287. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45288. */
  45289. _this._forceAlphaTest = false;
  45290. /**
  45291. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45292. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45293. */
  45294. _this._useAlphaFresnel = false;
  45295. /**
  45296. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45297. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45298. */
  45299. _this._useLinearAlphaFresnel = false;
  45300. /**
  45301. * The transparency mode of the material.
  45302. */
  45303. _this._transparencyMode = null;
  45304. /**
  45305. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  45306. * from cos thetav and roughness:
  45307. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  45308. */
  45309. _this._environmentBRDFTexture = null;
  45310. /**
  45311. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45312. */
  45313. _this._forceIrradianceInFragment = false;
  45314. /**
  45315. * Force normal to face away from face.
  45316. */
  45317. _this._forceNormalForward = false;
  45318. /**
  45319. * Enables specular anti aliasing in the PBR shader.
  45320. * It will both interacts on the Geometry for analytical and IBL lighting.
  45321. * It also prefilter the roughness map based on the bump values.
  45322. */
  45323. _this._enableSpecularAntiAliasing = false;
  45324. /**
  45325. * Stores the available render targets.
  45326. */
  45327. _this._renderTargets = new BABYLON.SmartArray(16);
  45328. /**
  45329. * Sets the global ambient color for the material used in lighting calculations.
  45330. */
  45331. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  45332. /**
  45333. * If set to true, no lighting calculations will be applied.
  45334. */
  45335. _this._unlit = false;
  45336. // Setup the default processing configuration to the scene.
  45337. _this._attachImageProcessingConfiguration(null);
  45338. _this.getRenderTargetTextures = function () {
  45339. _this._renderTargets.reset();
  45340. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  45341. _this._renderTargets.push(_this._reflectionTexture);
  45342. }
  45343. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  45344. _this._renderTargets.push(_this._refractionTexture);
  45345. }
  45346. return _this._renderTargets;
  45347. };
  45348. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45349. return _this;
  45350. }
  45351. /**
  45352. * Attaches a new image processing configuration to the PBR Material.
  45353. * @param configuration
  45354. */
  45355. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  45356. var _this = this;
  45357. if (configuration === this._imageProcessingConfiguration) {
  45358. return;
  45359. }
  45360. // Detaches observer.
  45361. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45362. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45363. }
  45364. // Pick the scene configuration if needed.
  45365. if (!configuration) {
  45366. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  45367. }
  45368. else {
  45369. this._imageProcessingConfiguration = configuration;
  45370. }
  45371. // Attaches observer.
  45372. if (this._imageProcessingConfiguration) {
  45373. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  45374. _this._markAllSubMeshesAsImageProcessingDirty();
  45375. });
  45376. }
  45377. };
  45378. Object.defineProperty(PBRBaseMaterial.prototype, "hasRenderTargetTextures", {
  45379. /**
  45380. * Gets a boolean indicating that current material needs to register RTT
  45381. */
  45382. get: function () {
  45383. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45384. return true;
  45385. }
  45386. if (BABYLON.StandardMaterial.RefractionTextureEnabled && this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45387. return true;
  45388. }
  45389. return false;
  45390. },
  45391. enumerable: true,
  45392. configurable: true
  45393. });
  45394. /**
  45395. * Gets the name of the material class.
  45396. */
  45397. PBRBaseMaterial.prototype.getClassName = function () {
  45398. return "PBRBaseMaterial";
  45399. };
  45400. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  45401. /**
  45402. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45403. */
  45404. get: function () {
  45405. return this._useLogarithmicDepth;
  45406. },
  45407. /**
  45408. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  45409. */
  45410. set: function (value) {
  45411. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  45412. },
  45413. enumerable: true,
  45414. configurable: true
  45415. });
  45416. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  45417. /**
  45418. * Gets the current transparency mode.
  45419. */
  45420. get: function () {
  45421. return this._transparencyMode;
  45422. },
  45423. /**
  45424. * Sets the transparency mode of the material.
  45425. *
  45426. * | Value | Type | Description |
  45427. * | ----- | ----------------------------------- | ----------- |
  45428. * | 0 | OPAQUE | |
  45429. * | 1 | ALPHATEST | |
  45430. * | 2 | ALPHABLEND | |
  45431. * | 3 | ALPHATESTANDBLEND | |
  45432. *
  45433. */
  45434. set: function (value) {
  45435. if (this._transparencyMode === value) {
  45436. return;
  45437. }
  45438. this._transparencyMode = value;
  45439. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  45440. this._markAllSubMeshesAsTexturesAndMiscDirty();
  45441. },
  45442. enumerable: true,
  45443. configurable: true
  45444. });
  45445. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  45446. /**
  45447. * Returns true if alpha blending should be disabled.
  45448. */
  45449. get: function () {
  45450. return (this._linkRefractionWithTransparency ||
  45451. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  45452. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45453. },
  45454. enumerable: true,
  45455. configurable: true
  45456. });
  45457. /**
  45458. * Specifies whether or not this material should be rendered in alpha blend mode.
  45459. */
  45460. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  45461. if (this._disableAlphaBlending) {
  45462. return false;
  45463. }
  45464. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  45465. };
  45466. /**
  45467. * Specifies if the mesh will require alpha blending.
  45468. * @param mesh - BJS mesh.
  45469. */
  45470. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  45471. if (this._disableAlphaBlending) {
  45472. return false;
  45473. }
  45474. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  45475. };
  45476. /**
  45477. * Specifies whether or not this material should be rendered in alpha test mode.
  45478. */
  45479. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  45480. if (this._forceAlphaTest) {
  45481. return true;
  45482. }
  45483. if (this._linkRefractionWithTransparency) {
  45484. return false;
  45485. }
  45486. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  45487. };
  45488. /**
  45489. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  45490. */
  45491. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  45492. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  45493. };
  45494. /**
  45495. * Gets the texture used for the alpha test.
  45496. */
  45497. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  45498. return this._albedoTexture;
  45499. };
  45500. /**
  45501. * Specifies that the submesh is ready to be used.
  45502. * @param mesh - BJS mesh.
  45503. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  45504. * @param useInstances - Specifies that instances should be used.
  45505. * @returns - boolean indicating that the submesh is ready or not.
  45506. */
  45507. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  45508. if (subMesh.effect && this.isFrozen) {
  45509. if (this._wasPreviouslyReady) {
  45510. return true;
  45511. }
  45512. }
  45513. if (!subMesh._materialDefines) {
  45514. subMesh._materialDefines = new PBRMaterialDefines();
  45515. }
  45516. var defines = subMesh._materialDefines;
  45517. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  45518. if (defines._renderId === this.getScene().getRenderId()) {
  45519. return true;
  45520. }
  45521. }
  45522. var scene = this.getScene();
  45523. var engine = scene.getEngine();
  45524. if (defines._areTexturesDirty) {
  45525. if (scene.texturesEnabled) {
  45526. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45527. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  45528. return false;
  45529. }
  45530. }
  45531. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45532. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  45533. return false;
  45534. }
  45535. }
  45536. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45537. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  45538. return false;
  45539. }
  45540. }
  45541. var reflectionTexture = this._getReflectionTexture();
  45542. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45543. if (!reflectionTexture.isReadyOrNotBlocking()) {
  45544. return false;
  45545. }
  45546. }
  45547. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45548. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  45549. return false;
  45550. }
  45551. }
  45552. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45553. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  45554. return false;
  45555. }
  45556. }
  45557. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45558. if (this._metallicTexture) {
  45559. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  45560. return false;
  45561. }
  45562. }
  45563. else if (this._reflectivityTexture) {
  45564. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  45565. return false;
  45566. }
  45567. }
  45568. if (this._microSurfaceTexture) {
  45569. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  45570. return false;
  45571. }
  45572. }
  45573. }
  45574. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45575. // Bump texture cannot be not blocking.
  45576. if (!this._bumpTexture.isReady()) {
  45577. return false;
  45578. }
  45579. }
  45580. var refractionTexture = this._getRefractionTexture();
  45581. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45582. if (!refractionTexture.isReadyOrNotBlocking()) {
  45583. return false;
  45584. }
  45585. }
  45586. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45587. // This is blocking.
  45588. if (!this._environmentBRDFTexture.isReady()) {
  45589. return false;
  45590. }
  45591. }
  45592. }
  45593. }
  45594. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45595. if (!this._imageProcessingConfiguration.isReady()) {
  45596. return false;
  45597. }
  45598. }
  45599. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  45600. mesh.createNormals(true);
  45601. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  45602. }
  45603. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  45604. if (effect) {
  45605. scene.resetCachedMaterial();
  45606. subMesh.setEffect(effect, defines);
  45607. this.buildUniformLayout();
  45608. }
  45609. if (!subMesh.effect || !subMesh.effect.isReady()) {
  45610. return false;
  45611. }
  45612. defines._renderId = scene.getRenderId();
  45613. this._wasPreviouslyReady = true;
  45614. return true;
  45615. };
  45616. /**
  45617. * Specifies if the material uses metallic roughness workflow.
  45618. * @returns boolean specifiying if the material uses metallic roughness workflow.
  45619. */
  45620. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  45621. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  45622. return true;
  45623. }
  45624. return false;
  45625. };
  45626. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  45627. if (onCompiled === void 0) { onCompiled = null; }
  45628. if (onError === void 0) { onError = null; }
  45629. if (useInstances === void 0) { useInstances = null; }
  45630. if (useClipPlane === void 0) { useClipPlane = null; }
  45631. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  45632. if (!defines.isDirty) {
  45633. return null;
  45634. }
  45635. defines.markAsProcessed();
  45636. var scene = this.getScene();
  45637. var engine = scene.getEngine();
  45638. // Fallbacks
  45639. var fallbacks = new BABYLON.EffectFallbacks();
  45640. var fallbackRank = 0;
  45641. if (defines.USESPHERICALINVERTEX) {
  45642. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  45643. }
  45644. if (defines.FOG) {
  45645. fallbacks.addFallback(fallbackRank, "FOG");
  45646. }
  45647. if (defines.SPECULARAA) {
  45648. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  45649. }
  45650. if (defines.POINTSIZE) {
  45651. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  45652. }
  45653. if (defines.LOGARITHMICDEPTH) {
  45654. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  45655. }
  45656. if (defines.PARALLAX) {
  45657. fallbacks.addFallback(fallbackRank, "PARALLAX");
  45658. }
  45659. if (defines.PARALLAXOCCLUSION) {
  45660. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  45661. }
  45662. if (defines.ENVIRONMENTBRDF) {
  45663. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  45664. }
  45665. if (defines.TANGENT) {
  45666. fallbacks.addFallback(fallbackRank++, "TANGENT");
  45667. }
  45668. if (defines.BUMP) {
  45669. fallbacks.addFallback(fallbackRank++, "BUMP");
  45670. }
  45671. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45672. if (defines.SPECULARTERM) {
  45673. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45674. }
  45675. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45676. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45677. }
  45678. if (defines.LIGHTMAP) {
  45679. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45680. }
  45681. if (defines.NORMAL) {
  45682. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45683. }
  45684. if (defines.AMBIENT) {
  45685. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45686. }
  45687. if (defines.EMISSIVE) {
  45688. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45689. }
  45690. if (defines.VERTEXCOLOR) {
  45691. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45692. }
  45693. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45694. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45695. }
  45696. if (defines.MORPHTARGETS) {
  45697. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45698. }
  45699. //Attributes
  45700. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45701. if (defines.NORMAL) {
  45702. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45703. }
  45704. if (defines.TANGENT) {
  45705. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45706. }
  45707. if (defines.UV1) {
  45708. attribs.push(BABYLON.VertexBuffer.UVKind);
  45709. }
  45710. if (defines.UV2) {
  45711. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45712. }
  45713. if (defines.VERTEXCOLOR) {
  45714. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45715. }
  45716. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45717. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45718. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45719. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45720. "vFogInfos", "vFogColor", "pointSize",
  45721. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45722. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45723. "mBones",
  45724. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45725. "vLightingIntensity",
  45726. "logarithmicDepthConstant",
  45727. "vSphericalX", "vSphericalY", "vSphericalZ",
  45728. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45729. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45730. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45731. "vTangentSpaceParams"
  45732. ];
  45733. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45734. "bumpSampler", "lightmapSampler", "opacitySampler",
  45735. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45736. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45737. "microSurfaceSampler", "environmentBrdfSampler"];
  45738. var uniformBuffers = ["Material", "Scene"];
  45739. if (BABYLON.ImageProcessingConfiguration) {
  45740. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45741. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45742. }
  45743. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45744. uniformsNames: uniforms,
  45745. uniformBuffersNames: uniformBuffers,
  45746. samplers: samplers,
  45747. defines: defines,
  45748. maxSimultaneousLights: this._maxSimultaneousLights
  45749. });
  45750. var join = defines.toString();
  45751. return engine.createEffect("pbr", {
  45752. attributes: attribs,
  45753. uniformsNames: uniforms,
  45754. uniformBuffersNames: uniformBuffers,
  45755. samplers: samplers,
  45756. defines: join,
  45757. fallbacks: fallbacks,
  45758. onCompiled: onCompiled,
  45759. onError: onError,
  45760. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45761. }, engine);
  45762. };
  45763. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45764. if (useInstances === void 0) { useInstances = null; }
  45765. if (useClipPlane === void 0) { useClipPlane = null; }
  45766. var scene = this.getScene();
  45767. var engine = scene.getEngine();
  45768. // Lights
  45769. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45770. defines._needNormals = true;
  45771. // Textures
  45772. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45773. if (defines._areTexturesDirty) {
  45774. defines._needUVs = false;
  45775. if (scene.texturesEnabled) {
  45776. if (scene.getEngine().getCaps().textureLOD) {
  45777. defines.LODBASEDMICROSFURACE = true;
  45778. }
  45779. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45780. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45781. }
  45782. else {
  45783. defines.ALBEDO = false;
  45784. }
  45785. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45786. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45787. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45788. }
  45789. else {
  45790. defines.AMBIENT = false;
  45791. }
  45792. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45793. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45794. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45795. }
  45796. else {
  45797. defines.OPACITY = false;
  45798. }
  45799. var reflectionTexture = this._getReflectionTexture();
  45800. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45801. defines.REFLECTION = true;
  45802. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45803. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  45804. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45805. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45806. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45807. defines.INVERTCUBICMAP = true;
  45808. }
  45809. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45810. switch (reflectionTexture.coordinatesMode) {
  45811. case BABYLON.Texture.EXPLICIT_MODE:
  45812. defines.REFLECTIONMAP_EXPLICIT = true;
  45813. break;
  45814. case BABYLON.Texture.PLANAR_MODE:
  45815. defines.REFLECTIONMAP_PLANAR = true;
  45816. break;
  45817. case BABYLON.Texture.PROJECTION_MODE:
  45818. defines.REFLECTIONMAP_PROJECTION = true;
  45819. break;
  45820. case BABYLON.Texture.SKYBOX_MODE:
  45821. defines.REFLECTIONMAP_SKYBOX = true;
  45822. break;
  45823. case BABYLON.Texture.SPHERICAL_MODE:
  45824. defines.REFLECTIONMAP_SPHERICAL = true;
  45825. break;
  45826. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45827. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45828. break;
  45829. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45830. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45831. break;
  45832. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45833. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45834. break;
  45835. case BABYLON.Texture.CUBIC_MODE:
  45836. case BABYLON.Texture.INVCUBIC_MODE:
  45837. default:
  45838. defines.REFLECTIONMAP_CUBIC = true;
  45839. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45840. break;
  45841. }
  45842. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45843. if (reflectionTexture.sphericalPolynomial) {
  45844. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45845. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45846. defines.USESPHERICALINVERTEX = false;
  45847. }
  45848. else {
  45849. defines.USESPHERICALINVERTEX = true;
  45850. }
  45851. }
  45852. }
  45853. else {
  45854. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  45855. }
  45856. }
  45857. else {
  45858. defines.REFLECTION = false;
  45859. defines.REFLECTIONMAP_3D = false;
  45860. defines.REFLECTIONMAP_SPHERICAL = false;
  45861. defines.REFLECTIONMAP_PLANAR = false;
  45862. defines.REFLECTIONMAP_CUBIC = false;
  45863. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45864. defines.REFLECTIONMAP_PROJECTION = false;
  45865. defines.REFLECTIONMAP_SKYBOX = false;
  45866. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  45867. defines.REFLECTIONMAP_EXPLICIT = false;
  45868. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45869. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45870. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45871. defines.INVERTCUBICMAP = false;
  45872. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45873. defines.USESPHERICALINVERTEX = false;
  45874. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45875. defines.LODINREFLECTIONALPHA = false;
  45876. defines.GAMMAREFLECTION = false;
  45877. defines.RGBDREFLECTION = false;
  45878. }
  45879. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45880. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45881. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45882. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45883. }
  45884. else {
  45885. defines.LIGHTMAP = false;
  45886. }
  45887. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45888. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45889. }
  45890. else {
  45891. defines.EMISSIVE = false;
  45892. }
  45893. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45894. if (this._metallicTexture) {
  45895. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45896. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45897. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45898. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45899. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45900. }
  45901. else if (this._reflectivityTexture) {
  45902. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45903. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45904. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45905. }
  45906. else {
  45907. defines.REFLECTIVITY = false;
  45908. }
  45909. if (this._microSurfaceTexture) {
  45910. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45911. }
  45912. else {
  45913. defines.MICROSURFACEMAP = false;
  45914. }
  45915. }
  45916. else {
  45917. defines.REFLECTIVITY = false;
  45918. defines.MICROSURFACEMAP = false;
  45919. }
  45920. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45921. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45922. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45923. defines.PARALLAX = true;
  45924. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45925. }
  45926. else {
  45927. defines.PARALLAX = false;
  45928. }
  45929. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45930. }
  45931. else {
  45932. defines.BUMP = false;
  45933. }
  45934. var refractionTexture = this._getRefractionTexture();
  45935. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45936. defines.REFRACTION = true;
  45937. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45938. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45939. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  45940. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45941. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45942. if (this._linkRefractionWithTransparency) {
  45943. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45944. }
  45945. }
  45946. else {
  45947. defines.REFRACTION = false;
  45948. }
  45949. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45950. defines.ENVIRONMENTBRDF = true;
  45951. }
  45952. else {
  45953. defines.ENVIRONMENTBRDF = false;
  45954. }
  45955. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45956. defines.ALPHAFROMALBEDO = true;
  45957. }
  45958. else {
  45959. defines.ALPHAFROMALBEDO = false;
  45960. }
  45961. }
  45962. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45963. if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_STANDARD) {
  45964. defines.USEPHYSICALLIGHTFALLOFF = false;
  45965. defines.USEGLTFLIGHTFALLOFF = false;
  45966. }
  45967. else if (this._lightFalloff === PBRBaseMaterial.LIGHTFALLOFF_GLTF) {
  45968. defines.USEPHYSICALLIGHTFALLOFF = false;
  45969. defines.USEGLTFLIGHTFALLOFF = true;
  45970. }
  45971. else {
  45972. defines.USEPHYSICALLIGHTFALLOFF = true;
  45973. defines.USEGLTFLIGHTFALLOFF = false;
  45974. }
  45975. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45976. if (!this.backFaceCulling && this._twoSidedLighting) {
  45977. defines.TWOSIDEDLIGHTING = true;
  45978. }
  45979. else {
  45980. defines.TWOSIDEDLIGHTING = false;
  45981. }
  45982. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45983. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45984. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45985. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45986. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45987. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45988. }
  45989. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  45990. this._imageProcessingConfiguration.prepareDefines(defines);
  45991. }
  45992. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45993. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45994. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45995. // Misc.
  45996. if (defines._areMiscDirty) {
  45997. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45998. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45999. }
  46000. // Values that need to be evaluated on every frame
  46001. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  46002. // Attribs
  46003. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  46004. };
  46005. /**
  46006. * Force shader compilation
  46007. */
  46008. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  46009. var _this = this;
  46010. var localOptions = __assign({ clipPlane: false }, options);
  46011. var defines = new PBRMaterialDefines();
  46012. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  46013. if (effect.isReady()) {
  46014. if (onCompiled) {
  46015. onCompiled(this);
  46016. }
  46017. }
  46018. else {
  46019. effect.onCompileObservable.add(function () {
  46020. if (onCompiled) {
  46021. onCompiled(_this);
  46022. }
  46023. });
  46024. }
  46025. };
  46026. /**
  46027. * Initializes the uniform buffer layout for the shader.
  46028. */
  46029. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  46030. // Order is important !
  46031. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  46032. this._uniformBuffer.addUniform("vAmbientInfos", 4);
  46033. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  46034. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  46035. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  46036. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  46037. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  46038. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  46039. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  46040. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  46041. this._uniformBuffer.addUniform("vReflectionSize", 3);
  46042. this._uniformBuffer.addUniform("vBumpInfos", 3);
  46043. this._uniformBuffer.addUniform("albedoMatrix", 16);
  46044. this._uniformBuffer.addUniform("ambientMatrix", 16);
  46045. this._uniformBuffer.addUniform("opacityMatrix", 16);
  46046. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  46047. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  46048. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  46049. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  46050. this._uniformBuffer.addUniform("bumpMatrix", 16);
  46051. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  46052. this._uniformBuffer.addUniform("refractionMatrix", 16);
  46053. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  46054. this._uniformBuffer.addUniform("vReflectionColor", 3);
  46055. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  46056. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  46057. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  46058. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  46059. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  46060. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  46061. this._uniformBuffer.addUniform("pointSize", 1);
  46062. this._uniformBuffer.create();
  46063. };
  46064. /**
  46065. * Unbinds the textures.
  46066. */
  46067. PBRBaseMaterial.prototype.unbind = function () {
  46068. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  46069. this._uniformBuffer.setTexture("reflectionSampler", null);
  46070. }
  46071. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  46072. this._uniformBuffer.setTexture("refractionSampler", null);
  46073. }
  46074. _super.prototype.unbind.call(this);
  46075. };
  46076. /**
  46077. * Binds the submesh data.
  46078. * @param world - The world matrix.
  46079. * @param mesh - The BJS mesh.
  46080. * @param subMesh - A submesh of the BJS mesh.
  46081. */
  46082. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  46083. var scene = this.getScene();
  46084. var defines = subMesh._materialDefines;
  46085. if (!defines) {
  46086. return;
  46087. }
  46088. var effect = subMesh.effect;
  46089. if (!effect) {
  46090. return;
  46091. }
  46092. this._activeEffect = effect;
  46093. // Matrices
  46094. this.bindOnlyWorldMatrix(world);
  46095. // Normal Matrix
  46096. if (defines.OBJECTSPACE_NORMALMAP) {
  46097. world.toNormalMatrix(this._normalMatrix);
  46098. this.bindOnlyNormalMatrix(this._normalMatrix);
  46099. }
  46100. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  46101. // Bones
  46102. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  46103. var reflectionTexture = null;
  46104. if (mustRebind) {
  46105. this._uniformBuffer.bindToEffect(effect, "Material");
  46106. this.bindViewProjection(effect);
  46107. reflectionTexture = this._getReflectionTexture();
  46108. var refractionTexture = this._getRefractionTexture();
  46109. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  46110. // Texture uniforms
  46111. if (scene.texturesEnabled) {
  46112. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46113. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  46114. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  46115. }
  46116. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46117. this._uniformBuffer.updateFloat4("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength, this._ambientTextureImpactOnAnalyticalLights);
  46118. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  46119. }
  46120. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46121. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  46122. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  46123. }
  46124. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46125. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  46126. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  46127. if (reflectionTexture.boundingBoxSize) {
  46128. var cubeTexture = reflectionTexture;
  46129. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  46130. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  46131. }
  46132. var polynomials = reflectionTexture.sphericalPolynomial;
  46133. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  46134. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  46135. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  46136. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  46137. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  46138. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  46139. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  46140. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  46141. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  46142. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  46143. }
  46144. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  46145. }
  46146. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46147. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  46148. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  46149. }
  46150. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46151. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  46152. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  46153. }
  46154. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46155. if (this._metallicTexture) {
  46156. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  46157. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  46158. }
  46159. else if (this._reflectivityTexture) {
  46160. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  46161. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  46162. }
  46163. if (this._microSurfaceTexture) {
  46164. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  46165. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  46166. }
  46167. }
  46168. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46169. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  46170. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  46171. if (scene._mirroredCameraPosition) {
  46172. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  46173. }
  46174. else {
  46175. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  46176. }
  46177. }
  46178. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46179. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  46180. var depth = 1.0;
  46181. if (!refractionTexture.isCube) {
  46182. if (refractionTexture.depth) {
  46183. depth = refractionTexture.depth;
  46184. }
  46185. }
  46186. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  46187. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  46188. }
  46189. }
  46190. // Point size
  46191. if (this.pointsCloud) {
  46192. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  46193. }
  46194. // Colors
  46195. if (defines.METALLICWORKFLOW) {
  46196. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  46197. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  46198. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  46199. }
  46200. else {
  46201. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  46202. }
  46203. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  46204. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  46205. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  46206. // Misc
  46207. this._lightingInfos.x = this._directIntensity;
  46208. this._lightingInfos.y = this._emissiveIntensity;
  46209. this._lightingInfos.z = this._environmentIntensity;
  46210. this._lightingInfos.w = this._specularIntensity;
  46211. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  46212. }
  46213. // Textures
  46214. if (scene.texturesEnabled) {
  46215. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  46216. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  46217. }
  46218. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  46219. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  46220. }
  46221. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  46222. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  46223. }
  46224. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  46225. if (defines.LODBASEDMICROSFURACE) {
  46226. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  46227. }
  46228. else {
  46229. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  46230. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  46231. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  46232. }
  46233. }
  46234. if (defines.ENVIRONMENTBRDF) {
  46235. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  46236. }
  46237. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  46238. if (defines.LODBASEDMICROSFURACE) {
  46239. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  46240. }
  46241. else {
  46242. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  46243. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  46244. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  46245. }
  46246. }
  46247. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  46248. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  46249. }
  46250. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  46251. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  46252. }
  46253. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  46254. if (this._metallicTexture) {
  46255. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  46256. }
  46257. else if (this._reflectivityTexture) {
  46258. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  46259. }
  46260. if (this._microSurfaceTexture) {
  46261. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  46262. }
  46263. }
  46264. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  46265. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  46266. }
  46267. }
  46268. // Clip plane
  46269. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  46270. // Colors
  46271. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  46272. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  46273. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  46274. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  46275. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  46276. }
  46277. if (mustRebind || !this.isFrozen) {
  46278. // Lights
  46279. if (scene.lightsEnabled && !this._disableLighting) {
  46280. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._lightFalloff !== PBRBaseMaterial.LIGHTFALLOFF_STANDARD);
  46281. }
  46282. // View
  46283. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  46284. this.bindView(effect);
  46285. }
  46286. // Fog
  46287. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  46288. // Morph targets
  46289. if (defines.NUM_MORPH_INFLUENCERS) {
  46290. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  46291. }
  46292. // image processing
  46293. this._imageProcessingConfiguration.bind(this._activeEffect);
  46294. // Log. depth
  46295. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  46296. }
  46297. this._uniformBuffer.update();
  46298. this._afterBind(mesh, this._activeEffect);
  46299. };
  46300. /**
  46301. * Returns the animatable textures.
  46302. * @returns - Array of animatable textures.
  46303. */
  46304. PBRBaseMaterial.prototype.getAnimatables = function () {
  46305. var results = [];
  46306. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  46307. results.push(this._albedoTexture);
  46308. }
  46309. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  46310. results.push(this._ambientTexture);
  46311. }
  46312. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  46313. results.push(this._opacityTexture);
  46314. }
  46315. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  46316. results.push(this._reflectionTexture);
  46317. }
  46318. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  46319. results.push(this._emissiveTexture);
  46320. }
  46321. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  46322. results.push(this._metallicTexture);
  46323. }
  46324. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  46325. results.push(this._reflectivityTexture);
  46326. }
  46327. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  46328. results.push(this._bumpTexture);
  46329. }
  46330. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  46331. results.push(this._lightmapTexture);
  46332. }
  46333. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  46334. results.push(this._refractionTexture);
  46335. }
  46336. return results;
  46337. };
  46338. /**
  46339. * Returns the texture used for reflections.
  46340. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  46341. */
  46342. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  46343. if (this._reflectionTexture) {
  46344. return this._reflectionTexture;
  46345. }
  46346. return this.getScene().environmentTexture;
  46347. };
  46348. /**
  46349. * Returns the texture used for refraction or null if none is used.
  46350. * @returns - Refection texture if present. If no refraction texture and refraction
  46351. * is linked with transparency, returns environment texture. Otherwise, returns null.
  46352. */
  46353. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  46354. if (this._refractionTexture) {
  46355. return this._refractionTexture;
  46356. }
  46357. if (this._linkRefractionWithTransparency) {
  46358. return this.getScene().environmentTexture;
  46359. }
  46360. return null;
  46361. };
  46362. /**
  46363. * Disposes the resources of the material.
  46364. * @param forceDisposeEffect - Forces the disposal of effects.
  46365. * @param forceDisposeTextures - Forces the disposal of all textures.
  46366. */
  46367. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  46368. if (forceDisposeTextures) {
  46369. if (this._albedoTexture) {
  46370. this._albedoTexture.dispose();
  46371. }
  46372. if (this._ambientTexture) {
  46373. this._ambientTexture.dispose();
  46374. }
  46375. if (this._opacityTexture) {
  46376. this._opacityTexture.dispose();
  46377. }
  46378. if (this._reflectionTexture) {
  46379. this._reflectionTexture.dispose();
  46380. }
  46381. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  46382. this._environmentBRDFTexture.dispose();
  46383. }
  46384. if (this._emissiveTexture) {
  46385. this._emissiveTexture.dispose();
  46386. }
  46387. if (this._metallicTexture) {
  46388. this._metallicTexture.dispose();
  46389. }
  46390. if (this._reflectivityTexture) {
  46391. this._reflectivityTexture.dispose();
  46392. }
  46393. if (this._bumpTexture) {
  46394. this._bumpTexture.dispose();
  46395. }
  46396. if (this._lightmapTexture) {
  46397. this._lightmapTexture.dispose();
  46398. }
  46399. if (this._refractionTexture) {
  46400. this._refractionTexture.dispose();
  46401. }
  46402. }
  46403. this._renderTargets.dispose();
  46404. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  46405. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  46406. }
  46407. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  46408. };
  46409. /**
  46410. * PBRMaterialLightFalloff Physical: light is falling off following the inverse squared distance law.
  46411. */
  46412. PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL = 0;
  46413. /**
  46414. * PBRMaterialLightFalloff gltf: light is falling off as described in the gltf moving to PBR document
  46415. * to enhance interoperability with other engines.
  46416. */
  46417. PBRBaseMaterial.LIGHTFALLOFF_GLTF = 1;
  46418. /**
  46419. * PBRMaterialLightFalloff Standard: light is falling off like in the standard material
  46420. * to enhance interoperability with other materials.
  46421. */
  46422. PBRBaseMaterial.LIGHTFALLOFF_STANDARD = 2;
  46423. /**
  46424. * Stores the reflectivity values based on metallic roughness workflow.
  46425. */
  46426. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  46427. __decorate([
  46428. BABYLON.serializeAsImageProcessingConfiguration()
  46429. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  46430. __decorate([
  46431. BABYLON.serialize()
  46432. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  46433. __decorate([
  46434. BABYLON.serialize()
  46435. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  46436. return PBRBaseMaterial;
  46437. }(BABYLON.PushMaterial));
  46438. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  46439. })(BABYLON || (BABYLON = {}));
  46440. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  46441. var BABYLON;
  46442. (function (BABYLON) {
  46443. /**
  46444. * The Physically based simple base material of BJS.
  46445. *
  46446. * This enables better naming and convention enforcements on top of the pbrMaterial.
  46447. * It is used as the base class for both the specGloss and metalRough conventions.
  46448. */
  46449. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  46450. __extends(PBRBaseSimpleMaterial, _super);
  46451. /**
  46452. * Instantiates a new PBRMaterial instance.
  46453. *
  46454. * @param name The material name
  46455. * @param scene The scene the material will be use in.
  46456. */
  46457. function PBRBaseSimpleMaterial(name, scene) {
  46458. var _this = _super.call(this, name, scene) || this;
  46459. /**
  46460. * Number of Simultaneous lights allowed on the material.
  46461. */
  46462. _this.maxSimultaneousLights = 4;
  46463. /**
  46464. * If sets to true, disables all the lights affecting the material.
  46465. */
  46466. _this.disableLighting = false;
  46467. /**
  46468. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46469. */
  46470. _this.invertNormalMapX = false;
  46471. /**
  46472. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46473. */
  46474. _this.invertNormalMapY = false;
  46475. /**
  46476. * Emissivie color used to self-illuminate the model.
  46477. */
  46478. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46479. /**
  46480. * Occlusion Channel Strenght.
  46481. */
  46482. _this.occlusionStrength = 1.0;
  46483. /**
  46484. * If true, the light map contains occlusion information instead of lighting info.
  46485. */
  46486. _this.useLightmapAsShadowmap = false;
  46487. _this._useAlphaFromAlbedoTexture = true;
  46488. _this._useAmbientInGrayScale = true;
  46489. return _this;
  46490. }
  46491. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  46492. /**
  46493. * Gets the current double sided mode.
  46494. */
  46495. get: function () {
  46496. return this._twoSidedLighting;
  46497. },
  46498. /**
  46499. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46500. */
  46501. set: function (value) {
  46502. if (this._twoSidedLighting === value) {
  46503. return;
  46504. }
  46505. this._twoSidedLighting = value;
  46506. this.backFaceCulling = !value;
  46507. this._markAllSubMeshesAsTexturesDirty();
  46508. },
  46509. enumerable: true,
  46510. configurable: true
  46511. });
  46512. /**
  46513. * Return the active textures of the material.
  46514. */
  46515. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  46516. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46517. if (this.environmentTexture) {
  46518. activeTextures.push(this.environmentTexture);
  46519. }
  46520. if (this.normalTexture) {
  46521. activeTextures.push(this.normalTexture);
  46522. }
  46523. if (this.emissiveTexture) {
  46524. activeTextures.push(this.emissiveTexture);
  46525. }
  46526. if (this.occlusionTexture) {
  46527. activeTextures.push(this.occlusionTexture);
  46528. }
  46529. if (this.lightmapTexture) {
  46530. activeTextures.push(this.lightmapTexture);
  46531. }
  46532. return activeTextures;
  46533. };
  46534. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  46535. if (_super.prototype.hasTexture.call(this, texture)) {
  46536. return true;
  46537. }
  46538. if (this.lightmapTexture === texture) {
  46539. return true;
  46540. }
  46541. return false;
  46542. };
  46543. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  46544. return "PBRBaseSimpleMaterial";
  46545. };
  46546. __decorate([
  46547. BABYLON.serialize(),
  46548. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46549. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  46550. __decorate([
  46551. BABYLON.serialize(),
  46552. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46553. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  46554. __decorate([
  46555. BABYLON.serializeAsTexture(),
  46556. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  46557. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  46558. __decorate([
  46559. BABYLON.serialize(),
  46560. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46561. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  46562. __decorate([
  46563. BABYLON.serialize(),
  46564. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46565. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  46566. __decorate([
  46567. BABYLON.serializeAsTexture(),
  46568. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  46569. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  46570. __decorate([
  46571. BABYLON.serializeAsColor3("emissive"),
  46572. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46573. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  46574. __decorate([
  46575. BABYLON.serializeAsTexture(),
  46576. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46577. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  46578. __decorate([
  46579. BABYLON.serialize(),
  46580. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  46581. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  46582. __decorate([
  46583. BABYLON.serializeAsTexture(),
  46584. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  46585. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  46586. __decorate([
  46587. BABYLON.serialize(),
  46588. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  46589. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  46590. __decorate([
  46591. BABYLON.serialize()
  46592. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  46593. __decorate([
  46594. BABYLON.serializeAsTexture(),
  46595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46596. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  46597. __decorate([
  46598. BABYLON.serialize(),
  46599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46600. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46601. return PBRBaseSimpleMaterial;
  46602. }(BABYLON.PBRBaseMaterial));
  46603. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  46604. })(BABYLON || (BABYLON = {}));
  46605. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  46606. var BABYLON;
  46607. (function (BABYLON) {
  46608. /**
  46609. * The Physically based material of BJS.
  46610. *
  46611. * This offers the main features of a standard PBR material.
  46612. * For more information, please refer to the documentation :
  46613. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  46614. */
  46615. var PBRMaterial = /** @class */ (function (_super) {
  46616. __extends(PBRMaterial, _super);
  46617. /**
  46618. * Instantiates a new PBRMaterial instance.
  46619. *
  46620. * @param name The material name
  46621. * @param scene The scene the material will be use in.
  46622. */
  46623. function PBRMaterial(name, scene) {
  46624. var _this = _super.call(this, name, scene) || this;
  46625. /**
  46626. * Intensity of the direct lights e.g. the four lights available in your scene.
  46627. * This impacts both the direct diffuse and specular highlights.
  46628. */
  46629. _this.directIntensity = 1.0;
  46630. /**
  46631. * Intensity of the emissive part of the material.
  46632. * This helps controlling the emissive effect without modifying the emissive color.
  46633. */
  46634. _this.emissiveIntensity = 1.0;
  46635. /**
  46636. * Intensity of the environment e.g. how much the environment will light the object
  46637. * either through harmonics for rough material or through the refelction for shiny ones.
  46638. */
  46639. _this.environmentIntensity = 1.0;
  46640. /**
  46641. * This is a special control allowing the reduction of the specular highlights coming from the
  46642. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  46643. */
  46644. _this.specularIntensity = 1.0;
  46645. /**
  46646. * Debug Control allowing disabling the bump map on this material.
  46647. */
  46648. _this.disableBumpMap = false;
  46649. /**
  46650. * AKA Occlusion Texture Intensity in other nomenclature.
  46651. */
  46652. _this.ambientTextureStrength = 1.0;
  46653. /**
  46654. * Defines how much the AO map is occluding the analytical lights (point spot...).
  46655. * 1 means it completely occludes it
  46656. * 0 mean it has no impact
  46657. */
  46658. _this.ambientTextureImpactOnAnalyticalLights = PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS;
  46659. /**
  46660. * The color of a material in ambient lighting.
  46661. */
  46662. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  46663. /**
  46664. * AKA Diffuse Color in other nomenclature.
  46665. */
  46666. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  46667. /**
  46668. * AKA Specular Color in other nomenclature.
  46669. */
  46670. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  46671. /**
  46672. * The color reflected from the material.
  46673. */
  46674. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  46675. /**
  46676. * The color emitted from the material.
  46677. */
  46678. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  46679. /**
  46680. * AKA Glossiness in other nomenclature.
  46681. */
  46682. _this.microSurface = 1.0;
  46683. /**
  46684. * source material index of refraction (IOR)' / 'destination material IOR.
  46685. */
  46686. _this.indexOfRefraction = 0.66;
  46687. /**
  46688. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  46689. */
  46690. _this.invertRefractionY = false;
  46691. /**
  46692. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  46693. * Materials half opaque for instance using refraction could benefit from this control.
  46694. */
  46695. _this.linkRefractionWithTransparency = false;
  46696. /**
  46697. * If true, the light map contains occlusion information instead of lighting info.
  46698. */
  46699. _this.useLightmapAsShadowmap = false;
  46700. /**
  46701. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  46702. */
  46703. _this.useAlphaFromAlbedoTexture = false;
  46704. /**
  46705. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  46706. */
  46707. _this.forceAlphaTest = false;
  46708. /**
  46709. * Defines the alpha limits in alpha test mode.
  46710. */
  46711. _this.alphaCutOff = 0.4;
  46712. /**
  46713. * Specifies that the material will keep the specular highlights over a transparent surface (only the most limunous ones).
  46714. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46715. */
  46716. _this.useSpecularOverAlpha = true;
  46717. /**
  46718. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46719. */
  46720. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46721. /**
  46722. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46723. */
  46724. _this.useRoughnessFromMetallicTextureAlpha = true;
  46725. /**
  46726. * Specifies if the metallic texture contains the roughness information in its green channel.
  46727. */
  46728. _this.useRoughnessFromMetallicTextureGreen = false;
  46729. /**
  46730. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46731. */
  46732. _this.useMetallnessFromMetallicTextureBlue = false;
  46733. /**
  46734. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46735. */
  46736. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46737. /**
  46738. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46739. */
  46740. _this.useAmbientInGrayScale = false;
  46741. /**
  46742. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46743. * The material will try to infer what glossiness each pixel should be.
  46744. */
  46745. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46746. /**
  46747. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46748. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46749. */
  46750. _this.useRadianceOverAlpha = true;
  46751. /**
  46752. * Allows using an object space normal map (instead of tangent space).
  46753. */
  46754. _this.useObjectSpaceNormalMap = false;
  46755. /**
  46756. * Allows using the bump map in parallax mode.
  46757. */
  46758. _this.useParallax = false;
  46759. /**
  46760. * Allows using the bump map in parallax occlusion mode.
  46761. */
  46762. _this.useParallaxOcclusion = false;
  46763. /**
  46764. * Controls the scale bias of the parallax mode.
  46765. */
  46766. _this.parallaxScaleBias = 0.05;
  46767. /**
  46768. * If sets to true, disables all the lights affecting the material.
  46769. */
  46770. _this.disableLighting = false;
  46771. /**
  46772. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46773. */
  46774. _this.forceIrradianceInFragment = false;
  46775. /**
  46776. * Number of Simultaneous lights allowed on the material.
  46777. */
  46778. _this.maxSimultaneousLights = 4;
  46779. /**
  46780. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46781. */
  46782. _this.invertNormalMapX = false;
  46783. /**
  46784. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46785. */
  46786. _this.invertNormalMapY = false;
  46787. /**
  46788. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46789. */
  46790. _this.twoSidedLighting = false;
  46791. /**
  46792. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46793. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46794. */
  46795. _this.useAlphaFresnel = false;
  46796. /**
  46797. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46798. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46799. */
  46800. _this.useLinearAlphaFresnel = false;
  46801. /**
  46802. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46803. * And/Or occlude the blended part.
  46804. */
  46805. _this.environmentBRDFTexture = null;
  46806. /**
  46807. * Force normal to face away from face.
  46808. */
  46809. _this.forceNormalForward = false;
  46810. /**
  46811. * Enables specular anti aliasing in the PBR shader.
  46812. * It will both interacts on the Geometry for analytical and IBL lighting.
  46813. * It also prefilter the roughness map based on the bump values.
  46814. */
  46815. _this.enableSpecularAntiAliasing = false;
  46816. /**
  46817. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46818. * makes the reflect vector face the model (under horizon).
  46819. */
  46820. _this.useHorizonOcclusion = true;
  46821. /**
  46822. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46823. * too much the area relying on ambient texture to define their ambient occlusion.
  46824. */
  46825. _this.useRadianceOcclusion = true;
  46826. /**
  46827. * If set to true, no lighting calculations will be applied.
  46828. */
  46829. _this.unlit = false;
  46830. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46831. return _this;
  46832. }
  46833. Object.defineProperty(PBRMaterial.prototype, "usePhysicalLightFalloff", {
  46834. /**
  46835. * BJS is using an harcoded light falloff based on a manually sets up range.
  46836. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46837. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46838. */
  46839. get: function () {
  46840. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46841. },
  46842. /**
  46843. * BJS is using an harcoded light falloff based on a manually sets up range.
  46844. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46845. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46846. */
  46847. set: function (value) {
  46848. if (value !== this.usePhysicalLightFalloff) {
  46849. // Ensure the effect will be rebuilt.
  46850. this._markAllSubMeshesAsTexturesDirty();
  46851. if (value) {
  46852. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_PHYSICAL;
  46853. }
  46854. else {
  46855. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46856. }
  46857. }
  46858. },
  46859. enumerable: true,
  46860. configurable: true
  46861. });
  46862. Object.defineProperty(PBRMaterial.prototype, "useGLTFLightFalloff", {
  46863. /**
  46864. * In order to support the falloff compatibility with gltf, a special mode has been added
  46865. * to reproduce the gltf light falloff.
  46866. */
  46867. get: function () {
  46868. return this._lightFalloff === BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46869. },
  46870. /**
  46871. * In order to support the falloff compatibility with gltf, a special mode has been added
  46872. * to reproduce the gltf light falloff.
  46873. */
  46874. set: function (value) {
  46875. if (value !== this.useGLTFLightFalloff) {
  46876. // Ensure the effect will be rebuilt.
  46877. this._markAllSubMeshesAsTexturesDirty();
  46878. if (value) {
  46879. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_GLTF;
  46880. }
  46881. else {
  46882. this._lightFalloff = BABYLON.PBRBaseMaterial.LIGHTFALLOFF_STANDARD;
  46883. }
  46884. }
  46885. },
  46886. enumerable: true,
  46887. configurable: true
  46888. });
  46889. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46890. /**
  46891. * Gets the image processing configuration used either in this material.
  46892. */
  46893. get: function () {
  46894. return this._imageProcessingConfiguration;
  46895. },
  46896. /**
  46897. * Sets the Default image processing configuration used either in the this material.
  46898. *
  46899. * If sets to null, the scene one is in use.
  46900. */
  46901. set: function (value) {
  46902. this._attachImageProcessingConfiguration(value);
  46903. // Ensure the effect will be rebuilt.
  46904. this._markAllSubMeshesAsTexturesDirty();
  46905. },
  46906. enumerable: true,
  46907. configurable: true
  46908. });
  46909. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46910. /**
  46911. * Gets wether the color curves effect is enabled.
  46912. */
  46913. get: function () {
  46914. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46915. },
  46916. /**
  46917. * Sets wether the color curves effect is enabled.
  46918. */
  46919. set: function (value) {
  46920. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46921. },
  46922. enumerable: true,
  46923. configurable: true
  46924. });
  46925. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46926. /**
  46927. * Gets wether the color grading effect is enabled.
  46928. */
  46929. get: function () {
  46930. return this.imageProcessingConfiguration.colorGradingEnabled;
  46931. },
  46932. /**
  46933. * Gets wether the color grading effect is enabled.
  46934. */
  46935. set: function (value) {
  46936. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46937. },
  46938. enumerable: true,
  46939. configurable: true
  46940. });
  46941. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46942. /**
  46943. * Gets wether tonemapping is enabled or not.
  46944. */
  46945. get: function () {
  46946. return this._imageProcessingConfiguration.toneMappingEnabled;
  46947. },
  46948. /**
  46949. * Sets wether tonemapping is enabled or not
  46950. */
  46951. set: function (value) {
  46952. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46953. },
  46954. enumerable: true,
  46955. configurable: true
  46956. });
  46957. ;
  46958. ;
  46959. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46960. /**
  46961. * The camera exposure used on this material.
  46962. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46963. * This corresponds to a photographic exposure.
  46964. */
  46965. get: function () {
  46966. return this._imageProcessingConfiguration.exposure;
  46967. },
  46968. /**
  46969. * The camera exposure used on this material.
  46970. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46971. * This corresponds to a photographic exposure.
  46972. */
  46973. set: function (value) {
  46974. this._imageProcessingConfiguration.exposure = value;
  46975. },
  46976. enumerable: true,
  46977. configurable: true
  46978. });
  46979. ;
  46980. ;
  46981. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46982. /**
  46983. * Gets The camera contrast used on this material.
  46984. */
  46985. get: function () {
  46986. return this._imageProcessingConfiguration.contrast;
  46987. },
  46988. /**
  46989. * Sets The camera contrast used on this material.
  46990. */
  46991. set: function (value) {
  46992. this._imageProcessingConfiguration.contrast = value;
  46993. },
  46994. enumerable: true,
  46995. configurable: true
  46996. });
  46997. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46998. /**
  46999. * Gets the Color Grading 2D Lookup Texture.
  47000. */
  47001. get: function () {
  47002. return this._imageProcessingConfiguration.colorGradingTexture;
  47003. },
  47004. /**
  47005. * Sets the Color Grading 2D Lookup Texture.
  47006. */
  47007. set: function (value) {
  47008. this._imageProcessingConfiguration.colorGradingTexture = value;
  47009. },
  47010. enumerable: true,
  47011. configurable: true
  47012. });
  47013. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  47014. /**
  47015. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47016. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47017. * 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;
  47018. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47019. */
  47020. get: function () {
  47021. return this._imageProcessingConfiguration.colorCurves;
  47022. },
  47023. /**
  47024. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  47025. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  47026. * 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;
  47027. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  47028. */
  47029. set: function (value) {
  47030. this._imageProcessingConfiguration.colorCurves = value;
  47031. },
  47032. enumerable: true,
  47033. configurable: true
  47034. });
  47035. /**
  47036. * Returns the name of this material class.
  47037. */
  47038. PBRMaterial.prototype.getClassName = function () {
  47039. return "PBRMaterial";
  47040. };
  47041. /**
  47042. * Returns an array of the actively used textures.
  47043. * @returns - Array of BaseTextures
  47044. */
  47045. PBRMaterial.prototype.getActiveTextures = function () {
  47046. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47047. if (this._albedoTexture) {
  47048. activeTextures.push(this._albedoTexture);
  47049. }
  47050. if (this._ambientTexture) {
  47051. activeTextures.push(this._ambientTexture);
  47052. }
  47053. if (this._opacityTexture) {
  47054. activeTextures.push(this._opacityTexture);
  47055. }
  47056. if (this._reflectionTexture) {
  47057. activeTextures.push(this._reflectionTexture);
  47058. }
  47059. if (this._emissiveTexture) {
  47060. activeTextures.push(this._emissiveTexture);
  47061. }
  47062. if (this._reflectivityTexture) {
  47063. activeTextures.push(this._reflectivityTexture);
  47064. }
  47065. if (this._metallicTexture) {
  47066. activeTextures.push(this._metallicTexture);
  47067. }
  47068. if (this._microSurfaceTexture) {
  47069. activeTextures.push(this._microSurfaceTexture);
  47070. }
  47071. if (this._bumpTexture) {
  47072. activeTextures.push(this._bumpTexture);
  47073. }
  47074. if (this._lightmapTexture) {
  47075. activeTextures.push(this._lightmapTexture);
  47076. }
  47077. if (this._refractionTexture) {
  47078. activeTextures.push(this._refractionTexture);
  47079. }
  47080. return activeTextures;
  47081. };
  47082. /**
  47083. * Checks to see if a texture is used in the material.
  47084. * @param texture - Base texture to use.
  47085. * @returns - Boolean specifying if a texture is used in the material.
  47086. */
  47087. PBRMaterial.prototype.hasTexture = function (texture) {
  47088. if (_super.prototype.hasTexture.call(this, texture)) {
  47089. return true;
  47090. }
  47091. if (this._albedoTexture === texture) {
  47092. return true;
  47093. }
  47094. if (this._ambientTexture === texture) {
  47095. return true;
  47096. }
  47097. if (this._opacityTexture === texture) {
  47098. return true;
  47099. }
  47100. if (this._reflectionTexture === texture) {
  47101. return true;
  47102. }
  47103. if (this._reflectivityTexture === texture) {
  47104. return true;
  47105. }
  47106. if (this._metallicTexture === texture) {
  47107. return true;
  47108. }
  47109. if (this._microSurfaceTexture === texture) {
  47110. return true;
  47111. }
  47112. if (this._bumpTexture === texture) {
  47113. return true;
  47114. }
  47115. if (this._lightmapTexture === texture) {
  47116. return true;
  47117. }
  47118. if (this._refractionTexture === texture) {
  47119. return true;
  47120. }
  47121. return false;
  47122. };
  47123. /**
  47124. * Makes a duplicate of the current material.
  47125. * @param name - name to use for the new material.
  47126. */
  47127. PBRMaterial.prototype.clone = function (name) {
  47128. var _this = this;
  47129. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  47130. clone.id = name;
  47131. clone.name = name;
  47132. return clone;
  47133. };
  47134. /**
  47135. * Serializes this PBR Material.
  47136. * @returns - An object with the serialized material.
  47137. */
  47138. PBRMaterial.prototype.serialize = function () {
  47139. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47140. serializationObject.customType = "BABYLON.PBRMaterial";
  47141. return serializationObject;
  47142. };
  47143. // Statics
  47144. /**
  47145. * Parses a PBR Material from a serialized object.
  47146. * @param source - Serialized object.
  47147. * @param scene - BJS scene instance.
  47148. * @param rootUrl - url for the scene object
  47149. * @returns - PBRMaterial
  47150. */
  47151. PBRMaterial.Parse = function (source, scene, rootUrl) {
  47152. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  47153. };
  47154. /**
  47155. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  47156. */
  47157. PBRMaterial.PBRMATERIAL_OPAQUE = 0;
  47158. /**
  47159. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  47160. */
  47161. PBRMaterial.PBRMATERIAL_ALPHATEST = 1;
  47162. /**
  47163. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47164. */
  47165. PBRMaterial.PBRMATERIAL_ALPHABLEND = 2;
  47166. /**
  47167. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  47168. * They are also discarded below the alpha cutoff threshold to improve performances.
  47169. */
  47170. PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND = 3;
  47171. /**
  47172. * Defines the default value of how much AO map is occluding the analytical lights
  47173. * (point spot...).
  47174. */
  47175. PBRMaterial.DEFAULT_AO_ON_ANALYTICAL_LIGHTS = 1;
  47176. __decorate([
  47177. BABYLON.serialize(),
  47178. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47179. ], PBRMaterial.prototype, "directIntensity", void 0);
  47180. __decorate([
  47181. BABYLON.serialize(),
  47182. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47183. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  47184. __decorate([
  47185. BABYLON.serialize(),
  47186. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47187. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  47188. __decorate([
  47189. BABYLON.serialize(),
  47190. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47191. ], PBRMaterial.prototype, "specularIntensity", void 0);
  47192. __decorate([
  47193. BABYLON.serialize(),
  47194. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47195. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  47196. __decorate([
  47197. BABYLON.serializeAsTexture(),
  47198. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47199. ], PBRMaterial.prototype, "albedoTexture", void 0);
  47200. __decorate([
  47201. BABYLON.serializeAsTexture(),
  47202. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47203. ], PBRMaterial.prototype, "ambientTexture", void 0);
  47204. __decorate([
  47205. BABYLON.serialize(),
  47206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47207. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  47208. __decorate([
  47209. BABYLON.serialize(),
  47210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47211. ], PBRMaterial.prototype, "ambientTextureImpactOnAnalyticalLights", void 0);
  47212. __decorate([
  47213. BABYLON.serializeAsTexture(),
  47214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47215. ], PBRMaterial.prototype, "opacityTexture", void 0);
  47216. __decorate([
  47217. BABYLON.serializeAsTexture(),
  47218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47219. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  47220. __decorate([
  47221. BABYLON.serializeAsTexture(),
  47222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47223. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  47224. __decorate([
  47225. BABYLON.serializeAsTexture(),
  47226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47227. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  47228. __decorate([
  47229. BABYLON.serializeAsTexture(),
  47230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47231. ], PBRMaterial.prototype, "metallicTexture", void 0);
  47232. __decorate([
  47233. BABYLON.serialize(),
  47234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47235. ], PBRMaterial.prototype, "metallic", void 0);
  47236. __decorate([
  47237. BABYLON.serialize(),
  47238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47239. ], PBRMaterial.prototype, "roughness", void 0);
  47240. __decorate([
  47241. BABYLON.serializeAsTexture(),
  47242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47243. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  47244. __decorate([
  47245. BABYLON.serializeAsTexture(),
  47246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47247. ], PBRMaterial.prototype, "bumpTexture", void 0);
  47248. __decorate([
  47249. BABYLON.serializeAsTexture(),
  47250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  47251. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  47252. __decorate([
  47253. BABYLON.serializeAsTexture(),
  47254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47255. ], PBRMaterial.prototype, "refractionTexture", void 0);
  47256. __decorate([
  47257. BABYLON.serializeAsColor3("ambient"),
  47258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47259. ], PBRMaterial.prototype, "ambientColor", void 0);
  47260. __decorate([
  47261. BABYLON.serializeAsColor3("albedo"),
  47262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47263. ], PBRMaterial.prototype, "albedoColor", void 0);
  47264. __decorate([
  47265. BABYLON.serializeAsColor3("reflectivity"),
  47266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47267. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  47268. __decorate([
  47269. BABYLON.serializeAsColor3("reflection"),
  47270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47271. ], PBRMaterial.prototype, "reflectionColor", void 0);
  47272. __decorate([
  47273. BABYLON.serializeAsColor3("emissive"),
  47274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47275. ], PBRMaterial.prototype, "emissiveColor", void 0);
  47276. __decorate([
  47277. BABYLON.serialize(),
  47278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47279. ], PBRMaterial.prototype, "microSurface", void 0);
  47280. __decorate([
  47281. BABYLON.serialize(),
  47282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47283. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  47284. __decorate([
  47285. BABYLON.serialize(),
  47286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47287. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  47288. __decorate([
  47289. BABYLON.serialize(),
  47290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47291. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  47292. __decorate([
  47293. BABYLON.serialize(),
  47294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47295. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  47296. __decorate([
  47297. BABYLON.serialize(),
  47298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47299. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  47300. __decorate([
  47301. BABYLON.serialize(),
  47302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47303. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  47304. __decorate([
  47305. BABYLON.serialize(),
  47306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  47307. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  47308. __decorate([
  47309. BABYLON.serialize(),
  47310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47311. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  47312. __decorate([
  47313. BABYLON.serialize(),
  47314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47315. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  47316. __decorate([
  47317. BABYLON.serialize(),
  47318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47319. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  47320. __decorate([
  47321. BABYLON.serialize(),
  47322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47323. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  47324. __decorate([
  47325. BABYLON.serialize(),
  47326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47327. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  47328. __decorate([
  47329. BABYLON.serialize(),
  47330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47331. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  47332. __decorate([
  47333. BABYLON.serialize(),
  47334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47335. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  47336. __decorate([
  47337. BABYLON.serialize(),
  47338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47339. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  47340. __decorate([
  47341. BABYLON.serialize()
  47342. ], PBRMaterial.prototype, "usePhysicalLightFalloff", null);
  47343. __decorate([
  47344. BABYLON.serialize()
  47345. ], PBRMaterial.prototype, "useGLTFLightFalloff", null);
  47346. __decorate([
  47347. BABYLON.serialize(),
  47348. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47349. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  47350. __decorate([
  47351. BABYLON.serialize(),
  47352. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47353. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  47354. __decorate([
  47355. BABYLON.serialize(),
  47356. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47357. ], PBRMaterial.prototype, "useParallax", void 0);
  47358. __decorate([
  47359. BABYLON.serialize(),
  47360. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47361. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  47362. __decorate([
  47363. BABYLON.serialize(),
  47364. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47365. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  47366. __decorate([
  47367. BABYLON.serialize(),
  47368. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47369. ], PBRMaterial.prototype, "disableLighting", void 0);
  47370. __decorate([
  47371. BABYLON.serialize(),
  47372. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47373. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  47374. __decorate([
  47375. BABYLON.serialize(),
  47376. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  47377. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  47378. __decorate([
  47379. BABYLON.serialize(),
  47380. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47381. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  47382. __decorate([
  47383. BABYLON.serialize(),
  47384. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47385. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  47386. __decorate([
  47387. BABYLON.serialize(),
  47388. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47389. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  47390. __decorate([
  47391. BABYLON.serialize(),
  47392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47393. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  47394. __decorate([
  47395. BABYLON.serialize(),
  47396. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47397. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  47398. __decorate([
  47399. BABYLON.serializeAsTexture(),
  47400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47401. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  47402. __decorate([
  47403. BABYLON.serialize(),
  47404. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47405. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  47406. __decorate([
  47407. BABYLON.serialize(),
  47408. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47409. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  47410. __decorate([
  47411. BABYLON.serialize(),
  47412. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47413. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  47414. __decorate([
  47415. BABYLON.serialize(),
  47416. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47417. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  47418. __decorate([
  47419. BABYLON.serialize(),
  47420. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  47421. ], PBRMaterial.prototype, "unlit", void 0);
  47422. return PBRMaterial;
  47423. }(BABYLON.PBRBaseMaterial));
  47424. BABYLON.PBRMaterial = PBRMaterial;
  47425. })(BABYLON || (BABYLON = {}));
  47426. //# sourceMappingURL=babylon.pbrMaterial.js.map
  47427. var BABYLON;
  47428. (function (BABYLON) {
  47429. /**
  47430. * The PBR material of BJS following the metal roughness convention.
  47431. *
  47432. * This fits to the PBR convention in the GLTF definition:
  47433. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  47434. */
  47435. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  47436. __extends(PBRMetallicRoughnessMaterial, _super);
  47437. /**
  47438. * Instantiates a new PBRMetalRoughnessMaterial instance.
  47439. *
  47440. * @param name The material name
  47441. * @param scene The scene the material will be use in.
  47442. */
  47443. function PBRMetallicRoughnessMaterial(name, scene) {
  47444. var _this = _super.call(this, name, scene) || this;
  47445. _this._useRoughnessFromMetallicTextureAlpha = false;
  47446. _this._useRoughnessFromMetallicTextureGreen = true;
  47447. _this._useMetallnessFromMetallicTextureBlue = true;
  47448. _this.metallic = 1.0;
  47449. _this.roughness = 1.0;
  47450. return _this;
  47451. }
  47452. /**
  47453. * Return the currrent class name of the material.
  47454. */
  47455. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  47456. return "PBRMetallicRoughnessMaterial";
  47457. };
  47458. /**
  47459. * Return the active textures of the material.
  47460. */
  47461. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  47462. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47463. if (this.baseTexture) {
  47464. activeTextures.push(this.baseTexture);
  47465. }
  47466. if (this.metallicRoughnessTexture) {
  47467. activeTextures.push(this.metallicRoughnessTexture);
  47468. }
  47469. return activeTextures;
  47470. };
  47471. /**
  47472. * Checks to see if a texture is used in the material.
  47473. * @param texture - Base texture to use.
  47474. * @returns - Boolean specifying if a texture is used in the material.
  47475. */
  47476. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  47477. if (_super.prototype.hasTexture.call(this, texture)) {
  47478. return true;
  47479. }
  47480. if (this.baseTexture === texture) {
  47481. return true;
  47482. }
  47483. if (this.metallicRoughnessTexture === texture) {
  47484. return true;
  47485. }
  47486. return false;
  47487. };
  47488. /**
  47489. * Makes a duplicate of the current material.
  47490. * @param name - name to use for the new material.
  47491. */
  47492. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  47493. var _this = this;
  47494. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  47495. clone.id = name;
  47496. clone.name = name;
  47497. return clone;
  47498. };
  47499. /**
  47500. * Serialize the material to a parsable JSON object.
  47501. */
  47502. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  47503. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47504. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  47505. return serializationObject;
  47506. };
  47507. /**
  47508. * Parses a JSON object correponding to the serialize function.
  47509. */
  47510. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  47511. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  47512. };
  47513. __decorate([
  47514. BABYLON.serializeAsColor3(),
  47515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47516. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  47517. __decorate([
  47518. BABYLON.serializeAsTexture(),
  47519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47520. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  47521. __decorate([
  47522. BABYLON.serialize(),
  47523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47524. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  47525. __decorate([
  47526. BABYLON.serialize(),
  47527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  47528. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  47529. __decorate([
  47530. BABYLON.serializeAsTexture(),
  47531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  47532. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  47533. return PBRMetallicRoughnessMaterial;
  47534. }(BABYLON.PBRBaseSimpleMaterial));
  47535. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  47536. })(BABYLON || (BABYLON = {}));
  47537. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  47538. var BABYLON;
  47539. (function (BABYLON) {
  47540. /**
  47541. * The PBR material of BJS following the specular glossiness convention.
  47542. *
  47543. * This fits to the PBR convention in the GLTF definition:
  47544. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  47545. */
  47546. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  47547. __extends(PBRSpecularGlossinessMaterial, _super);
  47548. /**
  47549. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  47550. *
  47551. * @param name The material name
  47552. * @param scene The scene the material will be use in.
  47553. */
  47554. function PBRSpecularGlossinessMaterial(name, scene) {
  47555. var _this = _super.call(this, name, scene) || this;
  47556. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  47557. return _this;
  47558. }
  47559. /**
  47560. * Return the currrent class name of the material.
  47561. */
  47562. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  47563. return "PBRSpecularGlossinessMaterial";
  47564. };
  47565. /**
  47566. * Return the active textures of the material.
  47567. */
  47568. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  47569. var activeTextures = _super.prototype.getActiveTextures.call(this);
  47570. if (this.diffuseTexture) {
  47571. activeTextures.push(this.diffuseTexture);
  47572. }
  47573. if (this.specularGlossinessTexture) {
  47574. activeTextures.push(this.specularGlossinessTexture);
  47575. }
  47576. return activeTextures;
  47577. };
  47578. /**
  47579. * Checks to see if a texture is used in the material.
  47580. * @param texture - Base texture to use.
  47581. * @returns - Boolean specifying if a texture is used in the material.
  47582. */
  47583. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  47584. if (_super.prototype.hasTexture.call(this, texture)) {
  47585. return true;
  47586. }
  47587. if (this.diffuseTexture === texture) {
  47588. return true;
  47589. }
  47590. if (this.specularGlossinessTexture === texture) {
  47591. return true;
  47592. }
  47593. return false;
  47594. };
  47595. /**
  47596. * Makes a duplicate of the current material.
  47597. * @param name - name to use for the new material.
  47598. */
  47599. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  47600. var _this = this;
  47601. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  47602. clone.id = name;
  47603. clone.name = name;
  47604. return clone;
  47605. };
  47606. /**
  47607. * Serialize the material to a parsable JSON object.
  47608. */
  47609. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  47610. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  47611. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  47612. return serializationObject;
  47613. };
  47614. /**
  47615. * Parses a JSON object correponding to the serialize function.
  47616. */
  47617. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  47618. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  47619. };
  47620. __decorate([
  47621. BABYLON.serializeAsColor3("diffuse"),
  47622. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  47623. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  47624. __decorate([
  47625. BABYLON.serializeAsTexture(),
  47626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  47627. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  47628. __decorate([
  47629. BABYLON.serializeAsColor3("specular"),
  47630. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  47631. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  47632. __decorate([
  47633. BABYLON.serialize(),
  47634. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  47635. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  47636. __decorate([
  47637. BABYLON.serializeAsTexture(),
  47638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  47639. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  47640. return PBRSpecularGlossinessMaterial;
  47641. }(BABYLON.PBRBaseSimpleMaterial));
  47642. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  47643. })(BABYLON || (BABYLON = {}));
  47644. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  47645. var BABYLON;
  47646. (function (BABYLON) {
  47647. /**
  47648. * @ignore
  47649. * This is a list of all the different input types that are available in the application.
  47650. * Fo instance: ArcRotateCameraGamepadInput...
  47651. */
  47652. BABYLON.CameraInputTypes = {};
  47653. /**
  47654. * This represents the input manager used within a camera.
  47655. * It helps dealing with all the different kind of input attached to a camera.
  47656. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47657. */
  47658. var CameraInputsManager = /** @class */ (function () {
  47659. /**
  47660. * Instantiate a new Camera Input Manager.
  47661. * @param camera Defines the camera the input manager blongs to
  47662. */
  47663. function CameraInputsManager(camera) {
  47664. this.attached = {};
  47665. this.camera = camera;
  47666. this.checkInputs = function () { };
  47667. }
  47668. /**
  47669. * Add an input method to a camera
  47670. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  47671. * @param input camera input method
  47672. */
  47673. CameraInputsManager.prototype.add = function (input) {
  47674. var type = input.getSimpleName();
  47675. if (this.attached[type]) {
  47676. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  47677. return;
  47678. }
  47679. this.attached[type] = input;
  47680. input.camera = this.camera;
  47681. //for checkInputs, we are dynamically creating a function
  47682. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  47683. if (input.checkInputs) {
  47684. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47685. }
  47686. if (this.attachedElement) {
  47687. input.attachControl(this.attachedElement);
  47688. }
  47689. };
  47690. /**
  47691. * Remove a specific input method from a camera
  47692. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  47693. * @param inputToRemove camera input method
  47694. */
  47695. CameraInputsManager.prototype.remove = function (inputToRemove) {
  47696. for (var cam in this.attached) {
  47697. var input = this.attached[cam];
  47698. if (input === inputToRemove) {
  47699. input.detachControl(this.attachedElement);
  47700. input.camera = null;
  47701. delete this.attached[cam];
  47702. this.rebuildInputCheck();
  47703. }
  47704. }
  47705. };
  47706. /**
  47707. * Remove a specific input type from a camera
  47708. * example: camera.inputs.remove("ArcRotateCameraGamepadInput");
  47709. * @param inputType the type of the input to remove
  47710. */
  47711. CameraInputsManager.prototype.removeByType = function (inputType) {
  47712. for (var cam in this.attached) {
  47713. var input = this.attached[cam];
  47714. if (input.getClassName() === inputType) {
  47715. input.detachControl(this.attachedElement);
  47716. input.camera = null;
  47717. delete this.attached[cam];
  47718. this.rebuildInputCheck();
  47719. }
  47720. }
  47721. };
  47722. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  47723. var current = this.checkInputs;
  47724. return function () {
  47725. current();
  47726. fn();
  47727. };
  47728. };
  47729. /**
  47730. * Attach the input controls to the currently attached dom element to listen the events from.
  47731. * @param input Defines the input to attach
  47732. */
  47733. CameraInputsManager.prototype.attachInput = function (input) {
  47734. if (this.attachedElement) {
  47735. input.attachControl(this.attachedElement, this.noPreventDefault);
  47736. }
  47737. };
  47738. /**
  47739. * Attach the current manager inputs controls to a specific dom element to listen the events from.
  47740. * @param element Defines the dom element to collect the events from
  47741. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  47742. */
  47743. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  47744. if (noPreventDefault === void 0) { noPreventDefault = false; }
  47745. if (this.attachedElement) {
  47746. return;
  47747. }
  47748. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  47749. this.attachedElement = element;
  47750. this.noPreventDefault = noPreventDefault;
  47751. for (var cam in this.attached) {
  47752. this.attached[cam].attachControl(element, noPreventDefault);
  47753. }
  47754. };
  47755. /**
  47756. * Detach the current manager inputs controls from a specific dom element.
  47757. * @param element Defines the dom element to collect the events from
  47758. * @param disconnect Defines whether the input should be removed from the current list of attached inputs
  47759. */
  47760. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  47761. if (disconnect === void 0) { disconnect = false; }
  47762. if (this.attachedElement !== element) {
  47763. return;
  47764. }
  47765. for (var cam in this.attached) {
  47766. this.attached[cam].detachControl(element);
  47767. if (disconnect) {
  47768. this.attached[cam].camera = null;
  47769. }
  47770. }
  47771. this.attachedElement = null;
  47772. };
  47773. /**
  47774. * Rebuild the dynamic inputCheck function from the current list of
  47775. * defined inputs in the manager.
  47776. */
  47777. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47778. this.checkInputs = function () { };
  47779. for (var cam in this.attached) {
  47780. var input = this.attached[cam];
  47781. if (input.checkInputs) {
  47782. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47783. }
  47784. }
  47785. };
  47786. /**
  47787. * Remove all attached input methods from a camera
  47788. */
  47789. CameraInputsManager.prototype.clear = function () {
  47790. if (this.attachedElement) {
  47791. this.detachElement(this.attachedElement, true);
  47792. }
  47793. this.attached = {};
  47794. this.attachedElement = null;
  47795. this.checkInputs = function () { };
  47796. };
  47797. /**
  47798. * Serialize the current input manager attached to a camera.
  47799. * This ensures than once parsed,
  47800. * the input associated to the camera will be identical to the current ones
  47801. * @param serializedCamera Defines the camera serialization JSON the input serialization should write to
  47802. */
  47803. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47804. var inputs = {};
  47805. for (var cam in this.attached) {
  47806. var input = this.attached[cam];
  47807. var res = BABYLON.SerializationHelper.Serialize(input);
  47808. inputs[input.getClassName()] = res;
  47809. }
  47810. serializedCamera.inputsmgr = inputs;
  47811. };
  47812. /**
  47813. * Parses an input manager serialized JSON to restore the previous list of inputs
  47814. * and states associated to a camera.
  47815. * @param parsedCamera Defines the JSON to parse
  47816. */
  47817. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47818. var parsedInputs = parsedCamera.inputsmgr;
  47819. if (parsedInputs) {
  47820. this.clear();
  47821. for (var n in parsedInputs) {
  47822. var construct = BABYLON.CameraInputTypes[n];
  47823. if (construct) {
  47824. var parsedinput = parsedInputs[n];
  47825. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47826. this.add(input);
  47827. }
  47828. }
  47829. }
  47830. else {
  47831. //2016-03-08 this part is for managing backward compatibility
  47832. for (var n in this.attached) {
  47833. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47834. if (construct) {
  47835. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47836. this.remove(this.attached[n]);
  47837. this.add(input);
  47838. }
  47839. }
  47840. }
  47841. };
  47842. return CameraInputsManager;
  47843. }());
  47844. BABYLON.CameraInputsManager = CameraInputsManager;
  47845. })(BABYLON || (BABYLON = {}));
  47846. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47847. var BABYLON;
  47848. (function (BABYLON) {
  47849. /**
  47850. * A target camera takes a mesh or position as a target and continues to look at it while it moves.
  47851. * This is the base of the follow, arc rotate cameras and Free camera
  47852. * @see http://doc.babylonjs.com/features/cameras
  47853. */
  47854. var TargetCamera = /** @class */ (function (_super) {
  47855. __extends(TargetCamera, _super);
  47856. /**
  47857. * Instantiates a target camera that takes a meshor position as a target and continues to look at it while it moves.
  47858. * This is the base of the follow, arc rotate cameras and Free camera
  47859. * @see http://doc.babylonjs.com/features/cameras
  47860. * @param name Defines the name of the camera in the scene
  47861. * @param position Defines the start position of the camera in the scene
  47862. * @param scene Defines the scene the camera belongs to
  47863. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  47864. */
  47865. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47866. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47867. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47868. /**
  47869. * Define the current direction the camera is moving to
  47870. */
  47871. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47872. /**
  47873. * Define the current rotation the camera is rotating to
  47874. */
  47875. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47876. /**
  47877. * Define the current rotation of the camera
  47878. */
  47879. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47880. /**
  47881. * Define the current speed of the camera
  47882. */
  47883. _this.speed = 2.0;
  47884. /**
  47885. * Add cconstraint to the camera to prevent it to move freely in all directions and
  47886. * around all axis.
  47887. */
  47888. _this.noRotationConstraint = false;
  47889. /**
  47890. * Define the current target of the camera as an object or a position.
  47891. */
  47892. _this.lockedTarget = null;
  47893. /** @hidden */
  47894. _this._currentTarget = BABYLON.Vector3.Zero();
  47895. /** @hidden */
  47896. _this._viewMatrix = BABYLON.Matrix.Zero();
  47897. /** @hidden */
  47898. _this._camMatrix = BABYLON.Matrix.Zero();
  47899. /** @hidden */
  47900. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47901. /** @hidden */
  47902. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47903. /** @hidden */
  47904. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47905. /** @hidden */
  47906. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47907. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47908. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47909. _this._defaultUp = BABYLON.Vector3.Up();
  47910. _this._cachedRotationZ = 0;
  47911. _this._cachedQuaternionRotationZ = 0;
  47912. return _this;
  47913. }
  47914. /**
  47915. * Gets the position in front of the camera at a given distance.
  47916. * @param distance The distance from the camera we want the position to be
  47917. * @returns the position
  47918. */
  47919. TargetCamera.prototype.getFrontPosition = function (distance) {
  47920. this.getWorldMatrix();
  47921. var direction = this.getTarget().subtract(this.position);
  47922. direction.normalize();
  47923. direction.scaleInPlace(distance);
  47924. return this.globalPosition.add(direction);
  47925. };
  47926. /** @hidden */
  47927. TargetCamera.prototype._getLockedTargetPosition = function () {
  47928. if (!this.lockedTarget) {
  47929. return null;
  47930. }
  47931. if (this.lockedTarget.absolutePosition) {
  47932. this.lockedTarget.computeWorldMatrix();
  47933. }
  47934. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47935. };
  47936. /**
  47937. * Store current camera state of the camera (fov, position, rotation, etc..)
  47938. * @returns the camera
  47939. */
  47940. TargetCamera.prototype.storeState = function () {
  47941. this._storedPosition = this.position.clone();
  47942. this._storedRotation = this.rotation.clone();
  47943. if (this.rotationQuaternion) {
  47944. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47945. }
  47946. return _super.prototype.storeState.call(this);
  47947. };
  47948. /**
  47949. * Restored camera state. You must call storeState() first
  47950. * @returns whether it was successful or not
  47951. * @hidden
  47952. */
  47953. TargetCamera.prototype._restoreStateValues = function () {
  47954. if (!_super.prototype._restoreStateValues.call(this)) {
  47955. return false;
  47956. }
  47957. this.position = this._storedPosition.clone();
  47958. this.rotation = this._storedRotation.clone();
  47959. if (this.rotationQuaternion) {
  47960. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47961. }
  47962. this.cameraDirection.copyFromFloats(0, 0, 0);
  47963. this.cameraRotation.copyFromFloats(0, 0);
  47964. return true;
  47965. };
  47966. /** @hidden */
  47967. TargetCamera.prototype._initCache = function () {
  47968. _super.prototype._initCache.call(this);
  47969. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47970. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47971. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47972. };
  47973. /** @hidden */
  47974. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47975. if (!ignoreParentClass) {
  47976. _super.prototype._updateCache.call(this);
  47977. }
  47978. var lockedTargetPosition = this._getLockedTargetPosition();
  47979. if (!lockedTargetPosition) {
  47980. this._cache.lockedTarget = null;
  47981. }
  47982. else {
  47983. if (!this._cache.lockedTarget) {
  47984. this._cache.lockedTarget = lockedTargetPosition.clone();
  47985. }
  47986. else {
  47987. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47988. }
  47989. }
  47990. this._cache.rotation.copyFrom(this.rotation);
  47991. if (this.rotationQuaternion)
  47992. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47993. };
  47994. // Synchronized
  47995. /** @hidden */
  47996. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47997. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47998. return false;
  47999. }
  48000. var lockedTargetPosition = this._getLockedTargetPosition();
  48001. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  48002. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  48003. };
  48004. // Methods
  48005. /** @hidden */
  48006. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  48007. var engine = this.getEngine();
  48008. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  48009. };
  48010. // Target
  48011. /** @hidden */
  48012. TargetCamera.prototype.setTarget = function (target) {
  48013. this.upVector.normalize();
  48014. if (this.position.z === target.z) {
  48015. this.position.z += BABYLON.Epsilon;
  48016. }
  48017. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUp, this._camMatrix);
  48018. this._camMatrix.invert();
  48019. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  48020. var vDir = target.subtract(this.position);
  48021. if (vDir.x >= 0.0) {
  48022. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  48023. }
  48024. else {
  48025. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  48026. }
  48027. this.rotation.z = 0;
  48028. if (isNaN(this.rotation.x)) {
  48029. this.rotation.x = 0;
  48030. }
  48031. if (isNaN(this.rotation.y)) {
  48032. this.rotation.y = 0;
  48033. }
  48034. if (isNaN(this.rotation.z)) {
  48035. this.rotation.z = 0;
  48036. }
  48037. if (this.rotationQuaternion) {
  48038. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48039. }
  48040. };
  48041. /**
  48042. * Return the current target position of the camera. This value is expressed in local space.
  48043. * @returns the target position
  48044. */
  48045. TargetCamera.prototype.getTarget = function () {
  48046. return this._currentTarget;
  48047. };
  48048. /** @hidden */
  48049. TargetCamera.prototype._decideIfNeedsToMove = function () {
  48050. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48051. };
  48052. /** @hidden */
  48053. TargetCamera.prototype._updatePosition = function () {
  48054. if (this.parent) {
  48055. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  48056. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  48057. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  48058. return;
  48059. }
  48060. this.position.addInPlace(this.cameraDirection);
  48061. };
  48062. /** @hidden */
  48063. TargetCamera.prototype._checkInputs = function () {
  48064. var needToMove = this._decideIfNeedsToMove();
  48065. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  48066. // Move
  48067. if (needToMove) {
  48068. this._updatePosition();
  48069. }
  48070. // Rotate
  48071. if (needToRotate) {
  48072. this.rotation.x += this.cameraRotation.x;
  48073. this.rotation.y += this.cameraRotation.y;
  48074. //rotate, if quaternion is set and rotation was used
  48075. if (this.rotationQuaternion) {
  48076. var len = this.rotation.lengthSquared();
  48077. if (len) {
  48078. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  48079. }
  48080. }
  48081. if (!this.noRotationConstraint) {
  48082. var limit = (Math.PI / 2) * 0.95;
  48083. if (this.rotation.x > limit)
  48084. this.rotation.x = limit;
  48085. if (this.rotation.x < -limit)
  48086. this.rotation.x = -limit;
  48087. }
  48088. }
  48089. // Inertia
  48090. if (needToMove) {
  48091. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  48092. this.cameraDirection.x = 0;
  48093. }
  48094. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  48095. this.cameraDirection.y = 0;
  48096. }
  48097. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  48098. this.cameraDirection.z = 0;
  48099. }
  48100. this.cameraDirection.scaleInPlace(this.inertia);
  48101. }
  48102. if (needToRotate) {
  48103. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  48104. this.cameraRotation.x = 0;
  48105. }
  48106. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  48107. this.cameraRotation.y = 0;
  48108. }
  48109. this.cameraRotation.scaleInPlace(this.inertia);
  48110. }
  48111. _super.prototype._checkInputs.call(this);
  48112. };
  48113. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  48114. if (this.rotationQuaternion) {
  48115. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  48116. }
  48117. else {
  48118. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  48119. }
  48120. };
  48121. /**
  48122. * 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)
  48123. * @returns the current camera
  48124. */
  48125. TargetCamera.prototype._rotateUpVectorWithCameraRotationMatrix = function () {
  48126. BABYLON.Vector3.TransformNormalToRef(this._defaultUp, this._cameraRotationMatrix, this.upVector);
  48127. return this;
  48128. };
  48129. /** @hidden */
  48130. TargetCamera.prototype._getViewMatrix = function () {
  48131. if (this.lockedTarget) {
  48132. this.setTarget(this._getLockedTargetPosition());
  48133. }
  48134. // Compute
  48135. this._updateCameraRotationMatrix();
  48136. // Apply the changed rotation to the upVector
  48137. if (this.rotationQuaternion && this._cachedQuaternionRotationZ != this.rotationQuaternion.z) {
  48138. this._rotateUpVectorWithCameraRotationMatrix();
  48139. this._cachedQuaternionRotationZ = this.rotationQuaternion.z;
  48140. }
  48141. else if (this._cachedRotationZ != this.rotation.z) {
  48142. this._rotateUpVectorWithCameraRotationMatrix();
  48143. this._cachedRotationZ = this.rotation.z;
  48144. }
  48145. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  48146. // Computing target and final matrix
  48147. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  48148. this._computeViewMatrix(this.position, this._currentTarget, this.upVector);
  48149. return this._viewMatrix;
  48150. };
  48151. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  48152. if (this.parent) {
  48153. var parentWorldMatrix = this.parent.getWorldMatrix();
  48154. BABYLON.Vector3.TransformCoordinatesToRef(position, parentWorldMatrix, this._globalPosition);
  48155. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  48156. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  48157. this._markSyncedWithParent();
  48158. }
  48159. else {
  48160. this._globalPosition.copyFrom(position);
  48161. this._globalCurrentTarget.copyFrom(target);
  48162. this._globalCurrentUpVector.copyFrom(up);
  48163. }
  48164. if (this.getScene().useRightHandedSystem) {
  48165. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48166. }
  48167. else {
  48168. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  48169. }
  48170. };
  48171. /**
  48172. * @hidden
  48173. */
  48174. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48175. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  48176. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  48177. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  48178. if (!this.rotationQuaternion) {
  48179. this.rotationQuaternion = new BABYLON.Quaternion();
  48180. }
  48181. rigCamera._cameraRigParams = {};
  48182. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  48183. }
  48184. return rigCamera;
  48185. }
  48186. return null;
  48187. };
  48188. /**
  48189. * @hidden
  48190. */
  48191. TargetCamera.prototype._updateRigCameras = function () {
  48192. var camLeft = this._rigCameras[0];
  48193. var camRight = this._rigCameras[1];
  48194. switch (this.cameraRigMode) {
  48195. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48196. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48197. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48198. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48199. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  48200. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  48201. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  48202. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  48203. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  48204. camLeft.setTarget(this.getTarget());
  48205. camRight.setTarget(this.getTarget());
  48206. break;
  48207. case BABYLON.Camera.RIG_MODE_VR:
  48208. if (camLeft.rotationQuaternion) {
  48209. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48210. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  48211. }
  48212. else {
  48213. camLeft.rotation.copyFrom(this.rotation);
  48214. camRight.rotation.copyFrom(this.rotation);
  48215. }
  48216. camLeft.position.copyFrom(this.position);
  48217. camRight.position.copyFrom(this.position);
  48218. break;
  48219. }
  48220. _super.prototype._updateRigCameras.call(this);
  48221. };
  48222. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  48223. if (!this._rigCamTransformMatrix) {
  48224. this._rigCamTransformMatrix = new BABYLON.Matrix();
  48225. }
  48226. var target = this.getTarget();
  48227. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  48228. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  48229. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  48230. };
  48231. /**
  48232. * Gets the current object class name.
  48233. * @return the class name
  48234. */
  48235. TargetCamera.prototype.getClassName = function () {
  48236. return "TargetCamera";
  48237. };
  48238. __decorate([
  48239. BABYLON.serializeAsVector3()
  48240. ], TargetCamera.prototype, "rotation", void 0);
  48241. __decorate([
  48242. BABYLON.serialize()
  48243. ], TargetCamera.prototype, "speed", void 0);
  48244. __decorate([
  48245. BABYLON.serializeAsMeshReference("lockedTargetId")
  48246. ], TargetCamera.prototype, "lockedTarget", void 0);
  48247. return TargetCamera;
  48248. }(BABYLON.Camera));
  48249. BABYLON.TargetCamera = TargetCamera;
  48250. })(BABYLON || (BABYLON = {}));
  48251. //# sourceMappingURL=babylon.targetCamera.js.map
  48252. var BABYLON;
  48253. (function (BABYLON) {
  48254. /**
  48255. * Manage the mouse inputs to control the movement of a free camera.
  48256. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48257. */
  48258. var FreeCameraMouseInput = /** @class */ (function () {
  48259. /**
  48260. * Manage the mouse inputs to control the movement of a free camera.
  48261. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48262. * @param touchEnabled Defines if touch is enabled or not
  48263. */
  48264. function FreeCameraMouseInput(
  48265. /**
  48266. * Define if touch is enabled in the mouse input
  48267. */
  48268. touchEnabled) {
  48269. if (touchEnabled === void 0) { touchEnabled = true; }
  48270. this.touchEnabled = touchEnabled;
  48271. /**
  48272. * Defines the buttons associated with the input to handle camera move.
  48273. */
  48274. this.buttons = [0, 1, 2];
  48275. /**
  48276. * Defines the pointer angular sensibility along the X and Y axis or how fast is the camera rotating.
  48277. */
  48278. this.angularSensibility = 2000.0;
  48279. this.previousPosition = null;
  48280. }
  48281. /**
  48282. * Attach the input controls to a specific dom element to get the input from.
  48283. * @param element Defines the element the controls should be listened from
  48284. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48285. */
  48286. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  48287. var _this = this;
  48288. var engine = this.camera.getEngine();
  48289. if (!this._pointerInput) {
  48290. this._pointerInput = function (p, s) {
  48291. var evt = p.event;
  48292. if (engine.isInVRExclusivePointerMode) {
  48293. return;
  48294. }
  48295. if (!_this.touchEnabled && evt.pointerType === "touch") {
  48296. return;
  48297. }
  48298. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48299. return;
  48300. }
  48301. var srcElement = (evt.srcElement || evt.target);
  48302. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48303. try {
  48304. srcElement.setPointerCapture(evt.pointerId);
  48305. }
  48306. catch (e) {
  48307. //Nothing to do with the error. Execution will continue.
  48308. }
  48309. _this.previousPosition = {
  48310. x: evt.clientX,
  48311. y: evt.clientY
  48312. };
  48313. if (!noPreventDefault) {
  48314. evt.preventDefault();
  48315. element.focus();
  48316. }
  48317. }
  48318. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48319. try {
  48320. srcElement.releasePointerCapture(evt.pointerId);
  48321. }
  48322. catch (e) {
  48323. //Nothing to do with the error.
  48324. }
  48325. _this.previousPosition = null;
  48326. if (!noPreventDefault) {
  48327. evt.preventDefault();
  48328. }
  48329. }
  48330. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48331. if (!_this.previousPosition || engine.isPointerLock) {
  48332. return;
  48333. }
  48334. var offsetX = evt.clientX - _this.previousPosition.x;
  48335. if (_this.camera.getScene().useRightHandedSystem)
  48336. offsetX *= -1;
  48337. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  48338. offsetX *= -1;
  48339. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48340. var offsetY = evt.clientY - _this.previousPosition.y;
  48341. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48342. _this.previousPosition = {
  48343. x: evt.clientX,
  48344. y: evt.clientY
  48345. };
  48346. if (!noPreventDefault) {
  48347. evt.preventDefault();
  48348. }
  48349. }
  48350. };
  48351. }
  48352. this._onMouseMove = function (evt) {
  48353. if (!engine.isPointerLock) {
  48354. return;
  48355. }
  48356. if (engine.isInVRExclusivePointerMode) {
  48357. return;
  48358. }
  48359. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48360. if (_this.camera.getScene().useRightHandedSystem)
  48361. offsetX *= -1;
  48362. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  48363. offsetX *= -1;
  48364. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  48365. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48366. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  48367. _this.previousPosition = null;
  48368. if (!noPreventDefault) {
  48369. evt.preventDefault();
  48370. }
  48371. };
  48372. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  48373. element.addEventListener("mousemove", this._onMouseMove, false);
  48374. };
  48375. /**
  48376. * Detach the current controls from the specified dom element.
  48377. * @param element Defines the element to stop listening the inputs from
  48378. */
  48379. FreeCameraMouseInput.prototype.detachControl = function (element) {
  48380. if (this._observer && element) {
  48381. this.camera.getScene().onPointerObservable.remove(this._observer);
  48382. if (this._onMouseMove) {
  48383. element.removeEventListener("mousemove", this._onMouseMove);
  48384. }
  48385. this._observer = null;
  48386. this._onMouseMove = null;
  48387. this.previousPosition = null;
  48388. }
  48389. };
  48390. /**
  48391. * Gets the class name of the current intput.
  48392. * @returns the class name
  48393. */
  48394. FreeCameraMouseInput.prototype.getClassName = function () {
  48395. return "FreeCameraMouseInput";
  48396. };
  48397. /**
  48398. * Get the friendly name associated with the input class.
  48399. * @returns the input friendly name
  48400. */
  48401. FreeCameraMouseInput.prototype.getSimpleName = function () {
  48402. return "mouse";
  48403. };
  48404. __decorate([
  48405. BABYLON.serialize()
  48406. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  48407. __decorate([
  48408. BABYLON.serialize()
  48409. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  48410. return FreeCameraMouseInput;
  48411. }());
  48412. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  48413. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  48414. })(BABYLON || (BABYLON = {}));
  48415. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  48416. var BABYLON;
  48417. (function (BABYLON) {
  48418. /**
  48419. * Manage the keyboard inputs to control the movement of a free camera.
  48420. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48421. */
  48422. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  48423. function FreeCameraKeyboardMoveInput() {
  48424. /**
  48425. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48426. */
  48427. this.keysUp = [38];
  48428. /**
  48429. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48430. */
  48431. this.keysDown = [40];
  48432. /**
  48433. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48434. */
  48435. this.keysLeft = [37];
  48436. /**
  48437. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48438. */
  48439. this.keysRight = [39];
  48440. this._keys = new Array();
  48441. }
  48442. /**
  48443. * Attach the input controls to a specific dom element to get the input from.
  48444. * @param element Defines the element the controls should be listened from
  48445. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48446. */
  48447. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48448. var _this = this;
  48449. if (this._onCanvasBlurObserver) {
  48450. return;
  48451. }
  48452. this._scene = this.camera.getScene();
  48453. this._engine = this._scene.getEngine();
  48454. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48455. _this._keys = [];
  48456. });
  48457. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48458. var evt = info.event;
  48459. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48460. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48461. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48462. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48463. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48464. var index = _this._keys.indexOf(evt.keyCode);
  48465. if (index === -1) {
  48466. _this._keys.push(evt.keyCode);
  48467. }
  48468. if (!noPreventDefault) {
  48469. evt.preventDefault();
  48470. }
  48471. }
  48472. }
  48473. else {
  48474. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48475. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48476. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48477. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  48478. var index = _this._keys.indexOf(evt.keyCode);
  48479. if (index >= 0) {
  48480. _this._keys.splice(index, 1);
  48481. }
  48482. if (!noPreventDefault) {
  48483. evt.preventDefault();
  48484. }
  48485. }
  48486. }
  48487. });
  48488. };
  48489. /**
  48490. * Detach the current controls from the specified dom element.
  48491. * @param element Defines the element to stop listening the inputs from
  48492. */
  48493. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  48494. if (this._scene) {
  48495. if (this._onKeyboardObserver) {
  48496. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  48497. }
  48498. if (this._onCanvasBlurObserver) {
  48499. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  48500. }
  48501. this._onKeyboardObserver = null;
  48502. this._onCanvasBlurObserver = null;
  48503. }
  48504. this._keys = [];
  48505. };
  48506. /**
  48507. * Update the current camera state depending on the inputs that have been used this frame.
  48508. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  48509. */
  48510. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  48511. if (this._onKeyboardObserver) {
  48512. var camera = this.camera;
  48513. // Keyboard
  48514. for (var index = 0; index < this._keys.length; index++) {
  48515. var keyCode = this._keys[index];
  48516. var speed = camera._computeLocalCameraSpeed();
  48517. if (this.keysLeft.indexOf(keyCode) !== -1) {
  48518. camera._localDirection.copyFromFloats(-speed, 0, 0);
  48519. }
  48520. else if (this.keysUp.indexOf(keyCode) !== -1) {
  48521. camera._localDirection.copyFromFloats(0, 0, speed);
  48522. }
  48523. else if (this.keysRight.indexOf(keyCode) !== -1) {
  48524. camera._localDirection.copyFromFloats(speed, 0, 0);
  48525. }
  48526. else if (this.keysDown.indexOf(keyCode) !== -1) {
  48527. camera._localDirection.copyFromFloats(0, 0, -speed);
  48528. }
  48529. if (camera.getScene().useRightHandedSystem) {
  48530. camera._localDirection.z *= -1;
  48531. }
  48532. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  48533. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  48534. camera.cameraDirection.addInPlace(camera._transformedDirection);
  48535. }
  48536. }
  48537. };
  48538. /**
  48539. * Gets the class name of the current intput.
  48540. * @returns the class name
  48541. */
  48542. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  48543. return "FreeCameraKeyboardMoveInput";
  48544. };
  48545. /** @hidden */
  48546. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  48547. this._keys = [];
  48548. };
  48549. /**
  48550. * Get the friendly name associated with the input class.
  48551. * @returns the input friendly name
  48552. */
  48553. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48554. return "keyboard";
  48555. };
  48556. __decorate([
  48557. BABYLON.serialize()
  48558. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48559. __decorate([
  48560. BABYLON.serialize()
  48561. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48562. __decorate([
  48563. BABYLON.serialize()
  48564. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48565. __decorate([
  48566. BABYLON.serialize()
  48567. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48568. return FreeCameraKeyboardMoveInput;
  48569. }());
  48570. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  48571. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  48572. })(BABYLON || (BABYLON = {}));
  48573. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  48574. var BABYLON;
  48575. (function (BABYLON) {
  48576. /**
  48577. * Default Inputs manager for the FreeCamera.
  48578. * It groups all the default supported inputs for ease of use.
  48579. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48580. */
  48581. var FreeCameraInputsManager = /** @class */ (function (_super) {
  48582. __extends(FreeCameraInputsManager, _super);
  48583. /**
  48584. * Instantiates a new FreeCameraInputsManager.
  48585. * @param camera Defines the camera the inputs belong to
  48586. */
  48587. function FreeCameraInputsManager(camera) {
  48588. return _super.call(this, camera) || this;
  48589. }
  48590. /**
  48591. * Add keyboard input support to the input manager.
  48592. * @returns the current input manager
  48593. */
  48594. FreeCameraInputsManager.prototype.addKeyboard = function () {
  48595. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  48596. return this;
  48597. };
  48598. /**
  48599. * Add mouse input support to the input manager.
  48600. * @param touchEnabled if the FreeCameraMouseInput should support touch (default: true)
  48601. * @returns the current input manager
  48602. */
  48603. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  48604. if (touchEnabled === void 0) { touchEnabled = true; }
  48605. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  48606. return this;
  48607. };
  48608. /**
  48609. * Add orientation input support to the input manager.
  48610. * @returns the current input manager
  48611. */
  48612. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  48613. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  48614. return this;
  48615. };
  48616. /**
  48617. * Add touch input support to the input manager.
  48618. * @returns the current input manager
  48619. */
  48620. FreeCameraInputsManager.prototype.addTouch = function () {
  48621. this.add(new BABYLON.FreeCameraTouchInput());
  48622. return this;
  48623. };
  48624. /**
  48625. * Add virtual joystick input support to the input manager.
  48626. * @returns the current input manager
  48627. */
  48628. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  48629. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  48630. return this;
  48631. };
  48632. return FreeCameraInputsManager;
  48633. }(BABYLON.CameraInputsManager));
  48634. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  48635. })(BABYLON || (BABYLON = {}));
  48636. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  48637. var BABYLON;
  48638. (function (BABYLON) {
  48639. BABYLON.Node.AddNodeConstructor("FreeCamera", function (name, scene) {
  48640. // Forcing to use the Universal camera
  48641. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  48642. });
  48643. /**
  48644. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48645. * Please consider using the new UniversalCamera instead as it adds more functionality like the gamepad.
  48646. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48647. */
  48648. var FreeCamera = /** @class */ (function (_super) {
  48649. __extends(FreeCamera, _super);
  48650. /**
  48651. * Instantiates a Free Camera.
  48652. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  48653. * Please consider using the new UniversalCamera instead as it adds more functionality like touch to this camera.
  48654. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  48655. * @param name Define the name of the camera in the scene
  48656. * @param position Define the start position of the camera in the scene
  48657. * @param scene Define the scene the camera belongs to
  48658. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  48659. */
  48660. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  48661. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48662. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  48663. /**
  48664. * Define the collision ellipsoid of the camera.
  48665. * This is helpful to simulate a camera body like the player body around the camera
  48666. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  48667. */
  48668. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  48669. /**
  48670. * Define an offset for the position of the ellipsoid around the camera.
  48671. * This can be helpful to determine the center of the body near the gravity center of the body
  48672. * instead of its head.
  48673. */
  48674. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  48675. /**
  48676. * Enable or disable collisions of the camera with the rest of the scene objects.
  48677. */
  48678. _this.checkCollisions = false;
  48679. /**
  48680. * Enable or disable gravity on the camera.
  48681. */
  48682. _this.applyGravity = false;
  48683. _this._needMoveForGravity = false;
  48684. _this._oldPosition = BABYLON.Vector3.Zero();
  48685. _this._diffPosition = BABYLON.Vector3.Zero();
  48686. _this._newPosition = BABYLON.Vector3.Zero();
  48687. // Collisions
  48688. _this._collisionMask = -1;
  48689. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48690. if (collidedMesh === void 0) { collidedMesh = null; }
  48691. //TODO move this to the collision coordinator!
  48692. if (_this.getScene().workerCollisions)
  48693. newPosition.multiplyInPlace(_this._collider._radius);
  48694. var updatePosition = function (newPos) {
  48695. _this._newPosition.copyFrom(newPos);
  48696. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  48697. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  48698. _this.position.addInPlace(_this._diffPosition);
  48699. if (_this.onCollide && collidedMesh) {
  48700. _this.onCollide(collidedMesh);
  48701. }
  48702. }
  48703. };
  48704. updatePosition(newPosition);
  48705. };
  48706. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  48707. _this.inputs.addKeyboard().addMouse();
  48708. return _this;
  48709. }
  48710. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  48711. /**
  48712. * Gets the input sensibility for a mouse input. (default is 2000.0)
  48713. * Higher values reduce sensitivity.
  48714. */
  48715. get: function () {
  48716. var mouse = this.inputs.attached["mouse"];
  48717. if (mouse)
  48718. return mouse.angularSensibility;
  48719. return 0;
  48720. },
  48721. /**
  48722. * Sets the input sensibility for a mouse input. (default is 2000.0)
  48723. * Higher values reduce sensitivity.
  48724. */
  48725. set: function (value) {
  48726. var mouse = this.inputs.attached["mouse"];
  48727. if (mouse)
  48728. mouse.angularSensibility = value;
  48729. },
  48730. enumerable: true,
  48731. configurable: true
  48732. });
  48733. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  48734. /**
  48735. * Gets or Set the list of keyboard keys used to control the forward move of the camera.
  48736. */
  48737. get: function () {
  48738. var keyboard = this.inputs.attached["keyboard"];
  48739. if (keyboard)
  48740. return keyboard.keysUp;
  48741. return [];
  48742. },
  48743. set: function (value) {
  48744. var keyboard = this.inputs.attached["keyboard"];
  48745. if (keyboard)
  48746. keyboard.keysUp = value;
  48747. },
  48748. enumerable: true,
  48749. configurable: true
  48750. });
  48751. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  48752. /**
  48753. * Gets or Set the list of keyboard keys used to control the backward move of the camera.
  48754. */
  48755. get: function () {
  48756. var keyboard = this.inputs.attached["keyboard"];
  48757. if (keyboard)
  48758. return keyboard.keysDown;
  48759. return [];
  48760. },
  48761. set: function (value) {
  48762. var keyboard = this.inputs.attached["keyboard"];
  48763. if (keyboard)
  48764. keyboard.keysDown = value;
  48765. },
  48766. enumerable: true,
  48767. configurable: true
  48768. });
  48769. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  48770. /**
  48771. * Gets or Set the list of keyboard keys used to control the left strafe move of the camera.
  48772. */
  48773. get: function () {
  48774. var keyboard = this.inputs.attached["keyboard"];
  48775. if (keyboard)
  48776. return keyboard.keysLeft;
  48777. return [];
  48778. },
  48779. set: function (value) {
  48780. var keyboard = this.inputs.attached["keyboard"];
  48781. if (keyboard)
  48782. keyboard.keysLeft = value;
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  48788. /**
  48789. * Gets or Set the list of keyboard keys used to control the right strafe move of the camera.
  48790. */
  48791. get: function () {
  48792. var keyboard = this.inputs.attached["keyboard"];
  48793. if (keyboard)
  48794. return keyboard.keysRight;
  48795. return [];
  48796. },
  48797. set: function (value) {
  48798. var keyboard = this.inputs.attached["keyboard"];
  48799. if (keyboard)
  48800. keyboard.keysRight = value;
  48801. },
  48802. enumerable: true,
  48803. configurable: true
  48804. });
  48805. /**
  48806. * Attached controls to the current camera.
  48807. * @param element Defines the element the controls should be listened from
  48808. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48809. */
  48810. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  48811. this.inputs.attachElement(element, noPreventDefault);
  48812. };
  48813. /**
  48814. * Detach the current controls from the camera.
  48815. * The camera will stop reacting to inputs.
  48816. * @param element Defines the element to stop listening the inputs from
  48817. */
  48818. FreeCamera.prototype.detachControl = function (element) {
  48819. this.inputs.detachElement(element);
  48820. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  48821. this.cameraRotation = new BABYLON.Vector2(0, 0);
  48822. };
  48823. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  48824. /**
  48825. * Define a collision mask to limit the list of object the camera can collide with
  48826. */
  48827. get: function () {
  48828. return this._collisionMask;
  48829. },
  48830. set: function (mask) {
  48831. this._collisionMask = !isNaN(mask) ? mask : -1;
  48832. },
  48833. enumerable: true,
  48834. configurable: true
  48835. });
  48836. /** @hidden */
  48837. FreeCamera.prototype._collideWithWorld = function (displacement) {
  48838. var globalPosition;
  48839. if (this.parent) {
  48840. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  48841. }
  48842. else {
  48843. globalPosition = this.position;
  48844. }
  48845. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  48846. this._oldPosition.addInPlace(this.ellipsoidOffset);
  48847. if (!this._collider) {
  48848. this._collider = new BABYLON.Collider();
  48849. }
  48850. this._collider._radius = this.ellipsoid;
  48851. this._collider.collisionMask = this._collisionMask;
  48852. //no need for clone, as long as gravity is not on.
  48853. var actualDisplacement = displacement;
  48854. //add gravity to the direction to prevent the dual-collision checking
  48855. if (this.applyGravity) {
  48856. //this prevents mending with cameraDirection, a global variable of the free camera class.
  48857. actualDisplacement = displacement.add(this.getScene().gravity);
  48858. }
  48859. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48860. };
  48861. /** @hidden */
  48862. FreeCamera.prototype._checkInputs = function () {
  48863. if (!this._localDirection) {
  48864. this._localDirection = BABYLON.Vector3.Zero();
  48865. this._transformedDirection = BABYLON.Vector3.Zero();
  48866. }
  48867. this.inputs.checkInputs();
  48868. _super.prototype._checkInputs.call(this);
  48869. };
  48870. /** @hidden */
  48871. FreeCamera.prototype._decideIfNeedsToMove = function () {
  48872. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  48873. };
  48874. /** @hidden */
  48875. FreeCamera.prototype._updatePosition = function () {
  48876. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  48877. this._collideWithWorld(this.cameraDirection);
  48878. }
  48879. else {
  48880. _super.prototype._updatePosition.call(this);
  48881. }
  48882. };
  48883. /**
  48884. * Destroy the camera and release the current resources hold by it.
  48885. */
  48886. FreeCamera.prototype.dispose = function () {
  48887. this.inputs.clear();
  48888. _super.prototype.dispose.call(this);
  48889. };
  48890. /**
  48891. * Gets the current object class name.
  48892. * @return the class name
  48893. */
  48894. FreeCamera.prototype.getClassName = function () {
  48895. return "FreeCamera";
  48896. };
  48897. __decorate([
  48898. BABYLON.serializeAsVector3()
  48899. ], FreeCamera.prototype, "ellipsoid", void 0);
  48900. __decorate([
  48901. BABYLON.serializeAsVector3()
  48902. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  48903. __decorate([
  48904. BABYLON.serialize()
  48905. ], FreeCamera.prototype, "checkCollisions", void 0);
  48906. __decorate([
  48907. BABYLON.serialize()
  48908. ], FreeCamera.prototype, "applyGravity", void 0);
  48909. return FreeCamera;
  48910. }(BABYLON.TargetCamera));
  48911. BABYLON.FreeCamera = FreeCamera;
  48912. })(BABYLON || (BABYLON = {}));
  48913. //# sourceMappingURL=babylon.freeCamera.js.map
  48914. var BABYLON;
  48915. (function (BABYLON) {
  48916. /**
  48917. * Manage the keyboard inputs to control the movement of an arc rotate camera.
  48918. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  48919. */
  48920. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  48921. function ArcRotateCameraKeyboardMoveInput() {
  48922. /**
  48923. * Defines the list of key codes associated with the up action (increase alpha)
  48924. */
  48925. this.keysUp = [38];
  48926. /**
  48927. * Defines the list of key codes associated with the down action (decrease alpha)
  48928. */
  48929. this.keysDown = [40];
  48930. /**
  48931. * Defines the list of key codes associated with the left action (increase beta)
  48932. */
  48933. this.keysLeft = [37];
  48934. /**
  48935. * Defines the list of key codes associated with the right action (decrease beta)
  48936. */
  48937. this.keysRight = [39];
  48938. /**
  48939. * Defines the list of key codes associated with the reset action.
  48940. * Those keys reset the camera to its last stored state (with the method camera.storeState())
  48941. */
  48942. this.keysReset = [220];
  48943. /**
  48944. * Defines the panning sensibility of the inputs.
  48945. * (How fast is the camera paning)
  48946. */
  48947. this.panningSensibility = 50.0;
  48948. /**
  48949. * Defines the zooming sensibility of the inputs.
  48950. * (How fast is the camera zooming)
  48951. */
  48952. this.zoomingSensibility = 25.0;
  48953. /**
  48954. * Defines wether maintaining the alt key down switch the movement mode from
  48955. * orientation to zoom.
  48956. */
  48957. this.useAltToZoom = true;
  48958. /**
  48959. * Rotation speed of the camera
  48960. */
  48961. this.angularSpeed = 0.01;
  48962. this._keys = new Array();
  48963. }
  48964. /**
  48965. * Attach the input controls to a specific dom element to get the input from.
  48966. * @param element Defines the element the controls should be listened from
  48967. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  48968. */
  48969. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  48970. var _this = this;
  48971. if (this._onCanvasBlurObserver) {
  48972. return;
  48973. }
  48974. this._scene = this.camera.getScene();
  48975. this._engine = this._scene.getEngine();
  48976. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  48977. _this._keys = [];
  48978. });
  48979. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  48980. var evt = info.event;
  48981. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  48982. _this._ctrlPressed = evt.ctrlKey;
  48983. _this._altPressed = evt.altKey;
  48984. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  48985. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  48986. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  48987. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  48988. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  48989. var index = _this._keys.indexOf(evt.keyCode);
  48990. if (index === -1) {
  48991. _this._keys.push(evt.keyCode);
  48992. }
  48993. if (evt.preventDefault) {
  48994. if (!noPreventDefault) {
  48995. evt.preventDefault();
  48996. }
  48997. }
  48998. }
  48999. }
  49000. else {
  49001. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  49002. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  49003. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  49004. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  49005. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  49006. var index = _this._keys.indexOf(evt.keyCode);
  49007. if (index >= 0) {
  49008. _this._keys.splice(index, 1);
  49009. }
  49010. if (evt.preventDefault) {
  49011. if (!noPreventDefault) {
  49012. evt.preventDefault();
  49013. }
  49014. }
  49015. }
  49016. }
  49017. });
  49018. };
  49019. /**
  49020. * Detach the current controls from the specified dom element.
  49021. * @param element Defines the element to stop listening the inputs from
  49022. */
  49023. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  49024. if (this._scene) {
  49025. if (this._onKeyboardObserver) {
  49026. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  49027. }
  49028. if (this._onCanvasBlurObserver) {
  49029. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  49030. }
  49031. this._onKeyboardObserver = null;
  49032. this._onCanvasBlurObserver = null;
  49033. }
  49034. this._keys = [];
  49035. };
  49036. /**
  49037. * Update the current camera state depending on the inputs that have been used this frame.
  49038. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  49039. */
  49040. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  49041. if (this._onKeyboardObserver) {
  49042. var camera = this.camera;
  49043. for (var index = 0; index < this._keys.length; index++) {
  49044. var keyCode = this._keys[index];
  49045. if (this.keysLeft.indexOf(keyCode) !== -1) {
  49046. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49047. camera.inertialPanningX -= 1 / this.panningSensibility;
  49048. }
  49049. else {
  49050. camera.inertialAlphaOffset -= this.angularSpeed;
  49051. }
  49052. }
  49053. else if (this.keysUp.indexOf(keyCode) !== -1) {
  49054. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49055. camera.inertialPanningY += 1 / this.panningSensibility;
  49056. }
  49057. else if (this._altPressed && this.useAltToZoom) {
  49058. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  49059. }
  49060. else {
  49061. camera.inertialBetaOffset -= this.angularSpeed;
  49062. }
  49063. }
  49064. else if (this.keysRight.indexOf(keyCode) !== -1) {
  49065. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49066. camera.inertialPanningX += 1 / this.panningSensibility;
  49067. }
  49068. else {
  49069. camera.inertialAlphaOffset += this.angularSpeed;
  49070. }
  49071. }
  49072. else if (this.keysDown.indexOf(keyCode) !== -1) {
  49073. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  49074. camera.inertialPanningY -= 1 / this.panningSensibility;
  49075. }
  49076. else if (this._altPressed && this.useAltToZoom) {
  49077. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  49078. }
  49079. else {
  49080. camera.inertialBetaOffset += this.angularSpeed;
  49081. }
  49082. }
  49083. else if (this.keysReset.indexOf(keyCode) !== -1) {
  49084. if (camera.useInputToRestoreState) {
  49085. camera.restoreState();
  49086. }
  49087. }
  49088. }
  49089. }
  49090. };
  49091. /**
  49092. * Gets the class name of the current intput.
  49093. * @returns the class name
  49094. */
  49095. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  49096. return "ArcRotateCameraKeyboardMoveInput";
  49097. };
  49098. /**
  49099. * Get the friendly name associated with the input class.
  49100. * @returns the input friendly name
  49101. */
  49102. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  49103. return "keyboard";
  49104. };
  49105. __decorate([
  49106. BABYLON.serialize()
  49107. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  49108. __decorate([
  49109. BABYLON.serialize()
  49110. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  49111. __decorate([
  49112. BABYLON.serialize()
  49113. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  49114. __decorate([
  49115. BABYLON.serialize()
  49116. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  49117. __decorate([
  49118. BABYLON.serialize()
  49119. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  49120. __decorate([
  49121. BABYLON.serialize()
  49122. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  49123. __decorate([
  49124. BABYLON.serialize()
  49125. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  49126. __decorate([
  49127. BABYLON.serialize()
  49128. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  49129. __decorate([
  49130. BABYLON.serialize()
  49131. ], ArcRotateCameraKeyboardMoveInput.prototype, "angularSpeed", void 0);
  49132. return ArcRotateCameraKeyboardMoveInput;
  49133. }());
  49134. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  49135. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  49136. })(BABYLON || (BABYLON = {}));
  49137. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  49138. var BABYLON;
  49139. (function (BABYLON) {
  49140. /**
  49141. * Manage the mouse wheel inputs to control an arc rotate camera.
  49142. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49143. */
  49144. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  49145. function ArcRotateCameraMouseWheelInput() {
  49146. /**
  49147. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  49148. */
  49149. this.wheelPrecision = 3.0;
  49150. /**
  49151. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  49152. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  49153. */
  49154. this.wheelDeltaPercentage = 0;
  49155. }
  49156. /**
  49157. * Attach the input controls to a specific dom element to get the input from.
  49158. * @param element Defines the element the controls should be listened from
  49159. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49160. */
  49161. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  49162. var _this = this;
  49163. this._wheel = function (p, s) {
  49164. //sanity check - this should be a PointerWheel event.
  49165. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  49166. return;
  49167. var event = p.event;
  49168. var delta = 0;
  49169. if (event.wheelDelta) {
  49170. if (_this.wheelDeltaPercentage) {
  49171. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  49172. if (event.wheelDelta > 0) {
  49173. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  49174. }
  49175. else {
  49176. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  49177. }
  49178. }
  49179. else {
  49180. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  49181. }
  49182. }
  49183. else if (event.detail) {
  49184. delta = -event.detail / _this.wheelPrecision;
  49185. }
  49186. if (delta)
  49187. _this.camera.inertialRadiusOffset += delta;
  49188. if (event.preventDefault) {
  49189. if (!noPreventDefault) {
  49190. event.preventDefault();
  49191. }
  49192. }
  49193. };
  49194. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  49195. };
  49196. /**
  49197. * Detach the current controls from the specified dom element.
  49198. * @param element Defines the element to stop listening the inputs from
  49199. */
  49200. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  49201. if (this._observer && element) {
  49202. this.camera.getScene().onPointerObservable.remove(this._observer);
  49203. this._observer = null;
  49204. this._wheel = null;
  49205. }
  49206. };
  49207. /**
  49208. * Gets the class name of the current intput.
  49209. * @returns the class name
  49210. */
  49211. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  49212. return "ArcRotateCameraMouseWheelInput";
  49213. };
  49214. /**
  49215. * Get the friendly name associated with the input class.
  49216. * @returns the input friendly name
  49217. */
  49218. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  49219. return "mousewheel";
  49220. };
  49221. __decorate([
  49222. BABYLON.serialize()
  49223. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  49224. __decorate([
  49225. BABYLON.serialize()
  49226. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  49227. return ArcRotateCameraMouseWheelInput;
  49228. }());
  49229. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  49230. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  49231. })(BABYLON || (BABYLON = {}));
  49232. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  49233. var BABYLON;
  49234. (function (BABYLON) {
  49235. /**
  49236. * Manage the pointers inputs to control an arc rotate camera.
  49237. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49238. */
  49239. var ArcRotateCameraPointersInput = /** @class */ (function () {
  49240. function ArcRotateCameraPointersInput() {
  49241. /**
  49242. * Defines the buttons associated with the input to handle camera move.
  49243. */
  49244. this.buttons = [0, 1, 2];
  49245. /**
  49246. * Defines the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49247. */
  49248. this.angularSensibilityX = 1000.0;
  49249. /**
  49250. * Defines the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49251. */
  49252. this.angularSensibilityY = 1000.0;
  49253. /**
  49254. * Defines the pointer pinch precision or how fast is the camera zooming.
  49255. */
  49256. this.pinchPrecision = 12.0;
  49257. /**
  49258. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  49259. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49260. */
  49261. this.pinchDeltaPercentage = 0;
  49262. /**
  49263. * Defines the pointer panning sensibility or how fast is the camera moving.
  49264. */
  49265. this.panningSensibility = 1000.0;
  49266. /**
  49267. * Defines whether panning (2 fingers swipe) is enabled through multitouch.
  49268. */
  49269. this.multiTouchPanning = true;
  49270. /**
  49271. * Defines whether panning is enabled for both pan (2 fingers swipe) and zoom (pinch) through multitouch.
  49272. */
  49273. this.multiTouchPanAndZoom = true;
  49274. /**
  49275. * Revers pinch action direction.
  49276. */
  49277. this.pinchInwards = true;
  49278. this._isPanClick = false;
  49279. }
  49280. /**
  49281. * Attach the input controls to a specific dom element to get the input from.
  49282. * @param element Defines the element the controls should be listened from
  49283. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  49284. */
  49285. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  49286. var _this = this;
  49287. var engine = this.camera.getEngine();
  49288. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  49289. var pointA = null;
  49290. var pointB = null;
  49291. var previousPinchSquaredDistance = 0;
  49292. var initialDistance = 0;
  49293. var twoFingerActivityCount = 0;
  49294. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  49295. this._pointerInput = function (p, s) {
  49296. var evt = p.event;
  49297. var isTouch = p.event.pointerType === "touch";
  49298. if (engine.isInVRExclusivePointerMode) {
  49299. return;
  49300. }
  49301. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  49302. return;
  49303. }
  49304. var srcElement = (evt.srcElement || evt.target);
  49305. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  49306. try {
  49307. srcElement.setPointerCapture(evt.pointerId);
  49308. }
  49309. catch (e) {
  49310. //Nothing to do with the error. Execution will continue.
  49311. }
  49312. // Manage panning with pan button click
  49313. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  49314. // manage pointers
  49315. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  49316. if (pointA === null) {
  49317. pointA = cacheSoloPointer;
  49318. }
  49319. else if (pointB === null) {
  49320. pointB = cacheSoloPointer;
  49321. }
  49322. if (!noPreventDefault) {
  49323. evt.preventDefault();
  49324. element.focus();
  49325. }
  49326. }
  49327. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  49328. if (_this.camera.useInputToRestoreState) {
  49329. _this.camera.restoreState();
  49330. }
  49331. }
  49332. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  49333. try {
  49334. srcElement.releasePointerCapture(evt.pointerId);
  49335. }
  49336. catch (e) {
  49337. //Nothing to do with the error.
  49338. }
  49339. cacheSoloPointer = null;
  49340. previousPinchSquaredDistance = 0;
  49341. previousMultiTouchPanPosition.isPaning = false;
  49342. previousMultiTouchPanPosition.isPinching = false;
  49343. twoFingerActivityCount = 0;
  49344. initialDistance = 0;
  49345. if (!isTouch) {
  49346. pointB = null; // Mouse and pen are mono pointer
  49347. }
  49348. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  49349. //but emptying completly pointers collection is required to fix a bug on iPhone :
  49350. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  49351. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  49352. if (engine._badOS) {
  49353. pointA = pointB = null;
  49354. }
  49355. else {
  49356. //only remove the impacted pointer in case of multitouch allowing on most
  49357. //platforms switching from rotate to zoom and pan seamlessly.
  49358. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  49359. pointA = pointB;
  49360. pointB = null;
  49361. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49362. }
  49363. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  49364. pointB = null;
  49365. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  49366. }
  49367. else {
  49368. pointA = pointB = null;
  49369. }
  49370. }
  49371. if (!noPreventDefault) {
  49372. evt.preventDefault();
  49373. }
  49374. }
  49375. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49376. if (!noPreventDefault) {
  49377. evt.preventDefault();
  49378. }
  49379. // One button down
  49380. if (pointA && pointB === null && cacheSoloPointer) {
  49381. if (_this.panningSensibility !== 0 &&
  49382. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  49383. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  49384. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  49385. }
  49386. else {
  49387. var offsetX = evt.clientX - cacheSoloPointer.x;
  49388. var offsetY = evt.clientY - cacheSoloPointer.y;
  49389. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49390. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49391. }
  49392. cacheSoloPointer.x = evt.clientX;
  49393. cacheSoloPointer.y = evt.clientY;
  49394. }
  49395. // Two buttons down: pinch/pan
  49396. else if (pointA && pointB) {
  49397. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  49398. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  49399. ed.x = evt.clientX;
  49400. ed.y = evt.clientY;
  49401. var direction = _this.pinchInwards ? 1 : -1;
  49402. var distX = pointA.x - pointB.x;
  49403. var distY = pointA.y - pointB.y;
  49404. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  49405. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  49406. if (previousPinchSquaredDistance === 0) {
  49407. initialDistance = pinchDistance;
  49408. previousPinchSquaredDistance = pinchSquaredDistance;
  49409. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  49410. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  49411. return;
  49412. }
  49413. if (_this.multiTouchPanAndZoom) {
  49414. if (_this.pinchDeltaPercentage) {
  49415. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49416. }
  49417. else {
  49418. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49419. (_this.pinchPrecision *
  49420. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49421. direction);
  49422. }
  49423. if (_this.panningSensibility !== 0) {
  49424. var pointersCenterX = (pointA.x + pointB.x) / 2;
  49425. var pointersCenterY = (pointA.y + pointB.y) / 2;
  49426. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  49427. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  49428. previousMultiTouchPanPosition.x = pointersCenterX;
  49429. previousMultiTouchPanPosition.y = pointersCenterY;
  49430. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  49431. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  49432. }
  49433. }
  49434. else {
  49435. twoFingerActivityCount++;
  49436. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  49437. if (_this.pinchDeltaPercentage) {
  49438. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  49439. }
  49440. else {
  49441. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  49442. (_this.pinchPrecision *
  49443. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  49444. direction);
  49445. }
  49446. previousMultiTouchPanPosition.isPaning = false;
  49447. previousMultiTouchPanPosition.isPinching = true;
  49448. }
  49449. else {
  49450. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  49451. if (!previousMultiTouchPanPosition.isPaning) {
  49452. previousMultiTouchPanPosition.isPaning = true;
  49453. previousMultiTouchPanPosition.isPinching = false;
  49454. previousMultiTouchPanPosition.x = ed.x;
  49455. previousMultiTouchPanPosition.y = ed.y;
  49456. return;
  49457. }
  49458. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  49459. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  49460. }
  49461. }
  49462. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  49463. previousMultiTouchPanPosition.x = ed.x;
  49464. previousMultiTouchPanPosition.y = ed.y;
  49465. }
  49466. }
  49467. previousPinchSquaredDistance = pinchSquaredDistance;
  49468. }
  49469. }
  49470. };
  49471. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  49472. this._onContextMenu = function (evt) {
  49473. evt.preventDefault();
  49474. };
  49475. if (!this.camera._useCtrlForPanning) {
  49476. element.addEventListener("contextmenu", this._onContextMenu, false);
  49477. }
  49478. this._onLostFocus = function () {
  49479. //this._keys = [];
  49480. pointA = pointB = null;
  49481. previousPinchSquaredDistance = 0;
  49482. previousMultiTouchPanPosition.isPaning = false;
  49483. previousMultiTouchPanPosition.isPinching = false;
  49484. twoFingerActivityCount = 0;
  49485. cacheSoloPointer = null;
  49486. initialDistance = 0;
  49487. };
  49488. this._onMouseMove = function (evt) {
  49489. if (!engine.isPointerLock) {
  49490. return;
  49491. }
  49492. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  49493. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  49494. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  49495. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  49496. if (!noPreventDefault) {
  49497. evt.preventDefault();
  49498. }
  49499. };
  49500. this._onGestureStart = function (e) {
  49501. if (window.MSGesture === undefined) {
  49502. return;
  49503. }
  49504. if (!_this._MSGestureHandler) {
  49505. _this._MSGestureHandler = new MSGesture();
  49506. _this._MSGestureHandler.target = element;
  49507. }
  49508. _this._MSGestureHandler.addPointer(e.pointerId);
  49509. };
  49510. this._onGesture = function (e) {
  49511. _this.camera.radius *= e.scale;
  49512. if (e.preventDefault) {
  49513. if (!noPreventDefault) {
  49514. e.stopPropagation();
  49515. e.preventDefault();
  49516. }
  49517. }
  49518. };
  49519. element.addEventListener("mousemove", this._onMouseMove, false);
  49520. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  49521. element.addEventListener("MSGestureChange", this._onGesture, false);
  49522. BABYLON.Tools.RegisterTopRootEvents([
  49523. { name: "blur", handler: this._onLostFocus }
  49524. ]);
  49525. };
  49526. /**
  49527. * Detach the current controls from the specified dom element.
  49528. * @param element Defines the element to stop listening the inputs from
  49529. */
  49530. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  49531. if (this._onLostFocus) {
  49532. BABYLON.Tools.UnregisterTopRootEvents([
  49533. { name: "blur", handler: this._onLostFocus }
  49534. ]);
  49535. }
  49536. if (element && this._observer) {
  49537. this.camera.getScene().onPointerObservable.remove(this._observer);
  49538. this._observer = null;
  49539. if (this._onContextMenu) {
  49540. element.removeEventListener("contextmenu", this._onContextMenu);
  49541. }
  49542. if (this._onMouseMove) {
  49543. element.removeEventListener("mousemove", this._onMouseMove);
  49544. }
  49545. if (this._onGestureStart) {
  49546. element.removeEventListener("MSPointerDown", this._onGestureStart);
  49547. }
  49548. if (this._onGesture) {
  49549. element.removeEventListener("MSGestureChange", this._onGesture);
  49550. }
  49551. this._isPanClick = false;
  49552. this.pinchInwards = true;
  49553. this._onMouseMove = null;
  49554. this._onGestureStart = null;
  49555. this._onGesture = null;
  49556. this._MSGestureHandler = null;
  49557. this._onLostFocus = null;
  49558. this._onContextMenu = null;
  49559. }
  49560. };
  49561. /**
  49562. * Gets the class name of the current intput.
  49563. * @returns the class name
  49564. */
  49565. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  49566. return "ArcRotateCameraPointersInput";
  49567. };
  49568. /**
  49569. * Get the friendly name associated with the input class.
  49570. * @returns the input friendly name
  49571. */
  49572. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  49573. return "pointers";
  49574. };
  49575. __decorate([
  49576. BABYLON.serialize()
  49577. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  49578. __decorate([
  49579. BABYLON.serialize()
  49580. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  49581. __decorate([
  49582. BABYLON.serialize()
  49583. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  49584. __decorate([
  49585. BABYLON.serialize()
  49586. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  49587. __decorate([
  49588. BABYLON.serialize()
  49589. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  49590. __decorate([
  49591. BABYLON.serialize()
  49592. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  49593. __decorate([
  49594. BABYLON.serialize()
  49595. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  49596. __decorate([
  49597. BABYLON.serialize()
  49598. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  49599. return ArcRotateCameraPointersInput;
  49600. }());
  49601. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  49602. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  49603. })(BABYLON || (BABYLON = {}));
  49604. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  49605. var BABYLON;
  49606. (function (BABYLON) {
  49607. /**
  49608. * Default Inputs manager for the ArcRotateCamera.
  49609. * It groups all the default supported inputs for ease of use.
  49610. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  49611. */
  49612. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  49613. __extends(ArcRotateCameraInputsManager, _super);
  49614. /**
  49615. * Instantiates a new ArcRotateCameraInputsManager.
  49616. * @param camera Defines the camera the inputs belong to
  49617. */
  49618. function ArcRotateCameraInputsManager(camera) {
  49619. return _super.call(this, camera) || this;
  49620. }
  49621. /**
  49622. * Add mouse wheel input support to the input manager.
  49623. * @returns the current input manager
  49624. */
  49625. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  49626. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  49627. return this;
  49628. };
  49629. /**
  49630. * Add pointers input support to the input manager.
  49631. * @returns the current input manager
  49632. */
  49633. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  49634. this.add(new BABYLON.ArcRotateCameraPointersInput());
  49635. return this;
  49636. };
  49637. /**
  49638. * Add keyboard input support to the input manager.
  49639. * @returns the current input manager
  49640. */
  49641. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  49642. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  49643. return this;
  49644. };
  49645. /**
  49646. * Add orientation input support to the input manager.
  49647. * @returns the current input manager
  49648. */
  49649. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  49650. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  49651. return this;
  49652. };
  49653. return ArcRotateCameraInputsManager;
  49654. }(BABYLON.CameraInputsManager));
  49655. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  49656. })(BABYLON || (BABYLON = {}));
  49657. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  49658. var BABYLON;
  49659. (function (BABYLON) {
  49660. BABYLON.Node.AddNodeConstructor("ArcRotateCamera", function (name, scene) {
  49661. return function () { return new ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  49662. });
  49663. /**
  49664. * This represents an orbital type of camera.
  49665. *
  49666. * 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.
  49667. * 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.
  49668. * @see http://doc.babylonjs.com/babylon101/cameras#arc-rotate-camera
  49669. */
  49670. var ArcRotateCamera = /** @class */ (function (_super) {
  49671. __extends(ArcRotateCamera, _super);
  49672. /**
  49673. * Instantiates a new ArcRotateCamera in a given scene
  49674. * @param name Defines the name of the camera
  49675. * @param alpha Defines the camera rotation along the logitudinal axis
  49676. * @param beta Defines the camera rotation along the latitudinal axis
  49677. * @param radius Defines the camera distance from its target
  49678. * @param target Defines the camera target
  49679. * @param scene Defines the scene the camera belongs to
  49680. * @param setActiveOnSceneIfNoneActive Defines wheter the camera should be marked as active if not other active cameras have been defined
  49681. */
  49682. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  49683. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  49684. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  49685. /**
  49686. * Current inertia value on the longitudinal axis.
  49687. * The bigger this number the longer it will take for the camera to stop.
  49688. */
  49689. _this.inertialAlphaOffset = 0;
  49690. /**
  49691. * Current inertia value on the latitudinal axis.
  49692. * The bigger this number the longer it will take for the camera to stop.
  49693. */
  49694. _this.inertialBetaOffset = 0;
  49695. /**
  49696. * Current inertia value on the radius axis.
  49697. * The bigger this number the longer it will take for the camera to stop.
  49698. */
  49699. _this.inertialRadiusOffset = 0;
  49700. /**
  49701. * Minimum allowed angle on the longitudinal axis.
  49702. * This can help limiting how the Camera is able to move in the scene.
  49703. */
  49704. _this.lowerAlphaLimit = null;
  49705. /**
  49706. * Maximum allowed angle on the longitudinal axis.
  49707. * This can help limiting how the Camera is able to move in the scene.
  49708. */
  49709. _this.upperAlphaLimit = null;
  49710. /**
  49711. * Minimum allowed angle on the latitudinal axis.
  49712. * This can help limiting how the Camera is able to move in the scene.
  49713. */
  49714. _this.lowerBetaLimit = 0.01;
  49715. /**
  49716. * Maximum allowed angle on the latitudinal axis.
  49717. * This can help limiting how the Camera is able to move in the scene.
  49718. */
  49719. _this.upperBetaLimit = Math.PI;
  49720. /**
  49721. * Minimum allowed distance of the camera to the target (The camera can not get closer).
  49722. * This can help limiting how the Camera is able to move in the scene.
  49723. */
  49724. _this.lowerRadiusLimit = null;
  49725. /**
  49726. * Maximum allowed distance of the camera to the target (The camera can not get further).
  49727. * This can help limiting how the Camera is able to move in the scene.
  49728. */
  49729. _this.upperRadiusLimit = null;
  49730. /**
  49731. * Defines the current inertia value used during panning of the camera along the X axis.
  49732. */
  49733. _this.inertialPanningX = 0;
  49734. /**
  49735. * Defines the current inertia value used during panning of the camera along the Y axis.
  49736. */
  49737. _this.inertialPanningY = 0;
  49738. /**
  49739. * Defines the distance used to consider the camera in pan mode vs pinch/zoom.
  49740. * Basically if your fingers moves away from more than this distance you will be considered
  49741. * in pinch mode.
  49742. */
  49743. _this.pinchToPanMaxDistance = 20;
  49744. /**
  49745. * Defines the maximum distance the camera can pan.
  49746. * This could help keeping the cammera always in your scene.
  49747. */
  49748. _this.panningDistanceLimit = null;
  49749. /**
  49750. * Defines the target of the camera before paning.
  49751. */
  49752. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  49753. /**
  49754. * Defines the value of the inertia used during panning.
  49755. * 0 would mean stop inertia and one would mean no decelleration at all.
  49756. */
  49757. _this.panningInertia = 0.9;
  49758. //-- end properties for backward compatibility for inputs
  49759. /**
  49760. * Defines how much the radius should be scaled while zomming on a particular mesh (through the zoomOn function)
  49761. */
  49762. _this.zoomOnFactor = 1;
  49763. /**
  49764. * Defines a screen offset for the camera position.
  49765. */
  49766. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  49767. /**
  49768. * Allows the camera to be completely reversed.
  49769. * If false the camera can not arrive upside down.
  49770. */
  49771. _this.allowUpsideDown = true;
  49772. /**
  49773. * Define if double tap/click is used to restore the previously saved state of the camera.
  49774. */
  49775. _this.useInputToRestoreState = true;
  49776. /** @hidden */
  49777. _this._viewMatrix = new BABYLON.Matrix();
  49778. /**
  49779. * Defines the allowed panning axis.
  49780. */
  49781. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  49782. /**
  49783. * Observable triggered when the mesh target has been changed on the camera.
  49784. */
  49785. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  49786. /**
  49787. * Defines whether the camera should check collision with the objects oh the scene.
  49788. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#how-can-i-do-this
  49789. */
  49790. _this.checkCollisions = false;
  49791. /**
  49792. * Defines the collision radius of the camera.
  49793. * This simulates a sphere around the camera.
  49794. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#arcrotatecamera
  49795. */
  49796. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  49797. _this._previousPosition = BABYLON.Vector3.Zero();
  49798. _this._collisionVelocity = BABYLON.Vector3.Zero();
  49799. _this._newPosition = BABYLON.Vector3.Zero();
  49800. _this._computationVector = BABYLON.Vector3.Zero();
  49801. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  49802. if (collidedMesh === void 0) { collidedMesh = null; }
  49803. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  49804. newPosition.multiplyInPlace(_this._collider._radius);
  49805. }
  49806. if (!collidedMesh) {
  49807. _this._previousPosition.copyFrom(_this.position);
  49808. }
  49809. else {
  49810. _this.setPosition(newPosition);
  49811. if (_this.onCollide) {
  49812. _this.onCollide(collidedMesh);
  49813. }
  49814. }
  49815. // Recompute because of constraints
  49816. var cosa = Math.cos(_this.alpha);
  49817. var sina = Math.sin(_this.alpha);
  49818. var cosb = Math.cos(_this.beta);
  49819. var sinb = Math.sin(_this.beta);
  49820. if (sinb === 0) {
  49821. sinb = 0.0001;
  49822. }
  49823. var target = _this._getTargetPosition();
  49824. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  49825. target.addToRef(_this._computationVector, _this._newPosition);
  49826. _this.position.copyFrom(_this._newPosition);
  49827. var up = _this.upVector;
  49828. if (_this.allowUpsideDown && _this.beta < 0) {
  49829. up = up.clone();
  49830. up = up.negate();
  49831. }
  49832. _this._computeViewMatrix(_this.position, target, up);
  49833. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  49834. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  49835. _this._collisionTriggered = false;
  49836. };
  49837. _this._target = BABYLON.Vector3.Zero();
  49838. if (target) {
  49839. _this.setTarget(target);
  49840. }
  49841. _this.alpha = alpha;
  49842. _this.beta = beta;
  49843. _this.radius = radius;
  49844. _this.getViewMatrix();
  49845. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  49846. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  49847. return _this;
  49848. }
  49849. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  49850. /**
  49851. * Defines the target point of the camera.
  49852. * The camera looks towards it form the radius distance.
  49853. */
  49854. get: function () {
  49855. return this._target;
  49856. },
  49857. set: function (value) {
  49858. this.setTarget(value);
  49859. },
  49860. enumerable: true,
  49861. configurable: true
  49862. });
  49863. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  49864. //-- begin properties for backward compatibility for inputs
  49865. /**
  49866. * Gets or Set the pointer angular sensibility along the X axis or how fast is the camera rotating.
  49867. */
  49868. get: function () {
  49869. var pointers = this.inputs.attached["pointers"];
  49870. if (pointers)
  49871. return pointers.angularSensibilityX;
  49872. return 0;
  49873. },
  49874. set: function (value) {
  49875. var pointers = this.inputs.attached["pointers"];
  49876. if (pointers) {
  49877. pointers.angularSensibilityX = value;
  49878. }
  49879. },
  49880. enumerable: true,
  49881. configurable: true
  49882. });
  49883. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  49884. /**
  49885. * Gets or Set the pointer angular sensibility along the Y axis or how fast is the camera rotating.
  49886. */
  49887. get: function () {
  49888. var pointers = this.inputs.attached["pointers"];
  49889. if (pointers)
  49890. return pointers.angularSensibilityY;
  49891. return 0;
  49892. },
  49893. set: function (value) {
  49894. var pointers = this.inputs.attached["pointers"];
  49895. if (pointers) {
  49896. pointers.angularSensibilityY = value;
  49897. }
  49898. },
  49899. enumerable: true,
  49900. configurable: true
  49901. });
  49902. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  49903. /**
  49904. * Gets or Set the pointer pinch precision or how fast is the camera zooming.
  49905. */
  49906. get: function () {
  49907. var pointers = this.inputs.attached["pointers"];
  49908. if (pointers)
  49909. return pointers.pinchPrecision;
  49910. return 0;
  49911. },
  49912. set: function (value) {
  49913. var pointers = this.inputs.attached["pointers"];
  49914. if (pointers) {
  49915. pointers.pinchPrecision = value;
  49916. }
  49917. },
  49918. enumerable: true,
  49919. configurable: true
  49920. });
  49921. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  49922. /**
  49923. * Gets or Set the pointer pinch delta percentage or how fast is the camera zooming.
  49924. * It will be used instead of pinchDeltaPrecision if different from 0.
  49925. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  49926. */
  49927. get: function () {
  49928. var pointers = this.inputs.attached["pointers"];
  49929. if (pointers)
  49930. return pointers.pinchDeltaPercentage;
  49931. return 0;
  49932. },
  49933. set: function (value) {
  49934. var pointers = this.inputs.attached["pointers"];
  49935. if (pointers) {
  49936. pointers.pinchDeltaPercentage = value;
  49937. }
  49938. },
  49939. enumerable: true,
  49940. configurable: true
  49941. });
  49942. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  49943. /**
  49944. * Gets or Set the pointer panning sensibility or how fast is the camera moving.
  49945. */
  49946. get: function () {
  49947. var pointers = this.inputs.attached["pointers"];
  49948. if (pointers)
  49949. return pointers.panningSensibility;
  49950. return 0;
  49951. },
  49952. set: function (value) {
  49953. var pointers = this.inputs.attached["pointers"];
  49954. if (pointers) {
  49955. pointers.panningSensibility = value;
  49956. }
  49957. },
  49958. enumerable: true,
  49959. configurable: true
  49960. });
  49961. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  49962. /**
  49963. * Gets or Set the list of keyboard keys used to control beta angle in a positive direction.
  49964. */
  49965. get: function () {
  49966. var keyboard = this.inputs.attached["keyboard"];
  49967. if (keyboard)
  49968. return keyboard.keysUp;
  49969. return [];
  49970. },
  49971. set: function (value) {
  49972. var keyboard = this.inputs.attached["keyboard"];
  49973. if (keyboard)
  49974. keyboard.keysUp = value;
  49975. },
  49976. enumerable: true,
  49977. configurable: true
  49978. });
  49979. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  49980. /**
  49981. * Gets or Set the list of keyboard keys used to control beta angle in a negative direction.
  49982. */
  49983. get: function () {
  49984. var keyboard = this.inputs.attached["keyboard"];
  49985. if (keyboard)
  49986. return keyboard.keysDown;
  49987. return [];
  49988. },
  49989. set: function (value) {
  49990. var keyboard = this.inputs.attached["keyboard"];
  49991. if (keyboard)
  49992. keyboard.keysDown = value;
  49993. },
  49994. enumerable: true,
  49995. configurable: true
  49996. });
  49997. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  49998. /**
  49999. * Gets or Set the list of keyboard keys used to control alpha angle in a negative direction.
  50000. */
  50001. get: function () {
  50002. var keyboard = this.inputs.attached["keyboard"];
  50003. if (keyboard)
  50004. return keyboard.keysLeft;
  50005. return [];
  50006. },
  50007. set: function (value) {
  50008. var keyboard = this.inputs.attached["keyboard"];
  50009. if (keyboard)
  50010. keyboard.keysLeft = value;
  50011. },
  50012. enumerable: true,
  50013. configurable: true
  50014. });
  50015. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  50016. /**
  50017. * Gets or Set the list of keyboard keys used to control alpha angle in a positive direction.
  50018. */
  50019. get: function () {
  50020. var keyboard = this.inputs.attached["keyboard"];
  50021. if (keyboard)
  50022. return keyboard.keysRight;
  50023. return [];
  50024. },
  50025. set: function (value) {
  50026. var keyboard = this.inputs.attached["keyboard"];
  50027. if (keyboard)
  50028. keyboard.keysRight = value;
  50029. },
  50030. enumerable: true,
  50031. configurable: true
  50032. });
  50033. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  50034. /**
  50035. * Gets or Set the mouse wheel precision or how fast is the camera zooming.
  50036. */
  50037. get: function () {
  50038. var mousewheel = this.inputs.attached["mousewheel"];
  50039. if (mousewheel)
  50040. return mousewheel.wheelPrecision;
  50041. return 0;
  50042. },
  50043. set: function (value) {
  50044. var mousewheel = this.inputs.attached["mousewheel"];
  50045. if (mousewheel)
  50046. mousewheel.wheelPrecision = value;
  50047. },
  50048. enumerable: true,
  50049. configurable: true
  50050. });
  50051. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  50052. /**
  50053. * Gets or Set the mouse wheel delta percentage or how fast is the camera zooming.
  50054. * It will be used instead of pinchDeltaPrecision if different from 0.
  50055. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  50056. */
  50057. get: function () {
  50058. var mousewheel = this.inputs.attached["mousewheel"];
  50059. if (mousewheel)
  50060. return mousewheel.wheelDeltaPercentage;
  50061. return 0;
  50062. },
  50063. set: function (value) {
  50064. var mousewheel = this.inputs.attached["mousewheel"];
  50065. if (mousewheel)
  50066. mousewheel.wheelDeltaPercentage = value;
  50067. },
  50068. enumerable: true,
  50069. configurable: true
  50070. });
  50071. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  50072. /**
  50073. * Gets the bouncing behavior of the camera if it has been enabled.
  50074. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50075. */
  50076. get: function () {
  50077. return this._bouncingBehavior;
  50078. },
  50079. enumerable: true,
  50080. configurable: true
  50081. });
  50082. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  50083. /**
  50084. * Defines if the bouncing behavior of the camera is enabled on the camera.
  50085. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  50086. */
  50087. get: function () {
  50088. return this._bouncingBehavior != null;
  50089. },
  50090. set: function (value) {
  50091. if (value === this.useBouncingBehavior) {
  50092. return;
  50093. }
  50094. if (value) {
  50095. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  50096. this.addBehavior(this._bouncingBehavior);
  50097. }
  50098. else if (this._bouncingBehavior) {
  50099. this.removeBehavior(this._bouncingBehavior);
  50100. this._bouncingBehavior = null;
  50101. }
  50102. },
  50103. enumerable: true,
  50104. configurable: true
  50105. });
  50106. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  50107. /**
  50108. * Gets the framing behavior of the camera if it has been enabled.
  50109. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50110. */
  50111. get: function () {
  50112. return this._framingBehavior;
  50113. },
  50114. enumerable: true,
  50115. configurable: true
  50116. });
  50117. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  50118. /**
  50119. * Defines if the framing behavior of the camera is enabled on the camera.
  50120. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  50121. */
  50122. get: function () {
  50123. return this._framingBehavior != null;
  50124. },
  50125. set: function (value) {
  50126. if (value === this.useFramingBehavior) {
  50127. return;
  50128. }
  50129. if (value) {
  50130. this._framingBehavior = new BABYLON.FramingBehavior();
  50131. this.addBehavior(this._framingBehavior);
  50132. }
  50133. else if (this._framingBehavior) {
  50134. this.removeBehavior(this._framingBehavior);
  50135. this._framingBehavior = null;
  50136. }
  50137. },
  50138. enumerable: true,
  50139. configurable: true
  50140. });
  50141. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  50142. /**
  50143. * Gets the auto rotation behavior of the camera if it has been enabled.
  50144. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50145. */
  50146. get: function () {
  50147. return this._autoRotationBehavior;
  50148. },
  50149. enumerable: true,
  50150. configurable: true
  50151. });
  50152. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  50153. /**
  50154. * Defines if the auto rotation behavior of the camera is enabled on the camera.
  50155. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  50156. */
  50157. get: function () {
  50158. return this._autoRotationBehavior != null;
  50159. },
  50160. set: function (value) {
  50161. if (value === this.useAutoRotationBehavior) {
  50162. return;
  50163. }
  50164. if (value) {
  50165. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  50166. this.addBehavior(this._autoRotationBehavior);
  50167. }
  50168. else if (this._autoRotationBehavior) {
  50169. this.removeBehavior(this._autoRotationBehavior);
  50170. this._autoRotationBehavior = null;
  50171. }
  50172. },
  50173. enumerable: true,
  50174. configurable: true
  50175. });
  50176. // Cache
  50177. /** @hidden */
  50178. ArcRotateCamera.prototype._initCache = function () {
  50179. _super.prototype._initCache.call(this);
  50180. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  50181. this._cache.alpha = undefined;
  50182. this._cache.beta = undefined;
  50183. this._cache.radius = undefined;
  50184. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  50185. };
  50186. /** @hidden */
  50187. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  50188. if (!ignoreParentClass) {
  50189. _super.prototype._updateCache.call(this);
  50190. }
  50191. this._cache._target.copyFrom(this._getTargetPosition());
  50192. this._cache.alpha = this.alpha;
  50193. this._cache.beta = this.beta;
  50194. this._cache.radius = this.radius;
  50195. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  50196. };
  50197. ArcRotateCamera.prototype._getTargetPosition = function () {
  50198. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  50199. var pos = this._targetHost.getAbsolutePosition();
  50200. if (this._targetBoundingCenter) {
  50201. pos.addToRef(this._targetBoundingCenter, this._target);
  50202. }
  50203. else {
  50204. this._target.copyFrom(pos);
  50205. }
  50206. }
  50207. var lockedTargetPosition = this._getLockedTargetPosition();
  50208. if (lockedTargetPosition) {
  50209. return lockedTargetPosition;
  50210. }
  50211. return this._target;
  50212. };
  50213. /**
  50214. * Stores the current state of the camera (alpha, beta, radius and target)
  50215. * @returns the camera itself
  50216. */
  50217. ArcRotateCamera.prototype.storeState = function () {
  50218. this._storedAlpha = this.alpha;
  50219. this._storedBeta = this.beta;
  50220. this._storedRadius = this.radius;
  50221. this._storedTarget = this._getTargetPosition().clone();
  50222. return _super.prototype.storeState.call(this);
  50223. };
  50224. /**
  50225. * @hidden
  50226. * Restored camera state. You must call storeState() first
  50227. */
  50228. ArcRotateCamera.prototype._restoreStateValues = function () {
  50229. if (!_super.prototype._restoreStateValues.call(this)) {
  50230. return false;
  50231. }
  50232. this.alpha = this._storedAlpha;
  50233. this.beta = this._storedBeta;
  50234. this.radius = this._storedRadius;
  50235. this.setTarget(this._storedTarget.clone());
  50236. this.inertialAlphaOffset = 0;
  50237. this.inertialBetaOffset = 0;
  50238. this.inertialRadiusOffset = 0;
  50239. this.inertialPanningX = 0;
  50240. this.inertialPanningY = 0;
  50241. return true;
  50242. };
  50243. // Synchronized
  50244. /** @hidden */
  50245. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  50246. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  50247. return false;
  50248. return this._cache._target.equals(this._getTargetPosition())
  50249. && this._cache.alpha === this.alpha
  50250. && this._cache.beta === this.beta
  50251. && this._cache.radius === this.radius
  50252. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  50253. };
  50254. /**
  50255. * Attached controls to the current camera.
  50256. * @param element Defines the element the controls should be listened from
  50257. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  50258. * @param useCtrlForPanning Defines whether ctrl is used for paning within the controls
  50259. * @param panningMouseButton Defines whether panning is allowed through mouse click button
  50260. */
  50261. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  50262. var _this = this;
  50263. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  50264. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  50265. this._useCtrlForPanning = useCtrlForPanning;
  50266. this._panningMouseButton = panningMouseButton;
  50267. this.inputs.attachElement(element, noPreventDefault);
  50268. this._reset = function () {
  50269. _this.inertialAlphaOffset = 0;
  50270. _this.inertialBetaOffset = 0;
  50271. _this.inertialRadiusOffset = 0;
  50272. _this.inertialPanningX = 0;
  50273. _this.inertialPanningY = 0;
  50274. };
  50275. };
  50276. /**
  50277. * Detach the current controls from the camera.
  50278. * The camera will stop reacting to inputs.
  50279. * @param element Defines the element to stop listening the inputs from
  50280. */
  50281. ArcRotateCamera.prototype.detachControl = function (element) {
  50282. this.inputs.detachElement(element);
  50283. if (this._reset) {
  50284. this._reset();
  50285. }
  50286. };
  50287. /** @hidden */
  50288. ArcRotateCamera.prototype._checkInputs = function () {
  50289. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  50290. if (this._collisionTriggered) {
  50291. return;
  50292. }
  50293. this.inputs.checkInputs();
  50294. // Inertia
  50295. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  50296. var inertialAlphaOffset = this.inertialAlphaOffset;
  50297. if (this.beta <= 0)
  50298. inertialAlphaOffset *= -1;
  50299. if (this.getScene().useRightHandedSystem)
  50300. inertialAlphaOffset *= -1;
  50301. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  50302. inertialAlphaOffset *= -1;
  50303. this.alpha += inertialAlphaOffset;
  50304. this.beta += this.inertialBetaOffset;
  50305. this.radius -= this.inertialRadiusOffset;
  50306. this.inertialAlphaOffset *= this.inertia;
  50307. this.inertialBetaOffset *= this.inertia;
  50308. this.inertialRadiusOffset *= this.inertia;
  50309. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  50310. this.inertialAlphaOffset = 0;
  50311. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  50312. this.inertialBetaOffset = 0;
  50313. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  50314. this.inertialRadiusOffset = 0;
  50315. }
  50316. // Panning inertia
  50317. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  50318. if (!this._localDirection) {
  50319. this._localDirection = BABYLON.Vector3.Zero();
  50320. this._transformedDirection = BABYLON.Vector3.Zero();
  50321. }
  50322. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  50323. this._localDirection.multiplyInPlace(this.panningAxis);
  50324. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  50325. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  50326. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  50327. if (!this.panningAxis.y) {
  50328. this._transformedDirection.y = 0;
  50329. }
  50330. if (!this._targetHost) {
  50331. if (this.panningDistanceLimit) {
  50332. this._transformedDirection.addInPlace(this._target);
  50333. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  50334. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  50335. this._target.copyFrom(this._transformedDirection);
  50336. }
  50337. }
  50338. else {
  50339. this._target.addInPlace(this._transformedDirection);
  50340. }
  50341. }
  50342. this.inertialPanningX *= this.panningInertia;
  50343. this.inertialPanningY *= this.panningInertia;
  50344. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  50345. this.inertialPanningX = 0;
  50346. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  50347. this.inertialPanningY = 0;
  50348. }
  50349. // Limits
  50350. this._checkLimits();
  50351. _super.prototype._checkInputs.call(this);
  50352. };
  50353. ArcRotateCamera.prototype._checkLimits = function () {
  50354. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  50355. if (this.allowUpsideDown && this.beta > Math.PI) {
  50356. this.beta = this.beta - (2 * Math.PI);
  50357. }
  50358. }
  50359. else {
  50360. if (this.beta < this.lowerBetaLimit) {
  50361. this.beta = this.lowerBetaLimit;
  50362. }
  50363. }
  50364. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  50365. if (this.allowUpsideDown && this.beta < -Math.PI) {
  50366. this.beta = this.beta + (2 * Math.PI);
  50367. }
  50368. }
  50369. else {
  50370. if (this.beta > this.upperBetaLimit) {
  50371. this.beta = this.upperBetaLimit;
  50372. }
  50373. }
  50374. if (this.lowerAlphaLimit !== null && this.alpha < this.lowerAlphaLimit) {
  50375. this.alpha = this.lowerAlphaLimit;
  50376. }
  50377. if (this.upperAlphaLimit !== null && this.alpha > this.upperAlphaLimit) {
  50378. this.alpha = this.upperAlphaLimit;
  50379. }
  50380. if (this.lowerRadiusLimit !== null && this.radius < this.lowerRadiusLimit) {
  50381. this.radius = this.lowerRadiusLimit;
  50382. }
  50383. if (this.upperRadiusLimit !== null && this.radius > this.upperRadiusLimit) {
  50384. this.radius = this.upperRadiusLimit;
  50385. }
  50386. };
  50387. /**
  50388. * Rebuilds angles (alpha, beta) and radius from the give position and target.
  50389. */
  50390. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  50391. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  50392. this.radius = this._computationVector.length();
  50393. if (this.radius === 0) {
  50394. this.radius = 0.0001; // Just to avoid division by zero
  50395. }
  50396. // Alpha
  50397. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  50398. if (this._computationVector.z < 0) {
  50399. this.alpha = 2 * Math.PI - this.alpha;
  50400. }
  50401. // Beta
  50402. this.beta = Math.acos(this._computationVector.y / this.radius);
  50403. this._checkLimits();
  50404. };
  50405. /**
  50406. * Use a position to define the current camera related information like aplha, beta and radius
  50407. * @param position Defines the position to set the camera at
  50408. */
  50409. ArcRotateCamera.prototype.setPosition = function (position) {
  50410. if (this.position.equals(position)) {
  50411. return;
  50412. }
  50413. this.position.copyFrom(position);
  50414. this.rebuildAnglesAndRadius();
  50415. };
  50416. /**
  50417. * Defines the target the camera should look at.
  50418. * This will automatically adapt alpha beta and radius to fit within the new target.
  50419. * @param target Defines the new target as a Vector or a mesh
  50420. * @param toBoundingCenter In case of a mesh target, defines wether to target the mesh position or its bounding information center
  50421. * @param allowSamePosition If false, prevents reapplying the new computed position if it is identical to the current one (optim)
  50422. */
  50423. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  50424. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  50425. if (allowSamePosition === void 0) { allowSamePosition = false; }
  50426. if (target.getBoundingInfo) {
  50427. if (toBoundingCenter) {
  50428. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  50429. }
  50430. else {
  50431. this._targetBoundingCenter = null;
  50432. }
  50433. this._targetHost = target;
  50434. this._target = this._getTargetPosition();
  50435. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  50436. }
  50437. else {
  50438. var newTarget = target;
  50439. var currentTarget = this._getTargetPosition();
  50440. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  50441. return;
  50442. }
  50443. this._targetHost = null;
  50444. this._target = newTarget;
  50445. this._targetBoundingCenter = null;
  50446. this.onMeshTargetChangedObservable.notifyObservers(null);
  50447. }
  50448. this.rebuildAnglesAndRadius();
  50449. };
  50450. /** @hidden */
  50451. ArcRotateCamera.prototype._getViewMatrix = function () {
  50452. // Compute
  50453. var cosa = Math.cos(this.alpha);
  50454. var sina = Math.sin(this.alpha);
  50455. var cosb = Math.cos(this.beta);
  50456. var sinb = Math.sin(this.beta);
  50457. if (sinb === 0) {
  50458. sinb = 0.0001;
  50459. }
  50460. var target = this._getTargetPosition();
  50461. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  50462. target.addToRef(this._computationVector, this._newPosition);
  50463. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  50464. if (!this._collider) {
  50465. this._collider = new BABYLON.Collider();
  50466. }
  50467. this._collider._radius = this.collisionRadius;
  50468. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  50469. this._collisionTriggered = true;
  50470. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  50471. }
  50472. else {
  50473. this.position.copyFrom(this._newPosition);
  50474. var up = this.upVector;
  50475. if (this.allowUpsideDown && sinb < 0) {
  50476. up = up.clone();
  50477. up = up.negate();
  50478. }
  50479. this._computeViewMatrix(this.position, target, up);
  50480. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  50481. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  50482. }
  50483. this._currentTarget = target;
  50484. return this._viewMatrix;
  50485. };
  50486. /**
  50487. * Zooms on a mesh to be at the min distance where we could see it fully in the current viewport.
  50488. * @param meshes Defines the mesh to zoom on
  50489. * @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)
  50490. */
  50491. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  50492. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50493. meshes = meshes || this.getScene().meshes;
  50494. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  50495. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  50496. this.radius = distance * this.zoomOnFactor;
  50497. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  50498. };
  50499. /**
  50500. * Focus on a mesh or a bounding box. This adapts the target and maxRadius if necessary but does not update the current radius.
  50501. * The target will be changed but the radius
  50502. * @param meshesOrMinMaxVectorAndDistance Defines the mesh or bounding info to focus on
  50503. * @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)
  50504. */
  50505. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  50506. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  50507. var meshesOrMinMaxVector;
  50508. var distance;
  50509. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  50510. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  50511. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  50512. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  50513. }
  50514. else { //minMaxVector and distance
  50515. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  50516. meshesOrMinMaxVector = minMaxVectorAndDistance;
  50517. distance = minMaxVectorAndDistance.distance;
  50518. }
  50519. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  50520. if (!doNotUpdateMaxZ) {
  50521. this.maxZ = distance * 2;
  50522. }
  50523. };
  50524. /**
  50525. * @override
  50526. * Override Camera.createRigCamera
  50527. */
  50528. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  50529. var alphaShift = 0;
  50530. switch (this.cameraRigMode) {
  50531. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50532. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50533. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50534. case BABYLON.Camera.RIG_MODE_VR:
  50535. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  50536. break;
  50537. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50538. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  50539. break;
  50540. }
  50541. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  50542. rigCam._cameraRigParams = {};
  50543. return rigCam;
  50544. };
  50545. /**
  50546. * @hidden
  50547. * @override
  50548. * Override Camera._updateRigCameras
  50549. */
  50550. ArcRotateCamera.prototype._updateRigCameras = function () {
  50551. var camLeft = this._rigCameras[0];
  50552. var camRight = this._rigCameras[1];
  50553. camLeft.beta = camRight.beta = this.beta;
  50554. camLeft.radius = camRight.radius = this.radius;
  50555. switch (this.cameraRigMode) {
  50556. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  50557. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  50558. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  50559. case BABYLON.Camera.RIG_MODE_VR:
  50560. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50561. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50562. break;
  50563. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  50564. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  50565. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  50566. break;
  50567. }
  50568. _super.prototype._updateRigCameras.call(this);
  50569. };
  50570. /**
  50571. * Destroy the camera and release the current resources hold by it.
  50572. */
  50573. ArcRotateCamera.prototype.dispose = function () {
  50574. this.inputs.clear();
  50575. _super.prototype.dispose.call(this);
  50576. };
  50577. /**
  50578. * Gets the current object class name.
  50579. * @return the class name
  50580. */
  50581. ArcRotateCamera.prototype.getClassName = function () {
  50582. return "ArcRotateCamera";
  50583. };
  50584. __decorate([
  50585. BABYLON.serialize()
  50586. ], ArcRotateCamera.prototype, "alpha", void 0);
  50587. __decorate([
  50588. BABYLON.serialize()
  50589. ], ArcRotateCamera.prototype, "beta", void 0);
  50590. __decorate([
  50591. BABYLON.serialize()
  50592. ], ArcRotateCamera.prototype, "radius", void 0);
  50593. __decorate([
  50594. BABYLON.serializeAsVector3("target")
  50595. ], ArcRotateCamera.prototype, "_target", void 0);
  50596. __decorate([
  50597. BABYLON.serialize()
  50598. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  50599. __decorate([
  50600. BABYLON.serialize()
  50601. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  50602. __decorate([
  50603. BABYLON.serialize()
  50604. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  50605. __decorate([
  50606. BABYLON.serialize()
  50607. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  50608. __decorate([
  50609. BABYLON.serialize()
  50610. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  50611. __decorate([
  50612. BABYLON.serialize()
  50613. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  50614. __decorate([
  50615. BABYLON.serialize()
  50616. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  50617. __decorate([
  50618. BABYLON.serialize()
  50619. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  50620. __decorate([
  50621. BABYLON.serialize()
  50622. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  50623. __decorate([
  50624. BABYLON.serialize()
  50625. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  50626. __decorate([
  50627. BABYLON.serialize()
  50628. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  50629. __decorate([
  50630. BABYLON.serialize()
  50631. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  50632. __decorate([
  50633. BABYLON.serialize()
  50634. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  50635. __decorate([
  50636. BABYLON.serializeAsVector3()
  50637. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  50638. __decorate([
  50639. BABYLON.serialize()
  50640. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  50641. __decorate([
  50642. BABYLON.serialize()
  50643. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  50644. __decorate([
  50645. BABYLON.serialize()
  50646. ], ArcRotateCamera.prototype, "targetScreenOffset", void 0);
  50647. __decorate([
  50648. BABYLON.serialize()
  50649. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  50650. __decorate([
  50651. BABYLON.serialize()
  50652. ], ArcRotateCamera.prototype, "useInputToRestoreState", void 0);
  50653. return ArcRotateCamera;
  50654. }(BABYLON.TargetCamera));
  50655. BABYLON.ArcRotateCamera = ArcRotateCamera;
  50656. })(BABYLON || (BABYLON = {}));
  50657. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  50658. var BABYLON;
  50659. (function (BABYLON) {
  50660. BABYLON.Node.AddNodeConstructor("Light_Type_3", function (name, scene) {
  50661. return function () { return new HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  50662. });
  50663. /**
  50664. * The HemisphericLight simulates the ambient environment light,
  50665. * so the passed direction is the light reflection direction, not the incoming direction.
  50666. */
  50667. var HemisphericLight = /** @class */ (function (_super) {
  50668. __extends(HemisphericLight, _super);
  50669. /**
  50670. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  50671. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  50672. * The HemisphericLight can't cast shadows.
  50673. * Documentation : http://doc.babylonjs.com/tutorials/lights
  50674. * @param name The friendly name of the light
  50675. * @param direction The direction of the light reflection
  50676. * @param scene The scene the light belongs to
  50677. */
  50678. function HemisphericLight(name, direction, scene) {
  50679. var _this = _super.call(this, name, scene) || this;
  50680. /**
  50681. * The groundColor is the light in the opposite direction to the one specified during creation.
  50682. * 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.
  50683. */
  50684. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  50685. _this.direction = direction || BABYLON.Vector3.Up();
  50686. return _this;
  50687. }
  50688. HemisphericLight.prototype._buildUniformLayout = function () {
  50689. this._uniformBuffer.addUniform("vLightData", 4);
  50690. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50691. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50692. this._uniformBuffer.addUniform("vLightGround", 3);
  50693. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50694. this._uniformBuffer.addUniform("depthValues", 2);
  50695. this._uniformBuffer.create();
  50696. };
  50697. /**
  50698. * Returns the string "HemisphericLight".
  50699. * @return The class name
  50700. */
  50701. HemisphericLight.prototype.getClassName = function () {
  50702. return "HemisphericLight";
  50703. };
  50704. /**
  50705. * Sets the HemisphericLight direction towards the passed target (Vector3).
  50706. * Returns the updated direction.
  50707. * @param target The target the direction should point to
  50708. * @return The computed direction
  50709. */
  50710. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  50711. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  50712. return this.direction;
  50713. };
  50714. /**
  50715. * Returns the shadow generator associated to the light.
  50716. * @returns Always null for hemispheric lights because it does not support shadows.
  50717. */
  50718. HemisphericLight.prototype.getShadowGenerator = function () {
  50719. return null;
  50720. };
  50721. /**
  50722. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  50723. * @param effect The effect to update
  50724. * @param lightIndex The index of the light in the effect to update
  50725. * @returns The hemispheric light
  50726. */
  50727. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  50728. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50729. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  50730. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  50731. return this;
  50732. };
  50733. /**
  50734. * Computes the world matrix of the node
  50735. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50736. * @param useWasUpdatedFlag defines a reserved property
  50737. * @returns the world matrix
  50738. */
  50739. HemisphericLight.prototype.computeWorldMatrix = function (force, useWasUpdatedFlag) {
  50740. if (!this._worldMatrix) {
  50741. this._worldMatrix = BABYLON.Matrix.Identity();
  50742. }
  50743. return this._worldMatrix;
  50744. };
  50745. /**
  50746. * Returns the integer 3.
  50747. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50748. */
  50749. HemisphericLight.prototype.getTypeID = function () {
  50750. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  50751. };
  50752. /**
  50753. * Prepares the list of defines specific to the light type.
  50754. * @param defines the list of defines
  50755. * @param lightIndex defines the index of the light for the effect
  50756. */
  50757. HemisphericLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  50758. defines["HEMILIGHT" + lightIndex] = true;
  50759. };
  50760. __decorate([
  50761. BABYLON.serializeAsColor3()
  50762. ], HemisphericLight.prototype, "groundColor", void 0);
  50763. __decorate([
  50764. BABYLON.serializeAsVector3()
  50765. ], HemisphericLight.prototype, "direction", void 0);
  50766. return HemisphericLight;
  50767. }(BABYLON.Light));
  50768. BABYLON.HemisphericLight = HemisphericLight;
  50769. })(BABYLON || (BABYLON = {}));
  50770. //# sourceMappingURL=babylon.hemisphericLight.js.map
  50771. var BABYLON;
  50772. (function (BABYLON) {
  50773. /**
  50774. * Base implementation IShadowLight
  50775. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  50776. */
  50777. var ShadowLight = /** @class */ (function (_super) {
  50778. __extends(ShadowLight, _super);
  50779. function ShadowLight() {
  50780. var _this = _super !== null && _super.apply(this, arguments) || this;
  50781. _this._needProjectionMatrixCompute = true;
  50782. return _this;
  50783. }
  50784. ShadowLight.prototype._setPosition = function (value) {
  50785. this._position = value;
  50786. };
  50787. Object.defineProperty(ShadowLight.prototype, "position", {
  50788. /**
  50789. * Sets the position the shadow will be casted from. Also use as the light position for both
  50790. * point and spot lights.
  50791. */
  50792. get: function () {
  50793. return this._position;
  50794. },
  50795. /**
  50796. * Sets the position the shadow will be casted from. Also use as the light position for both
  50797. * point and spot lights.
  50798. */
  50799. set: function (value) {
  50800. this._setPosition(value);
  50801. },
  50802. enumerable: true,
  50803. configurable: true
  50804. });
  50805. ShadowLight.prototype._setDirection = function (value) {
  50806. this._direction = value;
  50807. };
  50808. Object.defineProperty(ShadowLight.prototype, "direction", {
  50809. /**
  50810. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  50811. * Also use as the light direction on spot and directional lights.
  50812. */
  50813. get: function () {
  50814. return this._direction;
  50815. },
  50816. /**
  50817. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  50818. * Also use as the light direction on spot and directional lights.
  50819. */
  50820. set: function (value) {
  50821. this._setDirection(value);
  50822. },
  50823. enumerable: true,
  50824. configurable: true
  50825. });
  50826. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  50827. /**
  50828. * Gets the shadow projection clipping minimum z value.
  50829. */
  50830. get: function () {
  50831. return this._shadowMinZ;
  50832. },
  50833. /**
  50834. * Sets the shadow projection clipping minimum z value.
  50835. */
  50836. set: function (value) {
  50837. this._shadowMinZ = value;
  50838. this.forceProjectionMatrixCompute();
  50839. },
  50840. enumerable: true,
  50841. configurable: true
  50842. });
  50843. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  50844. /**
  50845. * Sets the shadow projection clipping maximum z value.
  50846. */
  50847. get: function () {
  50848. return this._shadowMaxZ;
  50849. },
  50850. /**
  50851. * Gets the shadow projection clipping maximum z value.
  50852. */
  50853. set: function (value) {
  50854. this._shadowMaxZ = value;
  50855. this.forceProjectionMatrixCompute();
  50856. },
  50857. enumerable: true,
  50858. configurable: true
  50859. });
  50860. /**
  50861. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  50862. * @returns true if the information has been computed, false if it does not need to (no parenting)
  50863. */
  50864. ShadowLight.prototype.computeTransformedInformation = function () {
  50865. if (this.parent && this.parent.getWorldMatrix) {
  50866. if (!this.transformedPosition) {
  50867. this.transformedPosition = BABYLON.Vector3.Zero();
  50868. }
  50869. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  50870. // In case the direction is present.
  50871. if (this.direction) {
  50872. if (!this.transformedDirection) {
  50873. this.transformedDirection = BABYLON.Vector3.Zero();
  50874. }
  50875. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  50876. }
  50877. return true;
  50878. }
  50879. return false;
  50880. };
  50881. /**
  50882. * Return the depth scale used for the shadow map.
  50883. * @returns the depth scale.
  50884. */
  50885. ShadowLight.prototype.getDepthScale = function () {
  50886. return 50.0;
  50887. };
  50888. /**
  50889. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  50890. * @param faceIndex The index of the face we are computed the direction to generate shadow
  50891. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  50892. */
  50893. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  50894. return this.transformedDirection ? this.transformedDirection : this.direction;
  50895. };
  50896. /**
  50897. * Returns the ShadowLight absolute position in the World.
  50898. * @returns the position vector in world space
  50899. */
  50900. ShadowLight.prototype.getAbsolutePosition = function () {
  50901. return this.transformedPosition ? this.transformedPosition : this.position;
  50902. };
  50903. /**
  50904. * Sets the ShadowLight direction toward the passed target.
  50905. * @param target The point tot target in local space
  50906. * @returns the updated ShadowLight direction
  50907. */
  50908. ShadowLight.prototype.setDirectionToTarget = function (target) {
  50909. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  50910. return this.direction;
  50911. };
  50912. /**
  50913. * Returns the light rotation in euler definition.
  50914. * @returns the x y z rotation in local space.
  50915. */
  50916. ShadowLight.prototype.getRotation = function () {
  50917. this.direction.normalize();
  50918. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  50919. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  50920. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  50921. };
  50922. /**
  50923. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  50924. * @returns true if a cube texture needs to be use
  50925. */
  50926. ShadowLight.prototype.needCube = function () {
  50927. return false;
  50928. };
  50929. /**
  50930. * Detects if the projection matrix requires to be recomputed this frame.
  50931. * @returns true if it requires to be recomputed otherwise, false.
  50932. */
  50933. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  50934. return this._needProjectionMatrixCompute;
  50935. };
  50936. /**
  50937. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  50938. */
  50939. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  50940. this._needProjectionMatrixCompute = true;
  50941. };
  50942. /** @hidden */
  50943. ShadowLight.prototype._initCache = function () {
  50944. _super.prototype._initCache.call(this);
  50945. this._cache.position = BABYLON.Vector3.Zero();
  50946. };
  50947. /** @hidden */
  50948. ShadowLight.prototype._isSynchronized = function () {
  50949. if (!this._cache.position.equals(this.position))
  50950. return false;
  50951. return true;
  50952. };
  50953. /**
  50954. * Computes the world matrix of the node
  50955. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  50956. * @returns the world matrix
  50957. */
  50958. ShadowLight.prototype.computeWorldMatrix = function (force) {
  50959. if (!force && this.isSynchronized()) {
  50960. this._currentRenderId = this.getScene().getRenderId();
  50961. return this._worldMatrix;
  50962. }
  50963. this._updateCache();
  50964. this._cache.position.copyFrom(this.position);
  50965. if (!this._worldMatrix) {
  50966. this._worldMatrix = BABYLON.Matrix.Identity();
  50967. }
  50968. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  50969. if (this.parent && this.parent.getWorldMatrix) {
  50970. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  50971. this._markSyncedWithParent();
  50972. }
  50973. // Cache the determinant
  50974. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  50975. return this._worldMatrix;
  50976. };
  50977. /**
  50978. * Gets the minZ used for shadow according to both the scene and the light.
  50979. * @param activeCamera The camera we are returning the min for
  50980. * @returns the depth min z
  50981. */
  50982. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  50983. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  50984. };
  50985. /**
  50986. * Gets the maxZ used for shadow according to both the scene and the light.
  50987. * @param activeCamera The camera we are returning the max for
  50988. * @returns the depth max z
  50989. */
  50990. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  50991. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  50992. };
  50993. /**
  50994. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  50995. * @param matrix The materix to updated with the projection information
  50996. * @param viewMatrix The transform matrix of the light
  50997. * @param renderList The list of mesh to render in the map
  50998. * @returns The current light
  50999. */
  51000. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51001. if (this.customProjectionMatrixBuilder) {
  51002. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  51003. }
  51004. else {
  51005. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51006. }
  51007. return this;
  51008. };
  51009. __decorate([
  51010. BABYLON.serializeAsVector3()
  51011. ], ShadowLight.prototype, "position", null);
  51012. __decorate([
  51013. BABYLON.serializeAsVector3()
  51014. ], ShadowLight.prototype, "direction", null);
  51015. __decorate([
  51016. BABYLON.serialize()
  51017. ], ShadowLight.prototype, "shadowMinZ", null);
  51018. __decorate([
  51019. BABYLON.serialize()
  51020. ], ShadowLight.prototype, "shadowMaxZ", null);
  51021. return ShadowLight;
  51022. }(BABYLON.Light));
  51023. BABYLON.ShadowLight = ShadowLight;
  51024. })(BABYLON || (BABYLON = {}));
  51025. //# sourceMappingURL=babylon.shadowLight.js.map
  51026. var BABYLON;
  51027. (function (BABYLON) {
  51028. BABYLON.Node.AddNodeConstructor("Light_Type_0", function (name, scene) {
  51029. return function () { return new PointLight(name, BABYLON.Vector3.Zero(), scene); };
  51030. });
  51031. /**
  51032. * A point light is a light defined by an unique point in world space.
  51033. * The light is emitted in every direction from this point.
  51034. * A good example of a point light is a standard light bulb.
  51035. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51036. */
  51037. var PointLight = /** @class */ (function (_super) {
  51038. __extends(PointLight, _super);
  51039. /**
  51040. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  51041. * A PointLight emits the light in every direction.
  51042. * It can cast shadows.
  51043. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  51044. * ```javascript
  51045. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  51046. * ```
  51047. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51048. * @param name The light friendly name
  51049. * @param position The position of the point light in the scene
  51050. * @param scene The scene the lights belongs to
  51051. */
  51052. function PointLight(name, position, scene) {
  51053. var _this = _super.call(this, name, scene) || this;
  51054. _this._shadowAngle = Math.PI / 2;
  51055. _this.position = position;
  51056. return _this;
  51057. }
  51058. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  51059. /**
  51060. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51061. * This specifies what angle the shadow will use to be created.
  51062. *
  51063. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51064. */
  51065. get: function () {
  51066. return this._shadowAngle;
  51067. },
  51068. /**
  51069. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51070. * This specifies what angle the shadow will use to be created.
  51071. *
  51072. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  51073. */
  51074. set: function (value) {
  51075. this._shadowAngle = value;
  51076. this.forceProjectionMatrixCompute();
  51077. },
  51078. enumerable: true,
  51079. configurable: true
  51080. });
  51081. Object.defineProperty(PointLight.prototype, "direction", {
  51082. /**
  51083. * Gets the direction if it has been set.
  51084. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51085. */
  51086. get: function () {
  51087. return this._direction;
  51088. },
  51089. /**
  51090. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  51091. */
  51092. set: function (value) {
  51093. var previousNeedCube = this.needCube();
  51094. this._direction = value;
  51095. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  51096. this._shadowGenerator.recreateShadowMap();
  51097. }
  51098. },
  51099. enumerable: true,
  51100. configurable: true
  51101. });
  51102. /**
  51103. * Returns the string "PointLight"
  51104. * @returns the class name
  51105. */
  51106. PointLight.prototype.getClassName = function () {
  51107. return "PointLight";
  51108. };
  51109. /**
  51110. * Returns the integer 0.
  51111. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51112. */
  51113. PointLight.prototype.getTypeID = function () {
  51114. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  51115. };
  51116. /**
  51117. * Specifies wether or not the shadowmap should be a cube texture.
  51118. * @returns true if the shadowmap needs to be a cube texture.
  51119. */
  51120. PointLight.prototype.needCube = function () {
  51121. return !this.direction;
  51122. };
  51123. /**
  51124. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  51125. * @param faceIndex The index of the face we are computed the direction to generate shadow
  51126. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  51127. */
  51128. PointLight.prototype.getShadowDirection = function (faceIndex) {
  51129. if (this.direction) {
  51130. return _super.prototype.getShadowDirection.call(this, faceIndex);
  51131. }
  51132. else {
  51133. switch (faceIndex) {
  51134. case 0:
  51135. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  51136. case 1:
  51137. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  51138. case 2:
  51139. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  51140. case 3:
  51141. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  51142. case 4:
  51143. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  51144. case 5:
  51145. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  51146. }
  51147. }
  51148. return BABYLON.Vector3.Zero();
  51149. };
  51150. /**
  51151. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  51152. * - fov = PI / 2
  51153. * - aspect ratio : 1.0
  51154. * - z-near and far equal to the active camera minZ and maxZ.
  51155. * Returns the PointLight.
  51156. */
  51157. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51158. var activeCamera = this.getScene().activeCamera;
  51159. if (!activeCamera) {
  51160. return;
  51161. }
  51162. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51163. };
  51164. PointLight.prototype._buildUniformLayout = function () {
  51165. this._uniformBuffer.addUniform("vLightData", 4);
  51166. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51167. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51168. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51169. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51170. this._uniformBuffer.addUniform("depthValues", 2);
  51171. this._uniformBuffer.create();
  51172. };
  51173. /**
  51174. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  51175. * @param effect The effect to update
  51176. * @param lightIndex The index of the light in the effect to update
  51177. * @returns The point light
  51178. */
  51179. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  51180. if (this.computeTransformedInformation()) {
  51181. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  51182. }
  51183. else {
  51184. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  51185. }
  51186. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, 0, 0, lightIndex);
  51187. return this;
  51188. };
  51189. /**
  51190. * Prepares the list of defines specific to the light type.
  51191. * @param defines the list of defines
  51192. * @param lightIndex defines the index of the light for the effect
  51193. */
  51194. PointLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51195. defines["POINTLIGHT" + lightIndex] = true;
  51196. };
  51197. __decorate([
  51198. BABYLON.serialize()
  51199. ], PointLight.prototype, "shadowAngle", null);
  51200. return PointLight;
  51201. }(BABYLON.ShadowLight));
  51202. BABYLON.PointLight = PointLight;
  51203. })(BABYLON || (BABYLON = {}));
  51204. //# sourceMappingURL=babylon.pointLight.js.map
  51205. var BABYLON;
  51206. (function (BABYLON) {
  51207. BABYLON.Node.AddNodeConstructor("Light_Type_1", function (name, scene) {
  51208. return function () { return new DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  51209. });
  51210. /**
  51211. * A directional light is defined by a direction (what a surprise!).
  51212. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  51213. * 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.
  51214. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51215. */
  51216. var DirectionalLight = /** @class */ (function (_super) {
  51217. __extends(DirectionalLight, _super);
  51218. /**
  51219. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  51220. * The directional light is emitted from everywhere in the given direction.
  51221. * It can cast shadows.
  51222. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51223. * @param name The friendly name of the light
  51224. * @param direction The direction of the light
  51225. * @param scene The scene the light belongs to
  51226. */
  51227. function DirectionalLight(name, direction, scene) {
  51228. var _this = _super.call(this, name, scene) || this;
  51229. _this._shadowFrustumSize = 0;
  51230. _this._shadowOrthoScale = 0.1;
  51231. /**
  51232. * Automatically compute the projection matrix to best fit (including all the casters)
  51233. * on each frame.
  51234. */
  51235. _this.autoUpdateExtends = true;
  51236. // Cache
  51237. _this._orthoLeft = Number.MAX_VALUE;
  51238. _this._orthoRight = Number.MIN_VALUE;
  51239. _this._orthoTop = Number.MIN_VALUE;
  51240. _this._orthoBottom = Number.MAX_VALUE;
  51241. _this.position = direction.scale(-1.0);
  51242. _this.direction = direction;
  51243. return _this;
  51244. }
  51245. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  51246. /**
  51247. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  51248. */
  51249. get: function () {
  51250. return this._shadowFrustumSize;
  51251. },
  51252. /**
  51253. * Specifies a fix frustum size for the shadow generation.
  51254. */
  51255. set: function (value) {
  51256. this._shadowFrustumSize = value;
  51257. this.forceProjectionMatrixCompute();
  51258. },
  51259. enumerable: true,
  51260. configurable: true
  51261. });
  51262. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  51263. /**
  51264. * Gets the shadow projection scale against the optimal computed one.
  51265. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51266. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51267. */
  51268. get: function () {
  51269. return this._shadowOrthoScale;
  51270. },
  51271. /**
  51272. * Sets the shadow projection scale against the optimal computed one.
  51273. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  51274. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  51275. */
  51276. set: function (value) {
  51277. this._shadowOrthoScale = value;
  51278. this.forceProjectionMatrixCompute();
  51279. },
  51280. enumerable: true,
  51281. configurable: true
  51282. });
  51283. /**
  51284. * Returns the string "DirectionalLight".
  51285. * @return The class name
  51286. */
  51287. DirectionalLight.prototype.getClassName = function () {
  51288. return "DirectionalLight";
  51289. };
  51290. /**
  51291. * Returns the integer 1.
  51292. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51293. */
  51294. DirectionalLight.prototype.getTypeID = function () {
  51295. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  51296. };
  51297. /**
  51298. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  51299. * Returns the DirectionalLight Shadow projection matrix.
  51300. */
  51301. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51302. if (this.shadowFrustumSize > 0) {
  51303. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  51304. }
  51305. else {
  51306. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  51307. }
  51308. };
  51309. /**
  51310. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  51311. * Returns the DirectionalLight Shadow projection matrix.
  51312. */
  51313. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  51314. var activeCamera = this.getScene().activeCamera;
  51315. if (!activeCamera) {
  51316. return;
  51317. }
  51318. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  51319. };
  51320. /**
  51321. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  51322. * Returns the DirectionalLight Shadow projection matrix.
  51323. */
  51324. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51325. var activeCamera = this.getScene().activeCamera;
  51326. if (!activeCamera) {
  51327. return;
  51328. }
  51329. // Check extends
  51330. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  51331. var tempVector3 = BABYLON.Vector3.Zero();
  51332. this._orthoLeft = Number.MAX_VALUE;
  51333. this._orthoRight = Number.MIN_VALUE;
  51334. this._orthoTop = Number.MIN_VALUE;
  51335. this._orthoBottom = Number.MAX_VALUE;
  51336. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  51337. var mesh = renderList[meshIndex];
  51338. if (!mesh) {
  51339. continue;
  51340. }
  51341. var boundingInfo = mesh.getBoundingInfo();
  51342. var boundingBox = boundingInfo.boundingBox;
  51343. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  51344. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  51345. if (tempVector3.x < this._orthoLeft)
  51346. this._orthoLeft = tempVector3.x;
  51347. if (tempVector3.y < this._orthoBottom)
  51348. this._orthoBottom = tempVector3.y;
  51349. if (tempVector3.x > this._orthoRight)
  51350. this._orthoRight = tempVector3.x;
  51351. if (tempVector3.y > this._orthoTop)
  51352. this._orthoTop = tempVector3.y;
  51353. }
  51354. }
  51355. }
  51356. var xOffset = this._orthoRight - this._orthoLeft;
  51357. var yOffset = this._orthoTop - this._orthoBottom;
  51358. 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);
  51359. };
  51360. DirectionalLight.prototype._buildUniformLayout = function () {
  51361. this._uniformBuffer.addUniform("vLightData", 4);
  51362. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51363. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51364. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51365. this._uniformBuffer.addUniform("depthValues", 2);
  51366. this._uniformBuffer.create();
  51367. };
  51368. /**
  51369. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  51370. * @param effect The effect to update
  51371. * @param lightIndex The index of the light in the effect to update
  51372. * @returns The directional light
  51373. */
  51374. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  51375. if (this.computeTransformedInformation()) {
  51376. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  51377. return this;
  51378. }
  51379. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  51380. return this;
  51381. };
  51382. /**
  51383. * Gets the minZ used for shadow according to both the scene and the light.
  51384. *
  51385. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51386. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51387. * @param activeCamera The camera we are returning the min for
  51388. * @returns the depth min z
  51389. */
  51390. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  51391. return 1;
  51392. };
  51393. /**
  51394. * Gets the maxZ used for shadow according to both the scene and the light.
  51395. *
  51396. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  51397. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  51398. * @param activeCamera The camera we are returning the max for
  51399. * @returns the depth max z
  51400. */
  51401. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  51402. return 1;
  51403. };
  51404. /**
  51405. * Prepares the list of defines specific to the light type.
  51406. * @param defines the list of defines
  51407. * @param lightIndex defines the index of the light for the effect
  51408. */
  51409. DirectionalLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51410. defines["DIRLIGHT" + lightIndex] = true;
  51411. };
  51412. __decorate([
  51413. BABYLON.serialize()
  51414. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  51415. __decorate([
  51416. BABYLON.serialize()
  51417. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  51418. __decorate([
  51419. BABYLON.serialize()
  51420. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  51421. return DirectionalLight;
  51422. }(BABYLON.ShadowLight));
  51423. BABYLON.DirectionalLight = DirectionalLight;
  51424. })(BABYLON || (BABYLON = {}));
  51425. //# sourceMappingURL=babylon.directionalLight.js.map
  51426. var BABYLON;
  51427. (function (BABYLON) {
  51428. BABYLON.Node.AddNodeConstructor("Light_Type_2", function (name, scene) {
  51429. return function () { return new SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  51430. });
  51431. /**
  51432. * A spot light is defined by a position, a direction, an angle, and an exponent.
  51433. * These values define a cone of light starting from the position, emitting toward the direction.
  51434. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  51435. * and the exponent defines the speed of the decay of the light with distance (reach).
  51436. * Documentation: https://doc.babylonjs.com/babylon101/lights
  51437. */
  51438. var SpotLight = /** @class */ (function (_super) {
  51439. __extends(SpotLight, _super);
  51440. /**
  51441. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  51442. * It can cast shadows.
  51443. * Documentation : http://doc.babylonjs.com/tutorials/lights
  51444. * @param name The light friendly name
  51445. * @param position The position of the spot light in the scene
  51446. * @param direction The direction of the light in the scene
  51447. * @param angle The cone angle of the light in Radians
  51448. * @param exponent The light decay speed with the distance from the emission spot
  51449. * @param scene The scene the lights belongs to
  51450. */
  51451. function SpotLight(name, position, direction, angle, exponent, scene) {
  51452. var _this = _super.call(this, name, scene) || this;
  51453. _this._innerAngle = 0;
  51454. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  51455. _this._projectionTextureLightNear = 1e-6;
  51456. _this._projectionTextureLightFar = 1000.0;
  51457. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  51458. _this._projectionTextureViewLightDirty = true;
  51459. _this._projectionTextureProjectionLightDirty = true;
  51460. _this._projectionTextureDirty = true;
  51461. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  51462. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  51463. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  51464. _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);
  51465. _this.position = position;
  51466. _this.direction = direction;
  51467. _this.angle = angle;
  51468. _this.exponent = exponent;
  51469. return _this;
  51470. }
  51471. Object.defineProperty(SpotLight.prototype, "angle", {
  51472. /**
  51473. * Gets the cone angle of the spot light in Radians.
  51474. */
  51475. get: function () {
  51476. return this._angle;
  51477. },
  51478. /**
  51479. * Sets the cone angle of the spot light in Radians.
  51480. */
  51481. set: function (value) {
  51482. this._angle = value;
  51483. this._cosHalfAngle = Math.cos(value * 0.5);
  51484. this._projectionTextureProjectionLightDirty = true;
  51485. this.forceProjectionMatrixCompute();
  51486. this._computeAngleValues();
  51487. },
  51488. enumerable: true,
  51489. configurable: true
  51490. });
  51491. Object.defineProperty(SpotLight.prototype, "innerAngle", {
  51492. /**
  51493. * Only used in gltf falloff mode, this defines the angle where
  51494. * the directional falloff will start before cutting at angle which could be seen
  51495. * as outer angle.
  51496. */
  51497. get: function () {
  51498. return this._innerAngle;
  51499. },
  51500. /**
  51501. * Only used in gltf falloff mode, this defines the angle where
  51502. * the directional falloff will start before cutting at angle which could be seen
  51503. * as outer angle.
  51504. */
  51505. set: function (value) {
  51506. this._innerAngle = value;
  51507. this._computeAngleValues();
  51508. },
  51509. enumerable: true,
  51510. configurable: true
  51511. });
  51512. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  51513. /**
  51514. * Allows scaling the angle of the light for shadow generation only.
  51515. */
  51516. get: function () {
  51517. return this._shadowAngleScale;
  51518. },
  51519. /**
  51520. * Allows scaling the angle of the light for shadow generation only.
  51521. */
  51522. set: function (value) {
  51523. this._shadowAngleScale = value;
  51524. this.forceProjectionMatrixCompute();
  51525. },
  51526. enumerable: true,
  51527. configurable: true
  51528. });
  51529. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  51530. /**
  51531. * Allows reading the projecton texture
  51532. */
  51533. get: function () {
  51534. return this._projectionTextureMatrix;
  51535. },
  51536. enumerable: true,
  51537. configurable: true
  51538. });
  51539. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  51540. /**
  51541. * Gets the near clip of the Spotlight for texture projection.
  51542. */
  51543. get: function () {
  51544. return this._projectionTextureLightNear;
  51545. },
  51546. /**
  51547. * Sets the near clip of the Spotlight for texture projection.
  51548. */
  51549. set: function (value) {
  51550. this._projectionTextureLightNear = value;
  51551. this._projectionTextureProjectionLightDirty = true;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  51557. /**
  51558. * Gets the far clip of the Spotlight for texture projection.
  51559. */
  51560. get: function () {
  51561. return this._projectionTextureLightFar;
  51562. },
  51563. /**
  51564. * Sets the far clip of the Spotlight for texture projection.
  51565. */
  51566. set: function (value) {
  51567. this._projectionTextureLightFar = value;
  51568. this._projectionTextureProjectionLightDirty = true;
  51569. },
  51570. enumerable: true,
  51571. configurable: true
  51572. });
  51573. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  51574. /**
  51575. * Gets the Up vector of the Spotlight for texture projection.
  51576. */
  51577. get: function () {
  51578. return this._projectionTextureUpDirection;
  51579. },
  51580. /**
  51581. * Sets the Up vector of the Spotlight for texture projection.
  51582. */
  51583. set: function (value) {
  51584. this._projectionTextureUpDirection = value;
  51585. this._projectionTextureProjectionLightDirty = true;
  51586. },
  51587. enumerable: true,
  51588. configurable: true
  51589. });
  51590. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  51591. /**
  51592. * Gets the projection texture of the light.
  51593. */
  51594. get: function () {
  51595. return this._projectionTexture;
  51596. },
  51597. /**
  51598. * Sets the projection texture of the light.
  51599. */
  51600. set: function (value) {
  51601. this._projectionTexture = value;
  51602. this._projectionTextureDirty = true;
  51603. },
  51604. enumerable: true,
  51605. configurable: true
  51606. });
  51607. /**
  51608. * Returns the string "SpotLight".
  51609. * @returns the class name
  51610. */
  51611. SpotLight.prototype.getClassName = function () {
  51612. return "SpotLight";
  51613. };
  51614. /**
  51615. * Returns the integer 2.
  51616. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  51617. */
  51618. SpotLight.prototype.getTypeID = function () {
  51619. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  51620. };
  51621. /**
  51622. * Overrides the direction setter to recompute the projection texture view light Matrix.
  51623. */
  51624. SpotLight.prototype._setDirection = function (value) {
  51625. _super.prototype._setDirection.call(this, value);
  51626. this._projectionTextureViewLightDirty = true;
  51627. };
  51628. /**
  51629. * Overrides the position setter to recompute the projection texture view light Matrix.
  51630. */
  51631. SpotLight.prototype._setPosition = function (value) {
  51632. _super.prototype._setPosition.call(this, value);
  51633. this._projectionTextureViewLightDirty = true;
  51634. };
  51635. /**
  51636. * 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.
  51637. * Returns the SpotLight.
  51638. */
  51639. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  51640. var activeCamera = this.getScene().activeCamera;
  51641. if (!activeCamera) {
  51642. return;
  51643. }
  51644. this._shadowAngleScale = this._shadowAngleScale || 1;
  51645. var angle = this._shadowAngleScale * this._angle;
  51646. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  51647. };
  51648. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  51649. this._projectionTextureViewLightDirty = false;
  51650. this._projectionTextureDirty = true;
  51651. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  51652. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  51653. };
  51654. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  51655. this._projectionTextureProjectionLightDirty = false;
  51656. this._projectionTextureDirty = true;
  51657. var light_far = this.projectionTextureLightFar;
  51658. var light_near = this.projectionTextureLightNear;
  51659. var P = light_far / (light_far - light_near);
  51660. var Q = -P * light_near;
  51661. var S = 1.0 / Math.tan(this._angle / 2.0);
  51662. var A = 1.0;
  51663. 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);
  51664. };
  51665. /**
  51666. * Main function for light texture projection matrix computing.
  51667. */
  51668. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  51669. this._projectionTextureDirty = false;
  51670. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  51671. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  51672. };
  51673. SpotLight.prototype._buildUniformLayout = function () {
  51674. this._uniformBuffer.addUniform("vLightData", 4);
  51675. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  51676. this._uniformBuffer.addUniform("vLightSpecular", 3);
  51677. this._uniformBuffer.addUniform("vLightDirection", 3);
  51678. this._uniformBuffer.addUniform("vLightFalloff", 4);
  51679. this._uniformBuffer.addUniform("shadowsInfo", 3);
  51680. this._uniformBuffer.addUniform("depthValues", 2);
  51681. this._uniformBuffer.create();
  51682. };
  51683. SpotLight.prototype._computeAngleValues = function () {
  51684. this._lightAngleScale = 1.0 / Math.max(0.001, (Math.cos(this._innerAngle * 0.5) - this._cosHalfAngle));
  51685. this._lightAngleOffset = -this._cosHalfAngle * this._lightAngleScale;
  51686. };
  51687. /**
  51688. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  51689. * @param effect The effect to update
  51690. * @param lightIndex The index of the light in the effect to update
  51691. * @returns The spot light
  51692. */
  51693. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  51694. var normalizeDirection;
  51695. if (this.computeTransformedInformation()) {
  51696. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  51697. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  51698. }
  51699. else {
  51700. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  51701. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  51702. }
  51703. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, this._cosHalfAngle, lightIndex);
  51704. this._uniformBuffer.updateFloat4("vLightFalloff", this.range, this._inverseSquaredRange, this._lightAngleScale, this._lightAngleOffset, lightIndex);
  51705. if (this.projectionTexture && this.projectionTexture.isReady()) {
  51706. if (this._projectionTextureViewLightDirty) {
  51707. this._computeProjectionTextureViewLightMatrix();
  51708. }
  51709. if (this._projectionTextureProjectionLightDirty) {
  51710. this._computeProjectionTextureProjectionLightMatrix();
  51711. }
  51712. if (this._projectionTextureDirty) {
  51713. this._computeProjectionTextureMatrix();
  51714. }
  51715. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  51716. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  51717. }
  51718. return this;
  51719. };
  51720. /**
  51721. * Disposes the light and the associated resources.
  51722. */
  51723. SpotLight.prototype.dispose = function () {
  51724. _super.prototype.dispose.call(this);
  51725. if (this._projectionTexture) {
  51726. this._projectionTexture.dispose();
  51727. }
  51728. };
  51729. /**
  51730. * Prepares the list of defines specific to the light type.
  51731. * @param defines the list of defines
  51732. * @param lightIndex defines the index of the light for the effect
  51733. */
  51734. SpotLight.prototype.prepareLightSpecificDefines = function (defines, lightIndex) {
  51735. defines["SPOTLIGHT" + lightIndex] = true;
  51736. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = this.projectionTexture ? true : false;
  51737. };
  51738. __decorate([
  51739. BABYLON.serialize()
  51740. ], SpotLight.prototype, "angle", null);
  51741. __decorate([
  51742. BABYLON.serialize()
  51743. ], SpotLight.prototype, "innerAngle", null);
  51744. __decorate([
  51745. BABYLON.serialize()
  51746. ], SpotLight.prototype, "shadowAngleScale", null);
  51747. __decorate([
  51748. BABYLON.serialize()
  51749. ], SpotLight.prototype, "exponent", void 0);
  51750. __decorate([
  51751. BABYLON.serialize()
  51752. ], SpotLight.prototype, "projectionTextureLightNear", null);
  51753. __decorate([
  51754. BABYLON.serialize()
  51755. ], SpotLight.prototype, "projectionTextureLightFar", null);
  51756. __decorate([
  51757. BABYLON.serialize()
  51758. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  51759. __decorate([
  51760. BABYLON.serializeAsTexture("projectedLightTexture")
  51761. ], SpotLight.prototype, "_projectionTexture", void 0);
  51762. return SpotLight;
  51763. }(BABYLON.ShadowLight));
  51764. BABYLON.SpotLight = SpotLight;
  51765. })(BABYLON || (BABYLON = {}));
  51766. //# sourceMappingURL=babylon.spotLight.js.map
  51767. var BABYLON;
  51768. (function (BABYLON) {
  51769. /**
  51770. * Class used to override all child animations of a given target
  51771. */
  51772. var AnimationPropertiesOverride = /** @class */ (function () {
  51773. function AnimationPropertiesOverride() {
  51774. /**
  51775. * Gets or sets a value indicating if animation blending must be used
  51776. */
  51777. this.enableBlending = false;
  51778. /**
  51779. * Gets or sets the blending speed to use when enableBlending is true
  51780. */
  51781. this.blendingSpeed = 0.01;
  51782. /**
  51783. * Gets or sets the default loop mode to use
  51784. */
  51785. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  51786. }
  51787. return AnimationPropertiesOverride;
  51788. }());
  51789. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  51790. })(BABYLON || (BABYLON = {}));
  51791. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  51792. var BABYLON;
  51793. (function (BABYLON) {
  51794. /**
  51795. * Represents the range of an animation
  51796. */
  51797. var AnimationRange = /** @class */ (function () {
  51798. /**
  51799. * Initializes the range of an animation
  51800. * @param name The name of the animation range
  51801. * @param from The starting frame of the animation
  51802. * @param to The ending frame of the animation
  51803. */
  51804. function AnimationRange(
  51805. /**The name of the animation range**/
  51806. name,
  51807. /**The starting frame of the animation */
  51808. from,
  51809. /**The ending frame of the animation*/
  51810. to) {
  51811. this.name = name;
  51812. this.from = from;
  51813. this.to = to;
  51814. }
  51815. /**
  51816. * Makes a copy of the animation range
  51817. * @returns A copy of the animation range
  51818. */
  51819. AnimationRange.prototype.clone = function () {
  51820. return new AnimationRange(this.name, this.from, this.to);
  51821. };
  51822. return AnimationRange;
  51823. }());
  51824. BABYLON.AnimationRange = AnimationRange;
  51825. /**
  51826. * Composed of a frame, and an action function
  51827. */
  51828. var AnimationEvent = /** @class */ (function () {
  51829. /**
  51830. * Initializes the animation event
  51831. * @param frame The frame for which the event is triggered
  51832. * @param action The event to perform when triggered
  51833. * @param onlyOnce Specifies if the event should be triggered only once
  51834. */
  51835. function AnimationEvent(
  51836. /** The frame for which the event is triggered **/
  51837. frame,
  51838. /** The event to perform when triggered **/
  51839. action,
  51840. /** Specifies if the event should be triggered only once**/
  51841. onlyOnce) {
  51842. this.frame = frame;
  51843. this.action = action;
  51844. this.onlyOnce = onlyOnce;
  51845. /**
  51846. * Specifies if the animation event is done
  51847. */
  51848. this.isDone = false;
  51849. }
  51850. /** @hidden */
  51851. AnimationEvent.prototype._clone = function () {
  51852. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  51853. };
  51854. return AnimationEvent;
  51855. }());
  51856. BABYLON.AnimationEvent = AnimationEvent;
  51857. /**
  51858. * A cursor which tracks a point on a path
  51859. */
  51860. var PathCursor = /** @class */ (function () {
  51861. /**
  51862. * Initializes the path cursor
  51863. * @param path The path to track
  51864. */
  51865. function PathCursor(path) {
  51866. this.path = path;
  51867. /**
  51868. * Stores path cursor callbacks for when an onchange event is triggered
  51869. */
  51870. this._onchange = new Array();
  51871. /**
  51872. * The value of the path cursor
  51873. */
  51874. this.value = 0;
  51875. /**
  51876. * The animation array of the path cursor
  51877. */
  51878. this.animations = new Array();
  51879. }
  51880. /**
  51881. * Gets the cursor point on the path
  51882. * @returns A point on the path cursor at the cursor location
  51883. */
  51884. PathCursor.prototype.getPoint = function () {
  51885. var point = this.path.getPointAtLengthPosition(this.value);
  51886. return new BABYLON.Vector3(point.x, 0, point.y);
  51887. };
  51888. /**
  51889. * Moves the cursor ahead by the step amount
  51890. * @param step The amount to move the cursor forward
  51891. * @returns This path cursor
  51892. */
  51893. PathCursor.prototype.moveAhead = function (step) {
  51894. if (step === void 0) { step = 0.002; }
  51895. this.move(step);
  51896. return this;
  51897. };
  51898. /**
  51899. * Moves the cursor behind by the step amount
  51900. * @param step The amount to move the cursor back
  51901. * @returns This path cursor
  51902. */
  51903. PathCursor.prototype.moveBack = function (step) {
  51904. if (step === void 0) { step = 0.002; }
  51905. this.move(-step);
  51906. return this;
  51907. };
  51908. /**
  51909. * Moves the cursor by the step amount
  51910. * If the step amount is greater than one, an exception is thrown
  51911. * @param step The amount to move the cursor
  51912. * @returns This path cursor
  51913. */
  51914. PathCursor.prototype.move = function (step) {
  51915. if (Math.abs(step) > 1) {
  51916. throw "step size should be less than 1.";
  51917. }
  51918. this.value += step;
  51919. this.ensureLimits();
  51920. this.raiseOnChange();
  51921. return this;
  51922. };
  51923. /**
  51924. * Ensures that the value is limited between zero and one
  51925. * @returns This path cursor
  51926. */
  51927. PathCursor.prototype.ensureLimits = function () {
  51928. while (this.value > 1) {
  51929. this.value -= 1;
  51930. }
  51931. while (this.value < 0) {
  51932. this.value += 1;
  51933. }
  51934. return this;
  51935. };
  51936. /**
  51937. * Runs onchange callbacks on change (used by the animation engine)
  51938. * @returns This path cursor
  51939. */
  51940. PathCursor.prototype.raiseOnChange = function () {
  51941. var _this = this;
  51942. this._onchange.forEach(function (f) { return f(_this); });
  51943. return this;
  51944. };
  51945. /**
  51946. * Executes a function on change
  51947. * @param f A path cursor onchange callback
  51948. * @returns This path cursor
  51949. */
  51950. PathCursor.prototype.onchange = function (f) {
  51951. this._onchange.push(f);
  51952. return this;
  51953. };
  51954. return PathCursor;
  51955. }());
  51956. BABYLON.PathCursor = PathCursor;
  51957. /**
  51958. * Enum for the animation key frame interpolation type
  51959. */
  51960. var AnimationKeyInterpolation;
  51961. (function (AnimationKeyInterpolation) {
  51962. /**
  51963. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  51964. */
  51965. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  51966. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  51967. /**
  51968. * Class used to store any kind of animation
  51969. */
  51970. var Animation = /** @class */ (function () {
  51971. /**
  51972. * Initializes the animation
  51973. * @param name Name of the animation
  51974. * @param targetProperty Property to animate
  51975. * @param framePerSecond The frames per second of the animation
  51976. * @param dataType The data type of the animation
  51977. * @param loopMode The loop mode of the animation
  51978. * @param enableBlendings Specifies if blending should be enabled
  51979. */
  51980. function Animation(
  51981. /**Name of the animation */
  51982. name,
  51983. /**Property to animate */
  51984. targetProperty,
  51985. /**The frames per second of the animation */
  51986. framePerSecond,
  51987. /**The data type of the animation */
  51988. dataType,
  51989. /**The loop mode of the animation */
  51990. loopMode,
  51991. /**Specifies if blending should be enabled */
  51992. enableBlending) {
  51993. this.name = name;
  51994. this.targetProperty = targetProperty;
  51995. this.framePerSecond = framePerSecond;
  51996. this.dataType = dataType;
  51997. this.loopMode = loopMode;
  51998. this.enableBlending = enableBlending;
  51999. /**
  52000. * @hidden Internal use only
  52001. */
  52002. this._runtimeAnimations = new Array();
  52003. /**
  52004. * The set of event that will be linked to this animation
  52005. */
  52006. this._events = new Array();
  52007. /**
  52008. * Stores the blending speed of the animation
  52009. */
  52010. this.blendingSpeed = 0.01;
  52011. /**
  52012. * Stores the animation ranges for the animation
  52013. */
  52014. this._ranges = {};
  52015. this.targetPropertyPath = targetProperty.split(".");
  52016. this.dataType = dataType;
  52017. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  52018. }
  52019. /**
  52020. * @hidden Internal use
  52021. */
  52022. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  52023. var dataType = undefined;
  52024. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  52025. dataType = Animation.ANIMATIONTYPE_FLOAT;
  52026. }
  52027. else if (from instanceof BABYLON.Quaternion) {
  52028. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  52029. }
  52030. else if (from instanceof BABYLON.Vector3) {
  52031. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  52032. }
  52033. else if (from instanceof BABYLON.Vector2) {
  52034. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  52035. }
  52036. else if (from instanceof BABYLON.Color3) {
  52037. dataType = Animation.ANIMATIONTYPE_COLOR3;
  52038. }
  52039. else if (from instanceof BABYLON.Size) {
  52040. dataType = Animation.ANIMATIONTYPE_SIZE;
  52041. }
  52042. if (dataType == undefined) {
  52043. return null;
  52044. }
  52045. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  52046. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  52047. animation.setKeys(keys);
  52048. if (easingFunction !== undefined) {
  52049. animation.setEasingFunction(easingFunction);
  52050. }
  52051. return animation;
  52052. };
  52053. /**
  52054. * Sets up an animation
  52055. * @param property The property to animate
  52056. * @param animationType The animation type to apply
  52057. * @param framePerSecond The frames per second of the animation
  52058. * @param easingFunction The easing function used in the animation
  52059. * @returns The created animation
  52060. */
  52061. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  52062. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  52063. animation.setEasingFunction(easingFunction);
  52064. return animation;
  52065. };
  52066. /**
  52067. * Create and start an animation on a node
  52068. * @param name defines the name of the global animation that will be run on all nodes
  52069. * @param node defines the root node where the animation will take place
  52070. * @param targetProperty defines property to animate
  52071. * @param framePerSecond defines the number of frame per second yo use
  52072. * @param totalFrame defines the number of frames in total
  52073. * @param from defines the initial value
  52074. * @param to defines the final value
  52075. * @param loopMode defines which loop mode you want to use (off by default)
  52076. * @param easingFunction defines the easing function to use (linear by default)
  52077. * @param onAnimationEnd defines the callback to call when animation end
  52078. * @returns the animatable created for this animation
  52079. */
  52080. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52081. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52082. if (!animation) {
  52083. return null;
  52084. }
  52085. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52086. };
  52087. /**
  52088. * Create and start an animation on a node and its descendants
  52089. * @param name defines the name of the global animation that will be run on all nodes
  52090. * @param node defines the root node where the animation will take place
  52091. * @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
  52092. * @param targetProperty defines property to animate
  52093. * @param framePerSecond defines the number of frame per second to use
  52094. * @param totalFrame defines the number of frames in total
  52095. * @param from defines the initial value
  52096. * @param to defines the final value
  52097. * @param loopMode defines which loop mode you want to use (off by default)
  52098. * @param easingFunction defines the easing function to use (linear by default)
  52099. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  52100. * @returns the list of animatables created for all nodes
  52101. * @example https://www.babylonjs-playground.com/#MH0VLI
  52102. */
  52103. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52104. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52105. if (!animation) {
  52106. return null;
  52107. }
  52108. var scene = node.getScene();
  52109. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52110. };
  52111. /**
  52112. * Creates a new animation, merges it with the existing animations and starts it
  52113. * @param name Name of the animation
  52114. * @param node Node which contains the scene that begins the animations
  52115. * @param targetProperty Specifies which property to animate
  52116. * @param framePerSecond The frames per second of the animation
  52117. * @param totalFrame The total number of frames
  52118. * @param from The frame at the beginning of the animation
  52119. * @param to The frame at the end of the animation
  52120. * @param loopMode Specifies the loop mode of the animation
  52121. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  52122. * @param onAnimationEnd Callback to run once the animation is complete
  52123. * @returns Nullable animation
  52124. */
  52125. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  52126. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  52127. if (!animation) {
  52128. return null;
  52129. }
  52130. node.animations.push(animation);
  52131. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  52132. };
  52133. /**
  52134. * Transition property of an host to the target Value
  52135. * @param property The property to transition
  52136. * @param targetValue The target Value of the property
  52137. * @param host The object where the property to animate belongs
  52138. * @param scene Scene used to run the animation
  52139. * @param frameRate Framerate (in frame/s) to use
  52140. * @param transition The transition type we want to use
  52141. * @param duration The duration of the animation, in milliseconds
  52142. * @param onAnimationEnd Callback trigger at the end of the animation
  52143. * @returns Nullable animation
  52144. */
  52145. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  52146. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  52147. if (duration <= 0) {
  52148. host[property] = targetValue;
  52149. if (onAnimationEnd) {
  52150. onAnimationEnd();
  52151. }
  52152. return null;
  52153. }
  52154. var endFrame = frameRate * (duration / 1000);
  52155. transition.setKeys([{
  52156. frame: 0,
  52157. value: host[property].clone ? host[property].clone() : host[property]
  52158. },
  52159. {
  52160. frame: endFrame,
  52161. value: targetValue
  52162. }]);
  52163. if (!host.animations) {
  52164. host.animations = [];
  52165. }
  52166. host.animations.push(transition);
  52167. var animation = scene.beginAnimation(host, 0, endFrame, false);
  52168. animation.onAnimationEnd = onAnimationEnd;
  52169. return animation;
  52170. };
  52171. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  52172. /**
  52173. * Return the array of runtime animations currently using this animation
  52174. */
  52175. get: function () {
  52176. return this._runtimeAnimations;
  52177. },
  52178. enumerable: true,
  52179. configurable: true
  52180. });
  52181. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  52182. /**
  52183. * Specifies if any of the runtime animations are currently running
  52184. */
  52185. get: function () {
  52186. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  52187. var runtimeAnimation = _a[_i];
  52188. if (!runtimeAnimation.isStopped) {
  52189. return true;
  52190. }
  52191. }
  52192. return false;
  52193. },
  52194. enumerable: true,
  52195. configurable: true
  52196. });
  52197. // Methods
  52198. /**
  52199. * Converts the animation to a string
  52200. * @param fullDetails support for multiple levels of logging within scene loading
  52201. * @returns String form of the animation
  52202. */
  52203. Animation.prototype.toString = function (fullDetails) {
  52204. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  52205. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  52206. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  52207. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  52208. if (fullDetails) {
  52209. ret += ", Ranges: {";
  52210. var first = true;
  52211. for (var name in this._ranges) {
  52212. if (first) {
  52213. ret += ", ";
  52214. first = false;
  52215. }
  52216. ret += name;
  52217. }
  52218. ret += "}";
  52219. }
  52220. return ret;
  52221. };
  52222. /**
  52223. * Add an event to this animation
  52224. * @param event Event to add
  52225. */
  52226. Animation.prototype.addEvent = function (event) {
  52227. this._events.push(event);
  52228. };
  52229. /**
  52230. * Remove all events found at the given frame
  52231. * @param frame The frame to remove events from
  52232. */
  52233. Animation.prototype.removeEvents = function (frame) {
  52234. for (var index = 0; index < this._events.length; index++) {
  52235. if (this._events[index].frame === frame) {
  52236. this._events.splice(index, 1);
  52237. index--;
  52238. }
  52239. }
  52240. };
  52241. /**
  52242. * Retrieves all the events from the animation
  52243. * @returns Events from the animation
  52244. */
  52245. Animation.prototype.getEvents = function () {
  52246. return this._events;
  52247. };
  52248. /**
  52249. * Creates an animation range
  52250. * @param name Name of the animation range
  52251. * @param from Starting frame of the animation range
  52252. * @param to Ending frame of the animation
  52253. */
  52254. Animation.prototype.createRange = function (name, from, to) {
  52255. // check name not already in use; could happen for bones after serialized
  52256. if (!this._ranges[name]) {
  52257. this._ranges[name] = new AnimationRange(name, from, to);
  52258. }
  52259. };
  52260. /**
  52261. * Deletes an animation range by name
  52262. * @param name Name of the animation range to delete
  52263. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  52264. */
  52265. Animation.prototype.deleteRange = function (name, deleteFrames) {
  52266. if (deleteFrames === void 0) { deleteFrames = true; }
  52267. var range = this._ranges[name];
  52268. if (!range) {
  52269. return;
  52270. }
  52271. if (deleteFrames) {
  52272. var from = range.from;
  52273. var to = range.to;
  52274. // this loop MUST go high to low for multiple splices to work
  52275. for (var key = this._keys.length - 1; key >= 0; key--) {
  52276. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  52277. this._keys.splice(key, 1);
  52278. }
  52279. }
  52280. }
  52281. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  52282. };
  52283. /**
  52284. * Gets the animation range by name, or null if not defined
  52285. * @param name Name of the animation range
  52286. * @returns Nullable animation range
  52287. */
  52288. Animation.prototype.getRange = function (name) {
  52289. return this._ranges[name];
  52290. };
  52291. /**
  52292. * Gets the key frames from the animation
  52293. * @returns The key frames of the animation
  52294. */
  52295. Animation.prototype.getKeys = function () {
  52296. return this._keys;
  52297. };
  52298. /**
  52299. * Gets the highest frame rate of the animation
  52300. * @returns Highest frame rate of the animation
  52301. */
  52302. Animation.prototype.getHighestFrame = function () {
  52303. var ret = 0;
  52304. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  52305. if (ret < this._keys[key].frame) {
  52306. ret = this._keys[key].frame;
  52307. }
  52308. }
  52309. return ret;
  52310. };
  52311. /**
  52312. * Gets the easing function of the animation
  52313. * @returns Easing function of the animation
  52314. */
  52315. Animation.prototype.getEasingFunction = function () {
  52316. return this._easingFunction;
  52317. };
  52318. /**
  52319. * Sets the easing function of the animation
  52320. * @param easingFunction A custom mathematical formula for animation
  52321. */
  52322. Animation.prototype.setEasingFunction = function (easingFunction) {
  52323. this._easingFunction = easingFunction;
  52324. };
  52325. /**
  52326. * Interpolates a scalar linearly
  52327. * @param startValue Start value of the animation curve
  52328. * @param endValue End value of the animation curve
  52329. * @param gradient Scalar amount to interpolate
  52330. * @returns Interpolated scalar value
  52331. */
  52332. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  52333. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  52334. };
  52335. /**
  52336. * Interpolates a scalar cubically
  52337. * @param startValue Start value of the animation curve
  52338. * @param outTangent End tangent of the animation
  52339. * @param endValue End value of the animation curve
  52340. * @param inTangent Start tangent of the animation curve
  52341. * @param gradient Scalar amount to interpolate
  52342. * @returns Interpolated scalar value
  52343. */
  52344. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52345. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52346. };
  52347. /**
  52348. * Interpolates a quaternion using a spherical linear interpolation
  52349. * @param startValue Start value of the animation curve
  52350. * @param endValue End value of the animation curve
  52351. * @param gradient Scalar amount to interpolate
  52352. * @returns Interpolated quaternion value
  52353. */
  52354. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  52355. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  52356. };
  52357. /**
  52358. * Interpolates a quaternion cubically
  52359. * @param startValue Start value of the animation curve
  52360. * @param outTangent End tangent of the animation curve
  52361. * @param endValue End value of the animation curve
  52362. * @param inTangent Start tangent of the animation curve
  52363. * @param gradient Scalar amount to interpolate
  52364. * @returns Interpolated quaternion value
  52365. */
  52366. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52367. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  52368. };
  52369. /**
  52370. * Interpolates a Vector3 linearl
  52371. * @param startValue Start value of the animation curve
  52372. * @param endValue End value of the animation curve
  52373. * @param gradient Scalar amount to interpolate
  52374. * @returns Interpolated scalar value
  52375. */
  52376. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  52377. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  52378. };
  52379. /**
  52380. * Interpolates a Vector3 cubically
  52381. * @param startValue Start value of the animation curve
  52382. * @param outTangent End tangent of the animation
  52383. * @param endValue End value of the animation curve
  52384. * @param inTangent Start tangent of the animation curve
  52385. * @param gradient Scalar amount to interpolate
  52386. * @returns InterpolatedVector3 value
  52387. */
  52388. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52389. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52390. };
  52391. /**
  52392. * Interpolates a Vector2 linearly
  52393. * @param startValue Start value of the animation curve
  52394. * @param endValue End value of the animation curve
  52395. * @param gradient Scalar amount to interpolate
  52396. * @returns Interpolated Vector2 value
  52397. */
  52398. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  52399. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  52400. };
  52401. /**
  52402. * Interpolates a Vector2 cubically
  52403. * @param startValue Start value of the animation curve
  52404. * @param outTangent End tangent of the animation
  52405. * @param endValue End value of the animation curve
  52406. * @param inTangent Start tangent of the animation curve
  52407. * @param gradient Scalar amount to interpolate
  52408. * @returns Interpolated Vector2 value
  52409. */
  52410. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  52411. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  52412. };
  52413. /**
  52414. * Interpolates a size linearly
  52415. * @param startValue Start value of the animation curve
  52416. * @param endValue End value of the animation curve
  52417. * @param gradient Scalar amount to interpolate
  52418. * @returns Interpolated Size value
  52419. */
  52420. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  52421. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  52422. };
  52423. /**
  52424. * Interpolates a Color3 linearly
  52425. * @param startValue Start value of the animation curve
  52426. * @param endValue End value of the animation curve
  52427. * @param gradient Scalar amount to interpolate
  52428. * @returns Interpolated Color3 value
  52429. */
  52430. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  52431. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  52432. };
  52433. /**
  52434. * @hidden Internal use only
  52435. */
  52436. Animation.prototype._getKeyValue = function (value) {
  52437. if (typeof value === "function") {
  52438. return value();
  52439. }
  52440. return value;
  52441. };
  52442. /**
  52443. * @hidden Internal use only
  52444. */
  52445. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  52446. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  52447. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  52448. }
  52449. var keys = this.getKeys();
  52450. // Try to get a hash to find the right key
  52451. 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));
  52452. if (keys[startKeyIndex].frame >= currentFrame) {
  52453. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  52454. startKeyIndex--;
  52455. }
  52456. }
  52457. for (var key = startKeyIndex; key < keys.length; key++) {
  52458. var endKey = keys[key + 1];
  52459. if (endKey.frame >= currentFrame) {
  52460. var startKey = keys[key];
  52461. var startValue = this._getKeyValue(startKey.value);
  52462. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  52463. return startValue;
  52464. }
  52465. var endValue = this._getKeyValue(endKey.value);
  52466. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  52467. var frameDelta = endKey.frame - startKey.frame;
  52468. // gradient : percent of currentFrame between the frame inf and the frame sup
  52469. var gradient = (currentFrame - startKey.frame) / frameDelta;
  52470. // check for easingFunction and correction of gradient
  52471. var easingFunction = this.getEasingFunction();
  52472. if (easingFunction != null) {
  52473. gradient = easingFunction.ease(gradient);
  52474. }
  52475. switch (this.dataType) {
  52476. // Float
  52477. case Animation.ANIMATIONTYPE_FLOAT:
  52478. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  52479. switch (loopMode) {
  52480. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52481. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52482. return floatValue;
  52483. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52484. return offsetValue * repeatCount + floatValue;
  52485. }
  52486. break;
  52487. // Quaternion
  52488. case Animation.ANIMATIONTYPE_QUATERNION:
  52489. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  52490. switch (loopMode) {
  52491. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52492. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52493. return quatValue;
  52494. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52495. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  52496. }
  52497. return quatValue;
  52498. // Vector3
  52499. case Animation.ANIMATIONTYPE_VECTOR3:
  52500. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  52501. switch (loopMode) {
  52502. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52503. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52504. return vec3Value;
  52505. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52506. return vec3Value.add(offsetValue.scale(repeatCount));
  52507. }
  52508. // Vector2
  52509. case Animation.ANIMATIONTYPE_VECTOR2:
  52510. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  52511. switch (loopMode) {
  52512. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52513. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52514. return vec2Value;
  52515. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52516. return vec2Value.add(offsetValue.scale(repeatCount));
  52517. }
  52518. // Size
  52519. case Animation.ANIMATIONTYPE_SIZE:
  52520. switch (loopMode) {
  52521. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52522. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52523. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  52524. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52525. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52526. }
  52527. // Color3
  52528. case Animation.ANIMATIONTYPE_COLOR3:
  52529. switch (loopMode) {
  52530. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52531. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52532. return this.color3InterpolateFunction(startValue, endValue, gradient);
  52533. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52534. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  52535. }
  52536. // Matrix
  52537. case Animation.ANIMATIONTYPE_MATRIX:
  52538. switch (loopMode) {
  52539. case Animation.ANIMATIONLOOPMODE_CYCLE:
  52540. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  52541. if (Animation.AllowMatricesInterpolation) {
  52542. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  52543. }
  52544. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  52545. return startValue;
  52546. }
  52547. default:
  52548. break;
  52549. }
  52550. break;
  52551. }
  52552. }
  52553. return this._getKeyValue(keys[keys.length - 1].value);
  52554. };
  52555. /**
  52556. * Defines the function to use to interpolate matrices
  52557. * @param startValue defines the start matrix
  52558. * @param endValue defines the end matrix
  52559. * @param gradient defines the gradient between both matrices
  52560. * @param result defines an optional target matrix where to store the interpolation
  52561. * @returns the interpolated matrix
  52562. */
  52563. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  52564. if (Animation.AllowMatrixDecomposeForInterpolation) {
  52565. if (result) {
  52566. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  52567. return result;
  52568. }
  52569. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  52570. }
  52571. if (result) {
  52572. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  52573. return result;
  52574. }
  52575. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  52576. };
  52577. /**
  52578. * Makes a copy of the animation
  52579. * @returns Cloned animation
  52580. */
  52581. Animation.prototype.clone = function () {
  52582. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  52583. clone.enableBlending = this.enableBlending;
  52584. clone.blendingSpeed = this.blendingSpeed;
  52585. if (this._keys) {
  52586. clone.setKeys(this._keys);
  52587. }
  52588. if (this._ranges) {
  52589. clone._ranges = {};
  52590. for (var name in this._ranges) {
  52591. var range = this._ranges[name];
  52592. if (!range) {
  52593. continue;
  52594. }
  52595. clone._ranges[name] = range.clone();
  52596. }
  52597. }
  52598. return clone;
  52599. };
  52600. /**
  52601. * Sets the key frames of the animation
  52602. * @param values The animation key frames to set
  52603. */
  52604. Animation.prototype.setKeys = function (values) {
  52605. this._keys = values.slice(0);
  52606. };
  52607. /**
  52608. * Serializes the animation to an object
  52609. * @returns Serialized object
  52610. */
  52611. Animation.prototype.serialize = function () {
  52612. var serializationObject = {};
  52613. serializationObject.name = this.name;
  52614. serializationObject.property = this.targetProperty;
  52615. serializationObject.framePerSecond = this.framePerSecond;
  52616. serializationObject.dataType = this.dataType;
  52617. serializationObject.loopBehavior = this.loopMode;
  52618. serializationObject.enableBlending = this.enableBlending;
  52619. serializationObject.blendingSpeed = this.blendingSpeed;
  52620. var dataType = this.dataType;
  52621. serializationObject.keys = [];
  52622. var keys = this.getKeys();
  52623. for (var index = 0; index < keys.length; index++) {
  52624. var animationKey = keys[index];
  52625. var key = {};
  52626. key.frame = animationKey.frame;
  52627. switch (dataType) {
  52628. case Animation.ANIMATIONTYPE_FLOAT:
  52629. key.values = [animationKey.value];
  52630. break;
  52631. case Animation.ANIMATIONTYPE_QUATERNION:
  52632. case Animation.ANIMATIONTYPE_MATRIX:
  52633. case Animation.ANIMATIONTYPE_VECTOR3:
  52634. case Animation.ANIMATIONTYPE_COLOR3:
  52635. key.values = animationKey.value.asArray();
  52636. break;
  52637. }
  52638. serializationObject.keys.push(key);
  52639. }
  52640. serializationObject.ranges = [];
  52641. for (var name in this._ranges) {
  52642. var source = this._ranges[name];
  52643. if (!source) {
  52644. continue;
  52645. }
  52646. var range = {};
  52647. range.name = name;
  52648. range.from = source.from;
  52649. range.to = source.to;
  52650. serializationObject.ranges.push(range);
  52651. }
  52652. return serializationObject;
  52653. };
  52654. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  52655. /**
  52656. * Get the float animation type
  52657. */
  52658. get: function () {
  52659. return Animation._ANIMATIONTYPE_FLOAT;
  52660. },
  52661. enumerable: true,
  52662. configurable: true
  52663. });
  52664. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  52665. /**
  52666. * Get the Vector3 animation type
  52667. */
  52668. get: function () {
  52669. return Animation._ANIMATIONTYPE_VECTOR3;
  52670. },
  52671. enumerable: true,
  52672. configurable: true
  52673. });
  52674. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  52675. /**
  52676. * Get the Vector2 animation type
  52677. */
  52678. get: function () {
  52679. return Animation._ANIMATIONTYPE_VECTOR2;
  52680. },
  52681. enumerable: true,
  52682. configurable: true
  52683. });
  52684. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  52685. /**
  52686. * Get the Size animation type
  52687. */
  52688. get: function () {
  52689. return Animation._ANIMATIONTYPE_SIZE;
  52690. },
  52691. enumerable: true,
  52692. configurable: true
  52693. });
  52694. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  52695. /**
  52696. * Get the Quaternion animation type
  52697. */
  52698. get: function () {
  52699. return Animation._ANIMATIONTYPE_QUATERNION;
  52700. },
  52701. enumerable: true,
  52702. configurable: true
  52703. });
  52704. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  52705. /**
  52706. * Get the Matrix animation type
  52707. */
  52708. get: function () {
  52709. return Animation._ANIMATIONTYPE_MATRIX;
  52710. },
  52711. enumerable: true,
  52712. configurable: true
  52713. });
  52714. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  52715. /**
  52716. * Get the Color3 animation type
  52717. */
  52718. get: function () {
  52719. return Animation._ANIMATIONTYPE_COLOR3;
  52720. },
  52721. enumerable: true,
  52722. configurable: true
  52723. });
  52724. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  52725. /**
  52726. * Get the Relative Loop Mode
  52727. */
  52728. get: function () {
  52729. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  52730. },
  52731. enumerable: true,
  52732. configurable: true
  52733. });
  52734. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  52735. /**
  52736. * Get the Cycle Loop Mode
  52737. */
  52738. get: function () {
  52739. return Animation._ANIMATIONLOOPMODE_CYCLE;
  52740. },
  52741. enumerable: true,
  52742. configurable: true
  52743. });
  52744. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  52745. /**
  52746. * Get the Constant Loop Mode
  52747. */
  52748. get: function () {
  52749. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  52750. },
  52751. enumerable: true,
  52752. configurable: true
  52753. });
  52754. /** @hidden */
  52755. Animation._UniversalLerp = function (left, right, amount) {
  52756. var constructor = left.constructor;
  52757. if (constructor.Lerp) { // Lerp supported
  52758. return constructor.Lerp(left, right, amount);
  52759. }
  52760. else if (constructor.Slerp) { // Slerp supported
  52761. return constructor.Slerp(left, right, amount);
  52762. }
  52763. else if (left.toFixed) { // Number
  52764. return left * (1.0 - amount) + amount * right;
  52765. }
  52766. else { // Blending not supported
  52767. return right;
  52768. }
  52769. };
  52770. /**
  52771. * Parses an animation object and creates an animation
  52772. * @param parsedAnimation Parsed animation object
  52773. * @returns Animation object
  52774. */
  52775. Animation.Parse = function (parsedAnimation) {
  52776. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  52777. var dataType = parsedAnimation.dataType;
  52778. var keys = [];
  52779. var data;
  52780. var index;
  52781. if (parsedAnimation.enableBlending) {
  52782. animation.enableBlending = parsedAnimation.enableBlending;
  52783. }
  52784. if (parsedAnimation.blendingSpeed) {
  52785. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  52786. }
  52787. for (index = 0; index < parsedAnimation.keys.length; index++) {
  52788. var key = parsedAnimation.keys[index];
  52789. var inTangent;
  52790. var outTangent;
  52791. switch (dataType) {
  52792. case Animation.ANIMATIONTYPE_FLOAT:
  52793. data = key.values[0];
  52794. if (key.values.length >= 1) {
  52795. inTangent = key.values[1];
  52796. }
  52797. if (key.values.length >= 2) {
  52798. outTangent = key.values[2];
  52799. }
  52800. break;
  52801. case Animation.ANIMATIONTYPE_QUATERNION:
  52802. data = BABYLON.Quaternion.FromArray(key.values);
  52803. if (key.values.length >= 8) {
  52804. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  52805. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  52806. inTangent = _inTangent;
  52807. }
  52808. }
  52809. if (key.values.length >= 12) {
  52810. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  52811. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  52812. outTangent = _outTangent;
  52813. }
  52814. }
  52815. break;
  52816. case Animation.ANIMATIONTYPE_MATRIX:
  52817. data = BABYLON.Matrix.FromArray(key.values);
  52818. break;
  52819. case Animation.ANIMATIONTYPE_COLOR3:
  52820. data = BABYLON.Color3.FromArray(key.values);
  52821. break;
  52822. case Animation.ANIMATIONTYPE_VECTOR3:
  52823. default:
  52824. data = BABYLON.Vector3.FromArray(key.values);
  52825. break;
  52826. }
  52827. var keyData = {};
  52828. keyData.frame = key.frame;
  52829. keyData.value = data;
  52830. if (inTangent != undefined) {
  52831. keyData.inTangent = inTangent;
  52832. }
  52833. if (outTangent != undefined) {
  52834. keyData.outTangent = outTangent;
  52835. }
  52836. keys.push(keyData);
  52837. }
  52838. animation.setKeys(keys);
  52839. if (parsedAnimation.ranges) {
  52840. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  52841. data = parsedAnimation.ranges[index];
  52842. animation.createRange(data.name, data.from, data.to);
  52843. }
  52844. }
  52845. return animation;
  52846. };
  52847. /**
  52848. * Appends the serialized animations from the source animations
  52849. * @param source Source containing the animations
  52850. * @param destination Target to store the animations
  52851. */
  52852. Animation.AppendSerializedAnimations = function (source, destination) {
  52853. if (source.animations) {
  52854. destination.animations = [];
  52855. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  52856. var animation = source.animations[animationIndex];
  52857. destination.animations.push(animation.serialize());
  52858. }
  52859. }
  52860. };
  52861. /**
  52862. * Use matrix interpolation instead of using direct key value when animating matrices
  52863. */
  52864. Animation.AllowMatricesInterpolation = false;
  52865. /**
  52866. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  52867. */
  52868. Animation.AllowMatrixDecomposeForInterpolation = true;
  52869. // Statics
  52870. /**
  52871. * Float animation type
  52872. */
  52873. Animation._ANIMATIONTYPE_FLOAT = 0;
  52874. /**
  52875. * Vector3 animation type
  52876. */
  52877. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  52878. /**
  52879. * Quaternion animation type
  52880. */
  52881. Animation._ANIMATIONTYPE_QUATERNION = 2;
  52882. /**
  52883. * Matrix animation type
  52884. */
  52885. Animation._ANIMATIONTYPE_MATRIX = 3;
  52886. /**
  52887. * Color3 animation type
  52888. */
  52889. Animation._ANIMATIONTYPE_COLOR3 = 4;
  52890. /**
  52891. * Vector2 animation type
  52892. */
  52893. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  52894. /**
  52895. * Size animation type
  52896. */
  52897. Animation._ANIMATIONTYPE_SIZE = 6;
  52898. /**
  52899. * Relative Loop Mode
  52900. */
  52901. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  52902. /**
  52903. * Cycle Loop Mode
  52904. */
  52905. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  52906. /**
  52907. * Constant Loop Mode
  52908. */
  52909. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  52910. return Animation;
  52911. }());
  52912. BABYLON.Animation = Animation;
  52913. })(BABYLON || (BABYLON = {}));
  52914. //# sourceMappingURL=babylon.animation.js.map
  52915. var BABYLON;
  52916. (function (BABYLON) {
  52917. /**
  52918. * This class defines the direct association between an animation and a target
  52919. */
  52920. var TargetedAnimation = /** @class */ (function () {
  52921. function TargetedAnimation() {
  52922. }
  52923. return TargetedAnimation;
  52924. }());
  52925. BABYLON.TargetedAnimation = TargetedAnimation;
  52926. /**
  52927. * Use this class to create coordinated animations on multiple targets
  52928. */
  52929. var AnimationGroup = /** @class */ (function () {
  52930. /**
  52931. * Instantiates a new Animation Group.
  52932. * This helps managing several animations at once.
  52933. * @see http://doc.babylonjs.com/how_to/group
  52934. * @param name Defines the name of the group
  52935. * @param scene Defines the scene the group belongs to
  52936. */
  52937. function AnimationGroup(
  52938. /** The name of the animation group */
  52939. name, scene) {
  52940. if (scene === void 0) { scene = null; }
  52941. this.name = name;
  52942. this._targetedAnimations = new Array();
  52943. this._animatables = new Array();
  52944. this._from = Number.MAX_VALUE;
  52945. this._to = -Number.MAX_VALUE;
  52946. this._speedRatio = 1;
  52947. /**
  52948. * This observable will notify when one animation have ended.
  52949. */
  52950. this.onAnimationEndObservable = new BABYLON.Observable();
  52951. /**
  52952. * This observable will notify when all animations have ended.
  52953. */
  52954. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  52955. /**
  52956. * This observable will notify when all animations have paused.
  52957. */
  52958. this.onAnimationGroupPauseObservable = new BABYLON.Observable();
  52959. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52960. this._scene.animationGroups.push(this);
  52961. }
  52962. Object.defineProperty(AnimationGroup.prototype, "from", {
  52963. /**
  52964. * Gets the first frame
  52965. */
  52966. get: function () {
  52967. return this._from;
  52968. },
  52969. enumerable: true,
  52970. configurable: true
  52971. });
  52972. Object.defineProperty(AnimationGroup.prototype, "to", {
  52973. /**
  52974. * Gets the last frame
  52975. */
  52976. get: function () {
  52977. return this._to;
  52978. },
  52979. enumerable: true,
  52980. configurable: true
  52981. });
  52982. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  52983. /**
  52984. * Define if the animations are started
  52985. */
  52986. get: function () {
  52987. return this._isStarted;
  52988. },
  52989. enumerable: true,
  52990. configurable: true
  52991. });
  52992. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  52993. /**
  52994. * Gets or sets the speed ratio to use for all animations
  52995. */
  52996. get: function () {
  52997. return this._speedRatio;
  52998. },
  52999. /**
  53000. * Gets or sets the speed ratio to use for all animations
  53001. */
  53002. set: function (value) {
  53003. if (this._speedRatio === value) {
  53004. return;
  53005. }
  53006. this._speedRatio = value;
  53007. for (var index = 0; index < this._animatables.length; index++) {
  53008. var animatable = this._animatables[index];
  53009. animatable.speedRatio = this._speedRatio;
  53010. }
  53011. },
  53012. enumerable: true,
  53013. configurable: true
  53014. });
  53015. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  53016. /**
  53017. * Gets the targeted animations for this animation group
  53018. */
  53019. get: function () {
  53020. return this._targetedAnimations;
  53021. },
  53022. enumerable: true,
  53023. configurable: true
  53024. });
  53025. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  53026. /**
  53027. * returning the list of animatables controlled by this animation group.
  53028. */
  53029. get: function () {
  53030. return this._animatables;
  53031. },
  53032. enumerable: true,
  53033. configurable: true
  53034. });
  53035. /**
  53036. * Add an animation (with its target) in the group
  53037. * @param animation defines the animation we want to add
  53038. * @param target defines the target of the animation
  53039. * @returns the TargetedAnimation object
  53040. */
  53041. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  53042. var targetedAnimation = {
  53043. animation: animation,
  53044. target: target
  53045. };
  53046. var keys = animation.getKeys();
  53047. if (this._from > keys[0].frame) {
  53048. this._from = keys[0].frame;
  53049. }
  53050. if (this._to < keys[keys.length - 1].frame) {
  53051. this._to = keys[keys.length - 1].frame;
  53052. }
  53053. this._targetedAnimations.push(targetedAnimation);
  53054. return targetedAnimation;
  53055. };
  53056. /**
  53057. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  53058. * It can add constant keys at begin or end
  53059. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  53060. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  53061. * @returns the animation group
  53062. */
  53063. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  53064. if (beginFrame === void 0) { beginFrame = null; }
  53065. if (endFrame === void 0) { endFrame = null; }
  53066. if (beginFrame == null)
  53067. beginFrame = this._from;
  53068. if (endFrame == null)
  53069. endFrame = this._to;
  53070. for (var index = 0; index < this._targetedAnimations.length; index++) {
  53071. var targetedAnimation = this._targetedAnimations[index];
  53072. var keys = targetedAnimation.animation.getKeys();
  53073. var startKey = keys[0];
  53074. var endKey = keys[keys.length - 1];
  53075. if (startKey.frame > beginFrame) {
  53076. var newKey = {
  53077. frame: beginFrame,
  53078. value: startKey.value,
  53079. inTangent: startKey.inTangent,
  53080. outTangent: startKey.outTangent,
  53081. interpolation: startKey.interpolation
  53082. };
  53083. keys.splice(0, 0, newKey);
  53084. }
  53085. if (endKey.frame < endFrame) {
  53086. var newKey = {
  53087. frame: endFrame,
  53088. value: endKey.value,
  53089. inTangent: endKey.outTangent,
  53090. outTangent: endKey.outTangent,
  53091. interpolation: endKey.interpolation
  53092. };
  53093. keys.push(newKey);
  53094. }
  53095. }
  53096. this._from = beginFrame;
  53097. this._to = endFrame;
  53098. return this;
  53099. };
  53100. /**
  53101. * Start all animations on given targets
  53102. * @param loop defines if animations must loop
  53103. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  53104. * @param from defines the from key (optional)
  53105. * @param to defines the to key (optional)
  53106. * @returns the current animation group
  53107. */
  53108. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  53109. var _this = this;
  53110. if (loop === void 0) { loop = false; }
  53111. if (speedRatio === void 0) { speedRatio = 1; }
  53112. if (this._isStarted || this._targetedAnimations.length === 0) {
  53113. return this;
  53114. }
  53115. var _loop_1 = function (targetedAnimation) {
  53116. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  53117. animatable.onAnimationEnd = function () {
  53118. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  53119. _this._checkAnimationGroupEnded(animatable);
  53120. };
  53121. this_1._animatables.push(animatable);
  53122. };
  53123. var this_1 = this;
  53124. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  53125. var targetedAnimation = _a[_i];
  53126. _loop_1(targetedAnimation);
  53127. }
  53128. this._speedRatio = speedRatio;
  53129. this._isStarted = true;
  53130. return this;
  53131. };
  53132. /**
  53133. * Pause all animations
  53134. * @returns the animation group
  53135. */
  53136. AnimationGroup.prototype.pause = function () {
  53137. if (!this._isStarted) {
  53138. return this;
  53139. }
  53140. for (var index = 0; index < this._animatables.length; index++) {
  53141. var animatable = this._animatables[index];
  53142. animatable.pause();
  53143. }
  53144. this.onAnimationGroupPauseObservable.notifyObservers(this);
  53145. return this;
  53146. };
  53147. /**
  53148. * Play all animations to initial state
  53149. * This function will start() the animations if they were not started or will restart() them if they were paused
  53150. * @param loop defines if animations must loop
  53151. * @returns the animation group
  53152. */
  53153. AnimationGroup.prototype.play = function (loop) {
  53154. // only if all animatables are ready and exist
  53155. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  53156. if (loop !== undefined) {
  53157. for (var index = 0; index < this._animatables.length; index++) {
  53158. var animatable = this._animatables[index];
  53159. animatable.loopAnimation = loop;
  53160. }
  53161. }
  53162. this.restart();
  53163. }
  53164. else {
  53165. this.stop();
  53166. this.start(loop, this._speedRatio);
  53167. }
  53168. return this;
  53169. };
  53170. /**
  53171. * Reset all animations to initial state
  53172. * @returns the animation group
  53173. */
  53174. AnimationGroup.prototype.reset = function () {
  53175. if (!this._isStarted) {
  53176. return this;
  53177. }
  53178. for (var index = 0; index < this._animatables.length; index++) {
  53179. var animatable = this._animatables[index];
  53180. animatable.reset();
  53181. }
  53182. return this;
  53183. };
  53184. /**
  53185. * Restart animations from key 0
  53186. * @returns the animation group
  53187. */
  53188. AnimationGroup.prototype.restart = function () {
  53189. if (!this._isStarted) {
  53190. return this;
  53191. }
  53192. for (var index = 0; index < this._animatables.length; index++) {
  53193. var animatable = this._animatables[index];
  53194. animatable.restart();
  53195. }
  53196. return this;
  53197. };
  53198. /**
  53199. * Stop all animations
  53200. * @returns the animation group
  53201. */
  53202. AnimationGroup.prototype.stop = function () {
  53203. if (!this._isStarted) {
  53204. return this;
  53205. }
  53206. var list = this._animatables.slice();
  53207. for (var index = 0; index < list.length; index++) {
  53208. list[index].stop();
  53209. }
  53210. this._isStarted = false;
  53211. return this;
  53212. };
  53213. /**
  53214. * Set animation weight for all animatables
  53215. * @param weight defines the weight to use
  53216. * @return the animationGroup
  53217. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53218. */
  53219. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  53220. for (var index = 0; index < this._animatables.length; index++) {
  53221. var animatable = this._animatables[index];
  53222. animatable.weight = weight;
  53223. }
  53224. return this;
  53225. };
  53226. /**
  53227. * Synchronize and normalize all animatables with a source animatable
  53228. * @param root defines the root animatable to synchronize with
  53229. * @return the animationGroup
  53230. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  53231. */
  53232. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  53233. for (var index = 0; index < this._animatables.length; index++) {
  53234. var animatable = this._animatables[index];
  53235. animatable.syncWith(root);
  53236. }
  53237. return this;
  53238. };
  53239. /**
  53240. * Goes to a specific frame in this animation group
  53241. * @param frame the frame number to go to
  53242. * @return the animationGroup
  53243. */
  53244. AnimationGroup.prototype.goToFrame = function (frame) {
  53245. if (!this._isStarted) {
  53246. return this;
  53247. }
  53248. for (var index = 0; index < this._animatables.length; index++) {
  53249. var animatable = this._animatables[index];
  53250. animatable.goToFrame(frame);
  53251. }
  53252. return this;
  53253. };
  53254. /**
  53255. * Dispose all associated resources
  53256. */
  53257. AnimationGroup.prototype.dispose = function () {
  53258. this._targetedAnimations = [];
  53259. this._animatables = [];
  53260. var index = this._scene.animationGroups.indexOf(this);
  53261. if (index > -1) {
  53262. this._scene.animationGroups.splice(index, 1);
  53263. }
  53264. };
  53265. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  53266. // animatable should be taken out of the array
  53267. var idx = this._animatables.indexOf(animatable);
  53268. if (idx > -1) {
  53269. this._animatables.splice(idx, 1);
  53270. }
  53271. // all animatables were removed? animation group ended!
  53272. if (this._animatables.length === 0) {
  53273. this._isStarted = false;
  53274. this.onAnimationGroupEndObservable.notifyObservers(this);
  53275. }
  53276. };
  53277. // Statics
  53278. /**
  53279. * Returns a new AnimationGroup object parsed from the source provided.
  53280. * @param parsedAnimationGroup defines the source
  53281. * @param scene defines the scene that will receive the animationGroup
  53282. * @returns a new AnimationGroup
  53283. */
  53284. AnimationGroup.Parse = function (parsedAnimationGroup, scene) {
  53285. var animationGroup = new BABYLON.AnimationGroup(parsedAnimationGroup.name, scene);
  53286. for (var i = 0; i < parsedAnimationGroup.targetedAnimations.length; i++) {
  53287. var targetedAnimation = parsedAnimationGroup.targetedAnimations[i];
  53288. var animation = BABYLON.Animation.Parse(targetedAnimation.animation);
  53289. var id = targetedAnimation.targetId;
  53290. var targetNode = scene.getNodeByID(id);
  53291. if (targetNode != null)
  53292. animationGroup.addTargetedAnimation(animation, targetNode);
  53293. }
  53294. if (parsedAnimationGroup.from !== null && parsedAnimationGroup.from !== null)
  53295. animationGroup.normalize(parsedAnimationGroup.from, parsedAnimationGroup.to);
  53296. return animationGroup;
  53297. };
  53298. /**
  53299. * Returns the string "AnimationGroup"
  53300. * @returns "AnimationGroup"
  53301. */
  53302. AnimationGroup.prototype.getClassName = function () {
  53303. return "AnimationGroup";
  53304. };
  53305. /**
  53306. * Creates a detailled string about the object
  53307. * @param fullDetails defines if the output string will support multiple levels of logging within scene loading
  53308. * @returns a string representing the object
  53309. */
  53310. AnimationGroup.prototype.toString = function (fullDetails) {
  53311. var ret = "Name: " + this.name;
  53312. ret += ", type: " + this.getClassName();
  53313. if (fullDetails) {
  53314. ret += ", from: " + this._from;
  53315. ret += ", to: " + this._to;
  53316. ret += ", isStarted: " + this._isStarted;
  53317. ret += ", speedRatio: " + this._speedRatio;
  53318. ret += ", targetedAnimations length: " + this._targetedAnimations.length;
  53319. ret += ", animatables length: " + this._animatables;
  53320. }
  53321. return ret;
  53322. };
  53323. return AnimationGroup;
  53324. }());
  53325. BABYLON.AnimationGroup = AnimationGroup;
  53326. })(BABYLON || (BABYLON = {}));
  53327. //# sourceMappingURL=babylon.animationGroup.js.map
  53328. var BABYLON;
  53329. (function (BABYLON) {
  53330. // Static values to help the garbage collector
  53331. // Quaternion
  53332. var _staticOffsetValueQuaternion = Object.freeze(new BABYLON.Quaternion(0, 0, 0, 0));
  53333. // Vector3
  53334. var _staticOffsetValueVector3 = Object.freeze(BABYLON.Vector3.Zero());
  53335. // Vector2
  53336. var _staticOffsetValueVector2 = Object.freeze(BABYLON.Vector2.Zero());
  53337. // Size
  53338. var _staticOffsetValueSize = Object.freeze(BABYLON.Size.Zero());
  53339. // Color3
  53340. var _staticOffsetValueColor3 = Object.freeze(BABYLON.Color3.Black());
  53341. /**
  53342. * Defines a runtime animation
  53343. */
  53344. var RuntimeAnimation = /** @class */ (function () {
  53345. /**
  53346. * Create a new RuntimeAnimation object
  53347. * @param target defines the target of the animation
  53348. * @param animation defines the source animation object
  53349. * @param scene defines the hosting scene
  53350. * @param host defines the initiating Animatable
  53351. */
  53352. function RuntimeAnimation(target, animation, scene, host) {
  53353. var _this = this;
  53354. this._events = new Array();
  53355. /**
  53356. * The current frame of the runtime animation
  53357. */
  53358. this._currentFrame = 0;
  53359. /**
  53360. * The original value of the runtime animation
  53361. */
  53362. this._originalValue = new Array();
  53363. /**
  53364. * The offsets cache of the runtime animation
  53365. */
  53366. this._offsetsCache = {};
  53367. /**
  53368. * The high limits cache of the runtime animation
  53369. */
  53370. this._highLimitsCache = {};
  53371. /**
  53372. * Specifies if the runtime animation has been stopped
  53373. */
  53374. this._stopped = false;
  53375. /**
  53376. * The blending factor of the runtime animation
  53377. */
  53378. this._blendingFactor = 0;
  53379. /**
  53380. * The target path of the runtime animation
  53381. */
  53382. this._targetPath = "";
  53383. /**
  53384. * The weight of the runtime animation
  53385. */
  53386. this._weight = 1.0;
  53387. /**
  53388. * The ratio offset of the runtime animation
  53389. */
  53390. this._ratioOffset = 0;
  53391. /**
  53392. * The previous delay of the runtime animation
  53393. */
  53394. this._previousDelay = 0;
  53395. /**
  53396. * The previous ratio of the runtime animation
  53397. */
  53398. this._previousRatio = 0;
  53399. this._animation = animation;
  53400. this._target = target;
  53401. this._scene = scene;
  53402. this._host = host;
  53403. animation._runtimeAnimations.push(this);
  53404. // Cloning events locally
  53405. var events = animation.getEvents();
  53406. if (events && events.length > 0) {
  53407. events.forEach(function (e) {
  53408. _this._events.push(e._clone());
  53409. });
  53410. }
  53411. }
  53412. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  53413. /**
  53414. * Gets the current frame of the runtime animation
  53415. */
  53416. get: function () {
  53417. return this._currentFrame;
  53418. },
  53419. enumerable: true,
  53420. configurable: true
  53421. });
  53422. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  53423. /**
  53424. * Gets the weight of the runtime animation
  53425. */
  53426. get: function () {
  53427. return this._weight;
  53428. },
  53429. enumerable: true,
  53430. configurable: true
  53431. });
  53432. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  53433. /**
  53434. * Gets the current value of the runtime animation
  53435. */
  53436. get: function () {
  53437. return this._currentValue;
  53438. },
  53439. enumerable: true,
  53440. configurable: true
  53441. });
  53442. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  53443. /**
  53444. * Gets the target path of the runtime animation
  53445. */
  53446. get: function () {
  53447. return this._targetPath;
  53448. },
  53449. enumerable: true,
  53450. configurable: true
  53451. });
  53452. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  53453. /**
  53454. * Gets the actual target of the runtime animation
  53455. */
  53456. get: function () {
  53457. return this._activeTarget;
  53458. },
  53459. enumerable: true,
  53460. configurable: true
  53461. });
  53462. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  53463. /**
  53464. * Gets the animation from the runtime animation
  53465. */
  53466. get: function () {
  53467. return this._animation;
  53468. },
  53469. enumerable: true,
  53470. configurable: true
  53471. });
  53472. /**
  53473. * Resets the runtime animation to the beginning
  53474. * @param restoreOriginal defines whether to restore the target property to the original value
  53475. */
  53476. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  53477. if (restoreOriginal === void 0) { restoreOriginal = false; }
  53478. if (restoreOriginal) {
  53479. if (this._target instanceof Array) {
  53480. var index = 0;
  53481. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53482. var target = _a[_i];
  53483. if (this._originalValue[index] !== undefined) {
  53484. this._setValue(target, this._originalValue[index], -1);
  53485. }
  53486. index++;
  53487. }
  53488. }
  53489. else {
  53490. if (this._originalValue[0] !== undefined) {
  53491. this._setValue(this._target, this._originalValue[0], -1);
  53492. }
  53493. }
  53494. }
  53495. this._offsetsCache = {};
  53496. this._highLimitsCache = {};
  53497. this._currentFrame = 0;
  53498. this._blendingFactor = 0;
  53499. this._originalValue = new Array();
  53500. // Events
  53501. for (var index = 0; index < this._events.length; index++) {
  53502. this._events[index].isDone = false;
  53503. }
  53504. };
  53505. /**
  53506. * Specifies if the runtime animation is stopped
  53507. * @returns Boolean specifying if the runtime animation is stopped
  53508. */
  53509. RuntimeAnimation.prototype.isStopped = function () {
  53510. return this._stopped;
  53511. };
  53512. /**
  53513. * Disposes of the runtime animation
  53514. */
  53515. RuntimeAnimation.prototype.dispose = function () {
  53516. var index = this._animation.runtimeAnimations.indexOf(this);
  53517. if (index > -1) {
  53518. this._animation.runtimeAnimations.splice(index, 1);
  53519. }
  53520. };
  53521. /**
  53522. * Interpolates the animation from the current frame
  53523. * @param currentFrame The frame to interpolate the animation to
  53524. * @param repeatCount The number of times that the animation should loop
  53525. * @param loopMode The type of looping mode to use
  53526. * @param offsetValue Animation offset value
  53527. * @param highLimitValue The high limit value
  53528. * @returns The interpolated value
  53529. */
  53530. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  53531. this._currentFrame = currentFrame;
  53532. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  53533. this._workValue = BABYLON.Matrix.Zero();
  53534. }
  53535. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  53536. };
  53537. /**
  53538. * Apply the interpolated value to the target
  53539. * @param currentValue defines the value computed by the animation
  53540. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  53541. */
  53542. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  53543. if (weight === void 0) { weight = 1.0; }
  53544. if (this._target instanceof Array) {
  53545. var index = 0;
  53546. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  53547. var target = _a[_i];
  53548. this._setValue(target, currentValue, weight, index);
  53549. index++;
  53550. }
  53551. }
  53552. else {
  53553. this._setValue(this._target, currentValue, weight);
  53554. }
  53555. };
  53556. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  53557. if (targetIndex === void 0) { targetIndex = 0; }
  53558. // Set value
  53559. var path;
  53560. var destination;
  53561. var targetPropertyPath = this._animation.targetPropertyPath;
  53562. if (targetPropertyPath.length > 1) {
  53563. var property = target[targetPropertyPath[0]];
  53564. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  53565. property = property[targetPropertyPath[index]];
  53566. }
  53567. path = targetPropertyPath[targetPropertyPath.length - 1];
  53568. destination = property;
  53569. }
  53570. else {
  53571. path = targetPropertyPath[0];
  53572. destination = target;
  53573. }
  53574. this._targetPath = path;
  53575. this._activeTarget = destination;
  53576. this._weight = weight;
  53577. if (this._originalValue[targetIndex] === undefined) {
  53578. var originalValue = void 0;
  53579. if (destination.getRestPose && path === "_matrix") { // For bones
  53580. originalValue = destination.getRestPose();
  53581. }
  53582. else {
  53583. originalValue = destination[path];
  53584. }
  53585. if (originalValue && originalValue.clone) {
  53586. this._originalValue[targetIndex] = originalValue.clone();
  53587. }
  53588. else {
  53589. this._originalValue[targetIndex] = originalValue;
  53590. }
  53591. }
  53592. // Blending
  53593. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  53594. if (enableBlending && this._blendingFactor <= 1.0) {
  53595. if (!this._originalBlendValue) {
  53596. var originalValue = destination[path];
  53597. if (originalValue.clone) {
  53598. this._originalBlendValue = originalValue.clone();
  53599. }
  53600. else {
  53601. this._originalBlendValue = originalValue;
  53602. }
  53603. }
  53604. if (this._originalBlendValue.m) { // Matrix
  53605. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  53606. if (this._currentValue) {
  53607. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53608. }
  53609. else {
  53610. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53611. }
  53612. }
  53613. else {
  53614. if (this._currentValue) {
  53615. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  53616. }
  53617. else {
  53618. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53619. }
  53620. }
  53621. }
  53622. else {
  53623. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  53624. }
  53625. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  53626. this._blendingFactor += blendingSpeed;
  53627. }
  53628. else {
  53629. this._currentValue = currentValue;
  53630. }
  53631. if (weight !== -1.0) {
  53632. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  53633. }
  53634. else {
  53635. destination[path] = this._currentValue;
  53636. }
  53637. if (target.markAsDirty) {
  53638. target.markAsDirty(this._animation.targetProperty);
  53639. }
  53640. };
  53641. /**
  53642. * Gets the loop pmode of the runtime animation
  53643. * @returns Loop Mode
  53644. */
  53645. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  53646. if (this._target && this._target.animationPropertiesOverride) {
  53647. return this._target.animationPropertiesOverride.loopMode;
  53648. }
  53649. return this._animation.loopMode;
  53650. };
  53651. /**
  53652. * Move the current animation to a given frame
  53653. * @param frame defines the frame to move to
  53654. */
  53655. RuntimeAnimation.prototype.goToFrame = function (frame) {
  53656. var keys = this._animation.getKeys();
  53657. if (frame < keys[0].frame) {
  53658. frame = keys[0].frame;
  53659. }
  53660. else if (frame > keys[keys.length - 1].frame) {
  53661. frame = keys[keys.length - 1].frame;
  53662. }
  53663. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  53664. this.setValue(currentValue, -1);
  53665. };
  53666. /**
  53667. * @hidden Internal use only
  53668. */
  53669. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  53670. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  53671. this._ratioOffset = this._previousRatio - newRatio;
  53672. };
  53673. /**
  53674. * Execute the current animation
  53675. * @param delay defines the delay to add to the current frame
  53676. * @param from defines the lower bound of the animation range
  53677. * @param to defines the upper bound of the animation range
  53678. * @param loop defines if the current animation must loop
  53679. * @param speedRatio defines the current speed ratio
  53680. * @param weight defines the weight of the animation (default is -1 so no weight)
  53681. * @returns a boolean indicating if the animation is running
  53682. */
  53683. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  53684. if (weight === void 0) { weight = -1.0; }
  53685. var targetPropertyPath = this._animation.targetPropertyPath;
  53686. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  53687. this._stopped = true;
  53688. return false;
  53689. }
  53690. var returnValue = true;
  53691. var keys = this._animation.getKeys();
  53692. // Adding a start key at frame 0 if missing
  53693. if (keys[0].frame !== 0) {
  53694. var newKey = { frame: 0, value: keys[0].value };
  53695. keys.splice(0, 0, newKey);
  53696. }
  53697. // Adding a duplicate key when there is only one key at frame zero
  53698. else if (keys.length === 1) {
  53699. var newKey = { frame: 0.001, value: keys[0].value };
  53700. keys.push(newKey);
  53701. }
  53702. // Check limits
  53703. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  53704. from = keys[0].frame;
  53705. }
  53706. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  53707. to = keys[keys.length - 1].frame;
  53708. }
  53709. //to and from cannot be the same key
  53710. if (from === to) {
  53711. if (from > keys[0].frame) {
  53712. from--;
  53713. }
  53714. else if (to < keys[keys.length - 1].frame) {
  53715. to++;
  53716. }
  53717. }
  53718. // Compute ratio
  53719. var range = to - from;
  53720. var offsetValue;
  53721. // ratio represents the frame delta between from and to
  53722. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  53723. var highLimitValue = 0;
  53724. this._previousDelay = delay;
  53725. this._previousRatio = ratio;
  53726. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  53727. returnValue = false;
  53728. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  53729. }
  53730. else {
  53731. // Get max value if required
  53732. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  53733. var keyOffset = to.toString() + from.toString();
  53734. if (!this._offsetsCache[keyOffset]) {
  53735. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53736. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  53737. switch (this._animation.dataType) {
  53738. // Float
  53739. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53740. this._offsetsCache[keyOffset] = toValue - fromValue;
  53741. break;
  53742. // Quaternion
  53743. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53744. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53745. break;
  53746. // Vector3
  53747. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53748. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53749. // Vector2
  53750. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53751. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53752. // Size
  53753. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53754. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53755. // Color3
  53756. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53757. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  53758. default:
  53759. break;
  53760. }
  53761. this._highLimitsCache[keyOffset] = toValue;
  53762. }
  53763. highLimitValue = this._highLimitsCache[keyOffset];
  53764. offsetValue = this._offsetsCache[keyOffset];
  53765. }
  53766. }
  53767. if (offsetValue === undefined) {
  53768. switch (this._animation.dataType) {
  53769. // Float
  53770. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  53771. offsetValue = 0;
  53772. break;
  53773. // Quaternion
  53774. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  53775. offsetValue = _staticOffsetValueQuaternion;
  53776. break;
  53777. // Vector3
  53778. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  53779. offsetValue = _staticOffsetValueVector3;
  53780. break;
  53781. // Vector2
  53782. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  53783. offsetValue = _staticOffsetValueVector2;
  53784. break;
  53785. // Size
  53786. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  53787. offsetValue = _staticOffsetValueSize;
  53788. break;
  53789. // Color3
  53790. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  53791. offsetValue = _staticOffsetValueColor3;
  53792. }
  53793. }
  53794. // Compute value
  53795. var repeatCount = (ratio / range) >> 0;
  53796. var currentFrame = returnValue ? from + ratio % range : to;
  53797. // Need to normalize?
  53798. if (this._host && this._host.syncRoot) {
  53799. var syncRoot = this._host.syncRoot;
  53800. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  53801. currentFrame = from + (to - from) * hostNormalizedFrame;
  53802. }
  53803. // Reset events if looping
  53804. var events = this._events;
  53805. if (range > 0 && this.currentFrame > currentFrame ||
  53806. range < 0 && this.currentFrame < currentFrame) {
  53807. // Need to reset animation events
  53808. for (var index = 0; index < events.length; index++) {
  53809. if (!events[index].onlyOnce) {
  53810. // reset event, the animation is looping
  53811. events[index].isDone = false;
  53812. }
  53813. }
  53814. }
  53815. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  53816. // Set value
  53817. this.setValue(currentValue, weight);
  53818. // Check events
  53819. for (var index = 0; index < events.length; index++) {
  53820. // Make sure current frame has passed event frame and that event frame is within the current range
  53821. // Also, handle both forward and reverse animations
  53822. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  53823. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  53824. var event = events[index];
  53825. if (!event.isDone) {
  53826. // If event should be done only once, remove it.
  53827. if (event.onlyOnce) {
  53828. events.splice(index, 1);
  53829. index--;
  53830. }
  53831. event.isDone = true;
  53832. event.action(currentFrame);
  53833. } // Don't do anything if the event has already be done.
  53834. }
  53835. }
  53836. if (!returnValue) {
  53837. this._stopped = true;
  53838. }
  53839. return returnValue;
  53840. };
  53841. return RuntimeAnimation;
  53842. }());
  53843. BABYLON.RuntimeAnimation = RuntimeAnimation;
  53844. })(BABYLON || (BABYLON = {}));
  53845. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  53846. var BABYLON;
  53847. (function (BABYLON) {
  53848. /**
  53849. * Class used to store an actual running animation
  53850. */
  53851. var Animatable = /** @class */ (function () {
  53852. /**
  53853. * Creates a new Animatable
  53854. * @param scene defines the hosting scene
  53855. * @param target defines the target object
  53856. * @param fromFrame defines the starting frame number (default is 0)
  53857. * @param toFrame defines the ending frame number (default is 100)
  53858. * @param loopAnimation defines if the animation must loop (default is false)
  53859. * @param speedRatio defines the factor to apply to animation speed (default is 1)
  53860. * @param onAnimationEnd defines a callback to call when animation ends if it is not looping
  53861. * @param animations defines a group of animation to add to the new Animatable
  53862. */
  53863. function Animatable(scene,
  53864. /** defines the target object */
  53865. target,
  53866. /** defines the starting frame number (default is 0) */
  53867. fromFrame,
  53868. /** defines the ending frame number (default is 100) */
  53869. toFrame,
  53870. /** defines if the animation must loop (default is false) */
  53871. loopAnimation, speedRatio,
  53872. /** defines a callback to call when animation ends if it is not looping */
  53873. onAnimationEnd, animations) {
  53874. if (fromFrame === void 0) { fromFrame = 0; }
  53875. if (toFrame === void 0) { toFrame = 100; }
  53876. if (loopAnimation === void 0) { loopAnimation = false; }
  53877. if (speedRatio === void 0) { speedRatio = 1.0; }
  53878. this.target = target;
  53879. this.fromFrame = fromFrame;
  53880. this.toFrame = toFrame;
  53881. this.loopAnimation = loopAnimation;
  53882. this.onAnimationEnd = onAnimationEnd;
  53883. this._localDelayOffset = null;
  53884. this._pausedDelay = null;
  53885. this._runtimeAnimations = new Array();
  53886. this._paused = false;
  53887. this._speedRatio = 1;
  53888. this._weight = -1.0;
  53889. /**
  53890. * Gets or sets a boolean indicating if the animatable must be disposed and removed at the end of the animation.
  53891. * This will only apply for non looping animation (default is true)
  53892. */
  53893. this.disposeOnEnd = true;
  53894. /**
  53895. * Gets a boolean indicating if the animation has started
  53896. */
  53897. this.animationStarted = false;
  53898. /**
  53899. * Observer raised when the animation ends
  53900. */
  53901. this.onAnimationEndObservable = new BABYLON.Observable();
  53902. this._scene = scene;
  53903. if (animations) {
  53904. this.appendAnimations(target, animations);
  53905. }
  53906. this._speedRatio = speedRatio;
  53907. scene._activeAnimatables.push(this);
  53908. }
  53909. Object.defineProperty(Animatable.prototype, "syncRoot", {
  53910. /**
  53911. * Gets the root Animatable used to synchronize and normalize animations
  53912. */
  53913. get: function () {
  53914. return this._syncRoot;
  53915. },
  53916. enumerable: true,
  53917. configurable: true
  53918. });
  53919. Object.defineProperty(Animatable.prototype, "masterFrame", {
  53920. /**
  53921. * Gets the current frame of the first RuntimeAnimation
  53922. * Used to synchronize Animatables
  53923. */
  53924. get: function () {
  53925. if (this._runtimeAnimations.length === 0) {
  53926. return 0;
  53927. }
  53928. return this._runtimeAnimations[0].currentFrame;
  53929. },
  53930. enumerable: true,
  53931. configurable: true
  53932. });
  53933. Object.defineProperty(Animatable.prototype, "weight", {
  53934. /**
  53935. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  53936. */
  53937. get: function () {
  53938. return this._weight;
  53939. },
  53940. set: function (value) {
  53941. if (value === -1) { // -1 is ok and means no weight
  53942. this._weight = -1;
  53943. return;
  53944. }
  53945. // Else weight must be in [0, 1] range
  53946. this._weight = Math.min(Math.max(value, 0), 1.0);
  53947. },
  53948. enumerable: true,
  53949. configurable: true
  53950. });
  53951. Object.defineProperty(Animatable.prototype, "speedRatio", {
  53952. /**
  53953. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  53954. */
  53955. get: function () {
  53956. return this._speedRatio;
  53957. },
  53958. set: function (value) {
  53959. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  53960. var animation = this._runtimeAnimations[index];
  53961. animation._prepareForSpeedRatioChange(value);
  53962. }
  53963. this._speedRatio = value;
  53964. },
  53965. enumerable: true,
  53966. configurable: true
  53967. });
  53968. // Methods
  53969. /**
  53970. * Synchronize and normalize current Animatable with a source Animatable
  53971. * This is useful when using animation weights and when animations are not of the same length
  53972. * @param root defines the root Animatable to synchronize with
  53973. * @returns the current Animatable
  53974. */
  53975. Animatable.prototype.syncWith = function (root) {
  53976. this._syncRoot = root;
  53977. if (root) {
  53978. // Make sure this animatable will animate after the root
  53979. var index = this._scene._activeAnimatables.indexOf(this);
  53980. if (index > -1) {
  53981. this._scene._activeAnimatables.splice(index, 1);
  53982. this._scene._activeAnimatables.push(this);
  53983. }
  53984. }
  53985. return this;
  53986. };
  53987. /**
  53988. * Gets the list of runtime animations
  53989. * @returns an array of RuntimeAnimation
  53990. */
  53991. Animatable.prototype.getAnimations = function () {
  53992. return this._runtimeAnimations;
  53993. };
  53994. /**
  53995. * Adds more animations to the current animatable
  53996. * @param target defines the target of the animations
  53997. * @param animations defines the new animations to add
  53998. */
  53999. Animatable.prototype.appendAnimations = function (target, animations) {
  54000. for (var index = 0; index < animations.length; index++) {
  54001. var animation = animations[index];
  54002. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  54003. }
  54004. };
  54005. /**
  54006. * Gets the source animation for a specific property
  54007. * @param property defines the propertyu to look for
  54008. * @returns null or the source animation for the given property
  54009. */
  54010. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  54011. var runtimeAnimations = this._runtimeAnimations;
  54012. for (var index = 0; index < runtimeAnimations.length; index++) {
  54013. if (runtimeAnimations[index].animation.targetProperty === property) {
  54014. return runtimeAnimations[index].animation;
  54015. }
  54016. }
  54017. return null;
  54018. };
  54019. /**
  54020. * Gets the runtime animation for a specific property
  54021. * @param property defines the propertyu to look for
  54022. * @returns null or the runtime animation for the given property
  54023. */
  54024. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  54025. var runtimeAnimations = this._runtimeAnimations;
  54026. for (var index = 0; index < runtimeAnimations.length; index++) {
  54027. if (runtimeAnimations[index].animation.targetProperty === property) {
  54028. return runtimeAnimations[index];
  54029. }
  54030. }
  54031. return null;
  54032. };
  54033. /**
  54034. * Resets the animatable to its original state
  54035. */
  54036. Animatable.prototype.reset = function () {
  54037. var runtimeAnimations = this._runtimeAnimations;
  54038. for (var index = 0; index < runtimeAnimations.length; index++) {
  54039. runtimeAnimations[index].reset(true);
  54040. }
  54041. this._localDelayOffset = null;
  54042. this._pausedDelay = null;
  54043. };
  54044. /**
  54045. * Allows the animatable to blend with current running animations
  54046. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54047. * @param blendingSpeed defines the blending speed to use
  54048. */
  54049. Animatable.prototype.enableBlending = function (blendingSpeed) {
  54050. var runtimeAnimations = this._runtimeAnimations;
  54051. for (var index = 0; index < runtimeAnimations.length; index++) {
  54052. runtimeAnimations[index].animation.enableBlending = true;
  54053. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  54054. }
  54055. };
  54056. /**
  54057. * Disable animation blending
  54058. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  54059. */
  54060. Animatable.prototype.disableBlending = function () {
  54061. var runtimeAnimations = this._runtimeAnimations;
  54062. for (var index = 0; index < runtimeAnimations.length; index++) {
  54063. runtimeAnimations[index].animation.enableBlending = false;
  54064. }
  54065. };
  54066. /**
  54067. * Jump directly to a given frame
  54068. * @param frame defines the frame to jump to
  54069. */
  54070. Animatable.prototype.goToFrame = function (frame) {
  54071. var runtimeAnimations = this._runtimeAnimations;
  54072. if (runtimeAnimations[0]) {
  54073. var fps = runtimeAnimations[0].animation.framePerSecond;
  54074. var currentFrame = runtimeAnimations[0].currentFrame;
  54075. var adjustTime = frame - currentFrame;
  54076. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  54077. if (this._localDelayOffset === null) {
  54078. this._localDelayOffset = 0;
  54079. }
  54080. this._localDelayOffset -= delay;
  54081. }
  54082. for (var index = 0; index < runtimeAnimations.length; index++) {
  54083. runtimeAnimations[index].goToFrame(frame);
  54084. }
  54085. };
  54086. /**
  54087. * Pause the animation
  54088. */
  54089. Animatable.prototype.pause = function () {
  54090. if (this._paused) {
  54091. return;
  54092. }
  54093. this._paused = true;
  54094. };
  54095. /**
  54096. * Restart the animation
  54097. */
  54098. Animatable.prototype.restart = function () {
  54099. this._paused = false;
  54100. };
  54101. Animatable.prototype._raiseOnAnimationEnd = function () {
  54102. if (this.onAnimationEnd) {
  54103. this.onAnimationEnd();
  54104. }
  54105. this.onAnimationEndObservable.notifyObservers(this);
  54106. };
  54107. /**
  54108. * Stop and delete the current animation
  54109. * @param animationName defines a string used to only stop some of the runtime animations instead of all
  54110. * @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)
  54111. */
  54112. Animatable.prototype.stop = function (animationName, targetMask) {
  54113. if (animationName || targetMask) {
  54114. var idx = this._scene._activeAnimatables.indexOf(this);
  54115. if (idx > -1) {
  54116. var runtimeAnimations = this._runtimeAnimations;
  54117. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  54118. var runtimeAnimation = runtimeAnimations[index];
  54119. if (animationName && runtimeAnimation.animation.name != animationName) {
  54120. continue;
  54121. }
  54122. if (targetMask && !targetMask(runtimeAnimation.target)) {
  54123. continue;
  54124. }
  54125. runtimeAnimation.dispose();
  54126. runtimeAnimations.splice(index, 1);
  54127. }
  54128. if (runtimeAnimations.length == 0) {
  54129. this._scene._activeAnimatables.splice(idx, 1);
  54130. this._raiseOnAnimationEnd();
  54131. }
  54132. }
  54133. }
  54134. else {
  54135. var index = this._scene._activeAnimatables.indexOf(this);
  54136. if (index > -1) {
  54137. this._scene._activeAnimatables.splice(index, 1);
  54138. var runtimeAnimations = this._runtimeAnimations;
  54139. for (var index = 0; index < runtimeAnimations.length; index++) {
  54140. runtimeAnimations[index].dispose();
  54141. }
  54142. this._raiseOnAnimationEnd();
  54143. }
  54144. }
  54145. };
  54146. /**
  54147. * Wait asynchronously for the animation to end
  54148. * @returns a promise which will be fullfilled when the animation ends
  54149. */
  54150. Animatable.prototype.waitAsync = function () {
  54151. var _this = this;
  54152. return new Promise(function (resolve, reject) {
  54153. _this.onAnimationEndObservable.add(function () {
  54154. resolve(_this);
  54155. }, undefined, undefined, _this, true);
  54156. });
  54157. };
  54158. /** @hidden */
  54159. Animatable.prototype._animate = function (delay) {
  54160. if (this._paused) {
  54161. this.animationStarted = false;
  54162. if (this._pausedDelay === null) {
  54163. this._pausedDelay = delay;
  54164. }
  54165. return true;
  54166. }
  54167. if (this._localDelayOffset === null) {
  54168. this._localDelayOffset = delay;
  54169. this._pausedDelay = null;
  54170. }
  54171. else if (this._pausedDelay !== null) {
  54172. this._localDelayOffset += delay - this._pausedDelay;
  54173. this._pausedDelay = null;
  54174. }
  54175. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  54176. return true;
  54177. }
  54178. // Animating
  54179. var running = false;
  54180. var runtimeAnimations = this._runtimeAnimations;
  54181. var index;
  54182. for (index = 0; index < runtimeAnimations.length; index++) {
  54183. var animation = runtimeAnimations[index];
  54184. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  54185. running = running || isRunning;
  54186. }
  54187. this.animationStarted = running;
  54188. if (!running) {
  54189. if (this.disposeOnEnd) {
  54190. // Remove from active animatables
  54191. index = this._scene._activeAnimatables.indexOf(this);
  54192. this._scene._activeAnimatables.splice(index, 1);
  54193. // Dispose all runtime animations
  54194. for (index = 0; index < runtimeAnimations.length; index++) {
  54195. runtimeAnimations[index].dispose();
  54196. }
  54197. }
  54198. this._raiseOnAnimationEnd();
  54199. if (this.disposeOnEnd) {
  54200. this.onAnimationEnd = null;
  54201. this.onAnimationEndObservable.clear();
  54202. }
  54203. }
  54204. return running;
  54205. };
  54206. return Animatable;
  54207. }());
  54208. BABYLON.Animatable = Animatable;
  54209. })(BABYLON || (BABYLON = {}));
  54210. //# sourceMappingURL=babylon.animatable.js.map
  54211. var BABYLON;
  54212. (function (BABYLON) {
  54213. /**
  54214. * Base class used for every default easing function.
  54215. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54216. */
  54217. var EasingFunction = /** @class */ (function () {
  54218. function EasingFunction() {
  54219. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  54220. }
  54221. /**
  54222. * Sets the easing mode of the current function.
  54223. * @param easingMode Defines the willing mode (EASINGMODE_EASEIN, EASINGMODE_EASEOUT or EASINGMODE_EASEINOUT)
  54224. */
  54225. EasingFunction.prototype.setEasingMode = function (easingMode) {
  54226. var n = Math.min(Math.max(easingMode, 0), 2);
  54227. this._easingMode = n;
  54228. };
  54229. /**
  54230. * Gets the current easing mode.
  54231. * @returns the easing mode
  54232. */
  54233. EasingFunction.prototype.getEasingMode = function () {
  54234. return this._easingMode;
  54235. };
  54236. /**
  54237. * @hidden
  54238. */
  54239. EasingFunction.prototype.easeInCore = function (gradient) {
  54240. throw new Error('You must implement this method');
  54241. };
  54242. /**
  54243. * Given an input gradient between 0 and 1, this returns the corrseponding value
  54244. * of the easing function.
  54245. * @param gradient Defines the value between 0 and 1 we want the easing value for
  54246. * @returns the corresponding value on the curve defined by the easing function
  54247. */
  54248. EasingFunction.prototype.ease = function (gradient) {
  54249. switch (this._easingMode) {
  54250. case EasingFunction.EASINGMODE_EASEIN:
  54251. return this.easeInCore(gradient);
  54252. case EasingFunction.EASINGMODE_EASEOUT:
  54253. return (1 - this.easeInCore(1 - gradient));
  54254. }
  54255. if (gradient >= 0.5) {
  54256. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  54257. }
  54258. return (this.easeInCore(gradient * 2) * 0.5);
  54259. };
  54260. /**
  54261. * Interpolation follows the mathematical formula associated with the easing function.
  54262. */
  54263. EasingFunction.EASINGMODE_EASEIN = 0;
  54264. /**
  54265. * Interpolation follows 100% interpolation minus the output of the formula associated with the easing function.
  54266. */
  54267. EasingFunction.EASINGMODE_EASEOUT = 1;
  54268. /**
  54269. * Interpolation uses EaseIn for the first half of the animation and EaseOut for the second half.
  54270. */
  54271. EasingFunction.EASINGMODE_EASEINOUT = 2;
  54272. return EasingFunction;
  54273. }());
  54274. BABYLON.EasingFunction = EasingFunction;
  54275. /**
  54276. * Easing function with a circle shape (see link below).
  54277. * @see https://easings.net/#easeInCirc
  54278. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54279. */
  54280. var CircleEase = /** @class */ (function (_super) {
  54281. __extends(CircleEase, _super);
  54282. function CircleEase() {
  54283. return _super !== null && _super.apply(this, arguments) || this;
  54284. }
  54285. /** @hidden */
  54286. CircleEase.prototype.easeInCore = function (gradient) {
  54287. gradient = Math.max(0, Math.min(1, gradient));
  54288. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  54289. };
  54290. return CircleEase;
  54291. }(EasingFunction));
  54292. BABYLON.CircleEase = CircleEase;
  54293. /**
  54294. * Easing function with a ease back shape (see link below).
  54295. * @see https://easings.net/#easeInBack
  54296. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54297. */
  54298. var BackEase = /** @class */ (function (_super) {
  54299. __extends(BackEase, _super);
  54300. /**
  54301. * Instantiates a back ease easing
  54302. * @see https://easings.net/#easeInBack
  54303. * @param amplitude Defines the amplitude of the function
  54304. */
  54305. function BackEase(
  54306. /** Defines the amplitude of the function */
  54307. amplitude) {
  54308. if (amplitude === void 0) { amplitude = 1; }
  54309. var _this = _super.call(this) || this;
  54310. _this.amplitude = amplitude;
  54311. return _this;
  54312. }
  54313. /** @hidden */
  54314. BackEase.prototype.easeInCore = function (gradient) {
  54315. var num = Math.max(0, this.amplitude);
  54316. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  54317. };
  54318. return BackEase;
  54319. }(EasingFunction));
  54320. BABYLON.BackEase = BackEase;
  54321. /**
  54322. * Easing function with a bouncing shape (see link below).
  54323. * @see https://easings.net/#easeInBounce
  54324. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54325. */
  54326. var BounceEase = /** @class */ (function (_super) {
  54327. __extends(BounceEase, _super);
  54328. /**
  54329. * Instantiates a bounce easing
  54330. * @see https://easings.net/#easeInBounce
  54331. * @param bounces Defines the number of bounces
  54332. * @param bounciness Defines the amplitude of the bounce
  54333. */
  54334. function BounceEase(
  54335. /** Defines the number of bounces */
  54336. bounces,
  54337. /** Defines the amplitude of the bounce */
  54338. bounciness) {
  54339. if (bounces === void 0) { bounces = 3; }
  54340. if (bounciness === void 0) { bounciness = 2; }
  54341. var _this = _super.call(this) || this;
  54342. _this.bounces = bounces;
  54343. _this.bounciness = bounciness;
  54344. return _this;
  54345. }
  54346. /** @hidden */
  54347. BounceEase.prototype.easeInCore = function (gradient) {
  54348. var y = Math.max(0.0, this.bounces);
  54349. var bounciness = this.bounciness;
  54350. if (bounciness <= 1.0) {
  54351. bounciness = 1.001;
  54352. }
  54353. var num9 = Math.pow(bounciness, y);
  54354. var num5 = 1.0 - bounciness;
  54355. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  54356. var num15 = gradient * num4;
  54357. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  54358. var num3 = Math.floor(num65);
  54359. var num13 = num3 + 1.0;
  54360. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  54361. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  54362. var num7 = (num8 + num12) * 0.5;
  54363. var num6 = gradient - num7;
  54364. var num2 = num7 - num8;
  54365. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  54366. };
  54367. return BounceEase;
  54368. }(EasingFunction));
  54369. BABYLON.BounceEase = BounceEase;
  54370. /**
  54371. * Easing function with a power of 3 shape (see link below).
  54372. * @see https://easings.net/#easeInCubic
  54373. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54374. */
  54375. var CubicEase = /** @class */ (function (_super) {
  54376. __extends(CubicEase, _super);
  54377. function CubicEase() {
  54378. return _super !== null && _super.apply(this, arguments) || this;
  54379. }
  54380. /** @hidden */
  54381. CubicEase.prototype.easeInCore = function (gradient) {
  54382. return (gradient * gradient * gradient);
  54383. };
  54384. return CubicEase;
  54385. }(EasingFunction));
  54386. BABYLON.CubicEase = CubicEase;
  54387. /**
  54388. * Easing function with an elastic shape (see link below).
  54389. * @see https://easings.net/#easeInElastic
  54390. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54391. */
  54392. var ElasticEase = /** @class */ (function (_super) {
  54393. __extends(ElasticEase, _super);
  54394. /**
  54395. * Instantiates an elastic easing function
  54396. * @see https://easings.net/#easeInElastic
  54397. * @param oscillations Defines the number of oscillations
  54398. * @param springiness Defines the amplitude of the oscillations
  54399. */
  54400. function ElasticEase(
  54401. /** Defines the number of oscillations*/
  54402. oscillations,
  54403. /** Defines the amplitude of the oscillations*/
  54404. springiness) {
  54405. if (oscillations === void 0) { oscillations = 3; }
  54406. if (springiness === void 0) { springiness = 3; }
  54407. var _this = _super.call(this) || this;
  54408. _this.oscillations = oscillations;
  54409. _this.springiness = springiness;
  54410. return _this;
  54411. }
  54412. /** @hidden */
  54413. ElasticEase.prototype.easeInCore = function (gradient) {
  54414. var num2;
  54415. var num3 = Math.max(0.0, this.oscillations);
  54416. var num = Math.max(0.0, this.springiness);
  54417. if (num == 0) {
  54418. num2 = gradient;
  54419. }
  54420. else {
  54421. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  54422. }
  54423. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  54424. };
  54425. return ElasticEase;
  54426. }(EasingFunction));
  54427. BABYLON.ElasticEase = ElasticEase;
  54428. /**
  54429. * Easing function with an exponential shape (see link below).
  54430. * @see https://easings.net/#easeInExpo
  54431. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54432. */
  54433. var ExponentialEase = /** @class */ (function (_super) {
  54434. __extends(ExponentialEase, _super);
  54435. /**
  54436. * Instantiates an exponential easing function
  54437. * @see https://easings.net/#easeInExpo
  54438. * @param exponent Defines the exponent of the function
  54439. */
  54440. function ExponentialEase(
  54441. /** Defines the exponent of the function */
  54442. exponent) {
  54443. if (exponent === void 0) { exponent = 2; }
  54444. var _this = _super.call(this) || this;
  54445. _this.exponent = exponent;
  54446. return _this;
  54447. }
  54448. /** @hidden */
  54449. ExponentialEase.prototype.easeInCore = function (gradient) {
  54450. if (this.exponent <= 0) {
  54451. return gradient;
  54452. }
  54453. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  54454. };
  54455. return ExponentialEase;
  54456. }(EasingFunction));
  54457. BABYLON.ExponentialEase = ExponentialEase;
  54458. /**
  54459. * Easing function with a power shape (see link below).
  54460. * @see https://easings.net/#easeInQuad
  54461. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54462. */
  54463. var PowerEase = /** @class */ (function (_super) {
  54464. __extends(PowerEase, _super);
  54465. /**
  54466. * Instantiates an power base easing function
  54467. * @see https://easings.net/#easeInQuad
  54468. * @param power Defines the power of the function
  54469. */
  54470. function PowerEase(
  54471. /** Defines the power of the function */
  54472. power) {
  54473. if (power === void 0) { power = 2; }
  54474. var _this = _super.call(this) || this;
  54475. _this.power = power;
  54476. return _this;
  54477. }
  54478. /** @hidden */
  54479. PowerEase.prototype.easeInCore = function (gradient) {
  54480. var y = Math.max(0.0, this.power);
  54481. return Math.pow(gradient, y);
  54482. };
  54483. return PowerEase;
  54484. }(EasingFunction));
  54485. BABYLON.PowerEase = PowerEase;
  54486. /**
  54487. * Easing function with a power of 2 shape (see link below).
  54488. * @see https://easings.net/#easeInQuad
  54489. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54490. */
  54491. var QuadraticEase = /** @class */ (function (_super) {
  54492. __extends(QuadraticEase, _super);
  54493. function QuadraticEase() {
  54494. return _super !== null && _super.apply(this, arguments) || this;
  54495. }
  54496. /** @hidden */
  54497. QuadraticEase.prototype.easeInCore = function (gradient) {
  54498. return (gradient * gradient);
  54499. };
  54500. return QuadraticEase;
  54501. }(EasingFunction));
  54502. BABYLON.QuadraticEase = QuadraticEase;
  54503. /**
  54504. * Easing function with a power of 4 shape (see link below).
  54505. * @see https://easings.net/#easeInQuart
  54506. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54507. */
  54508. var QuarticEase = /** @class */ (function (_super) {
  54509. __extends(QuarticEase, _super);
  54510. function QuarticEase() {
  54511. return _super !== null && _super.apply(this, arguments) || this;
  54512. }
  54513. /** @hidden */
  54514. QuarticEase.prototype.easeInCore = function (gradient) {
  54515. return (gradient * gradient * gradient * gradient);
  54516. };
  54517. return QuarticEase;
  54518. }(EasingFunction));
  54519. BABYLON.QuarticEase = QuarticEase;
  54520. /**
  54521. * Easing function with a power of 5 shape (see link below).
  54522. * @see https://easings.net/#easeInQuint
  54523. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54524. */
  54525. var QuinticEase = /** @class */ (function (_super) {
  54526. __extends(QuinticEase, _super);
  54527. function QuinticEase() {
  54528. return _super !== null && _super.apply(this, arguments) || this;
  54529. }
  54530. /** @hidden */
  54531. QuinticEase.prototype.easeInCore = function (gradient) {
  54532. return (gradient * gradient * gradient * gradient * gradient);
  54533. };
  54534. return QuinticEase;
  54535. }(EasingFunction));
  54536. BABYLON.QuinticEase = QuinticEase;
  54537. /**
  54538. * Easing function with a sin shape (see link below).
  54539. * @see https://easings.net/#easeInSine
  54540. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54541. */
  54542. var SineEase = /** @class */ (function (_super) {
  54543. __extends(SineEase, _super);
  54544. function SineEase() {
  54545. return _super !== null && _super.apply(this, arguments) || this;
  54546. }
  54547. /** @hidden */
  54548. SineEase.prototype.easeInCore = function (gradient) {
  54549. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  54550. };
  54551. return SineEase;
  54552. }(EasingFunction));
  54553. BABYLON.SineEase = SineEase;
  54554. /**
  54555. * Easing function with a bezier shape (see link below).
  54556. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54557. * @see http://doc.babylonjs.com/babylon101/animations#easing-functions
  54558. */
  54559. var BezierCurveEase = /** @class */ (function (_super) {
  54560. __extends(BezierCurveEase, _super);
  54561. /**
  54562. * Instantiates a bezier function
  54563. * @see http://cubic-bezier.com/#.17,.67,.83,.67
  54564. * @param x1 Defines the x component of the start tangent in the bezier curve
  54565. * @param y1 Defines the y component of the start tangent in the bezier curve
  54566. * @param x2 Defines the x component of the end tangent in the bezier curve
  54567. * @param y2 Defines the y component of the end tangent in the bezier curve
  54568. */
  54569. function BezierCurveEase(
  54570. /** Defines the x component of the start tangent in the bezier curve */
  54571. x1,
  54572. /** Defines the y component of the start tangent in the bezier curve */
  54573. y1,
  54574. /** Defines the x component of the end tangent in the bezier curve */
  54575. x2,
  54576. /** Defines the y component of the end tangent in the bezier curve */
  54577. y2) {
  54578. if (x1 === void 0) { x1 = 0; }
  54579. if (y1 === void 0) { y1 = 0; }
  54580. if (x2 === void 0) { x2 = 1; }
  54581. if (y2 === void 0) { y2 = 1; }
  54582. var _this = _super.call(this) || this;
  54583. _this.x1 = x1;
  54584. _this.y1 = y1;
  54585. _this.x2 = x2;
  54586. _this.y2 = y2;
  54587. return _this;
  54588. }
  54589. /** @hidden */
  54590. BezierCurveEase.prototype.easeInCore = function (gradient) {
  54591. return BABYLON.BezierCurve.Interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  54592. };
  54593. return BezierCurveEase;
  54594. }(EasingFunction));
  54595. BABYLON.BezierCurveEase = BezierCurveEase;
  54596. })(BABYLON || (BABYLON = {}));
  54597. //# sourceMappingURL=babylon.easing.js.map
  54598. var BABYLON;
  54599. (function (BABYLON) {
  54600. /**
  54601. * A Condition applied to an Action
  54602. */
  54603. var Condition = /** @class */ (function () {
  54604. /**
  54605. * Creates a new Condition
  54606. * @param actionManager the manager of the action the condition is applied to
  54607. */
  54608. function Condition(actionManager) {
  54609. this._actionManager = actionManager;
  54610. }
  54611. /**
  54612. * Check if the current condition is valid
  54613. * @returns a boolean
  54614. */
  54615. Condition.prototype.isValid = function () {
  54616. return true;
  54617. };
  54618. /**
  54619. * Internal only
  54620. * @hidden
  54621. */
  54622. Condition.prototype._getProperty = function (propertyPath) {
  54623. return this._actionManager._getProperty(propertyPath);
  54624. };
  54625. /**
  54626. * Internal only
  54627. * @hidden
  54628. */
  54629. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  54630. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54631. };
  54632. /**
  54633. * Serialize placeholder for child classes
  54634. * @returns the serialized object
  54635. */
  54636. Condition.prototype.serialize = function () {
  54637. };
  54638. /**
  54639. * Internal only
  54640. * @hidden
  54641. */
  54642. Condition.prototype._serialize = function (serializedCondition) {
  54643. return {
  54644. type: 2,
  54645. children: [],
  54646. name: serializedCondition.name,
  54647. properties: serializedCondition.properties
  54648. };
  54649. };
  54650. return Condition;
  54651. }());
  54652. BABYLON.Condition = Condition;
  54653. /**
  54654. * Defines specific conditional operators as extensions of Condition
  54655. */
  54656. var ValueCondition = /** @class */ (function (_super) {
  54657. __extends(ValueCondition, _super);
  54658. /**
  54659. * Creates a new ValueCondition
  54660. * @param actionManager manager for the action the condition applies to
  54661. * @param target for the action
  54662. * @param propertyPath path to specify the property of the target the conditional operator uses
  54663. * @param value the value compared by the conditional operator against the current value of the property
  54664. * @param operator the conditional operator, default ValueCondition.IsEqual
  54665. */
  54666. function ValueCondition(actionManager, target,
  54667. /** path to specify the property of the target the conditional operator uses */
  54668. propertyPath,
  54669. /** the value compared by the conditional operator against the current value of the property */
  54670. value,
  54671. /** the conditional operator, default ValueCondition.IsEqual */
  54672. operator) {
  54673. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  54674. var _this = _super.call(this, actionManager) || this;
  54675. _this.propertyPath = propertyPath;
  54676. _this.value = value;
  54677. _this.operator = operator;
  54678. _this._target = target;
  54679. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  54680. _this._property = _this._getProperty(_this.propertyPath);
  54681. return _this;
  54682. }
  54683. Object.defineProperty(ValueCondition, "IsEqual", {
  54684. /**
  54685. * returns the number for IsEqual
  54686. */
  54687. get: function () {
  54688. return ValueCondition._IsEqual;
  54689. },
  54690. enumerable: true,
  54691. configurable: true
  54692. });
  54693. Object.defineProperty(ValueCondition, "IsDifferent", {
  54694. /**
  54695. * Returns the number for IsDifferent
  54696. */
  54697. get: function () {
  54698. return ValueCondition._IsDifferent;
  54699. },
  54700. enumerable: true,
  54701. configurable: true
  54702. });
  54703. Object.defineProperty(ValueCondition, "IsGreater", {
  54704. /**
  54705. * Returns the number for IsGreater
  54706. */
  54707. get: function () {
  54708. return ValueCondition._IsGreater;
  54709. },
  54710. enumerable: true,
  54711. configurable: true
  54712. });
  54713. Object.defineProperty(ValueCondition, "IsLesser", {
  54714. /**
  54715. * Returns the number for IsLesser
  54716. */
  54717. get: function () {
  54718. return ValueCondition._IsLesser;
  54719. },
  54720. enumerable: true,
  54721. configurable: true
  54722. });
  54723. /**
  54724. * Compares the given value with the property value for the specified conditional operator
  54725. * @returns the result of the comparison
  54726. */
  54727. ValueCondition.prototype.isValid = function () {
  54728. switch (this.operator) {
  54729. case ValueCondition.IsGreater:
  54730. return this._effectiveTarget[this._property] > this.value;
  54731. case ValueCondition.IsLesser:
  54732. return this._effectiveTarget[this._property] < this.value;
  54733. case ValueCondition.IsEqual:
  54734. case ValueCondition.IsDifferent:
  54735. var check;
  54736. if (this.value.equals) {
  54737. check = this.value.equals(this._effectiveTarget[this._property]);
  54738. }
  54739. else {
  54740. check = this.value === this._effectiveTarget[this._property];
  54741. }
  54742. return this.operator === ValueCondition.IsEqual ? check : !check;
  54743. }
  54744. return false;
  54745. };
  54746. /**
  54747. * Serialize the ValueCondition into a JSON compatible object
  54748. * @returns serialization object
  54749. */
  54750. ValueCondition.prototype.serialize = function () {
  54751. return this._serialize({
  54752. name: "ValueCondition",
  54753. properties: [
  54754. BABYLON.Action._GetTargetProperty(this._target),
  54755. { name: "propertyPath", value: this.propertyPath },
  54756. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  54757. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  54758. ]
  54759. });
  54760. };
  54761. /**
  54762. * Gets the name of the conditional operator for the ValueCondition
  54763. * @param operator the conditional operator
  54764. * @returns the name
  54765. */
  54766. ValueCondition.GetOperatorName = function (operator) {
  54767. switch (operator) {
  54768. case ValueCondition._IsEqual: return "IsEqual";
  54769. case ValueCondition._IsDifferent: return "IsDifferent";
  54770. case ValueCondition._IsGreater: return "IsGreater";
  54771. case ValueCondition._IsLesser: return "IsLesser";
  54772. default: return "";
  54773. }
  54774. };
  54775. /**
  54776. * Internal only
  54777. * @hidden
  54778. */
  54779. ValueCondition._IsEqual = 0;
  54780. /**
  54781. * Internal only
  54782. * @hidden
  54783. */
  54784. ValueCondition._IsDifferent = 1;
  54785. /**
  54786. * Internal only
  54787. * @hidden
  54788. */
  54789. ValueCondition._IsGreater = 2;
  54790. /**
  54791. * Internal only
  54792. * @hidden
  54793. */
  54794. ValueCondition._IsLesser = 3;
  54795. return ValueCondition;
  54796. }(Condition));
  54797. BABYLON.ValueCondition = ValueCondition;
  54798. /**
  54799. * Defines a predicate condition as an extension of Condition
  54800. */
  54801. var PredicateCondition = /** @class */ (function (_super) {
  54802. __extends(PredicateCondition, _super);
  54803. /**
  54804. * Creates a new PredicateCondition
  54805. * @param actionManager manager for the action the condition applies to
  54806. * @param predicate defines the predicate function used to validate the condition
  54807. */
  54808. function PredicateCondition(actionManager,
  54809. /** defines the predicate function used to validate the condition */
  54810. predicate) {
  54811. var _this = _super.call(this, actionManager) || this;
  54812. _this.predicate = predicate;
  54813. return _this;
  54814. }
  54815. /**
  54816. * @returns the validity of the predicate condition
  54817. */
  54818. PredicateCondition.prototype.isValid = function () {
  54819. return this.predicate();
  54820. };
  54821. return PredicateCondition;
  54822. }(Condition));
  54823. BABYLON.PredicateCondition = PredicateCondition;
  54824. /**
  54825. * Defines a state condition as an extension of Condition
  54826. */
  54827. var StateCondition = /** @class */ (function (_super) {
  54828. __extends(StateCondition, _super);
  54829. /**
  54830. * Creates a new StateCondition
  54831. * @param actionManager manager for the action the condition applies to
  54832. * @param target of the condition
  54833. * @param value to compare with target state
  54834. */
  54835. function StateCondition(actionManager, target,
  54836. /** Value to compare with target state */
  54837. value) {
  54838. var _this = _super.call(this, actionManager) || this;
  54839. _this.value = value;
  54840. _this._target = target;
  54841. return _this;
  54842. }
  54843. /**
  54844. * Gets a boolean indicating if the current condition is met
  54845. * @returns the validity of the state
  54846. */
  54847. StateCondition.prototype.isValid = function () {
  54848. return this._target.state === this.value;
  54849. };
  54850. /**
  54851. * Serialize the StateCondition into a JSON compatible object
  54852. * @returns serialization object
  54853. */
  54854. StateCondition.prototype.serialize = function () {
  54855. return this._serialize({
  54856. name: "StateCondition",
  54857. properties: [
  54858. BABYLON.Action._GetTargetProperty(this._target),
  54859. { name: "value", value: this.value }
  54860. ]
  54861. });
  54862. };
  54863. return StateCondition;
  54864. }(Condition));
  54865. BABYLON.StateCondition = StateCondition;
  54866. })(BABYLON || (BABYLON = {}));
  54867. //# sourceMappingURL=babylon.condition.js.map
  54868. var BABYLON;
  54869. (function (BABYLON) {
  54870. /**
  54871. * The action to be carried out following a trigger
  54872. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  54873. */
  54874. var Action = /** @class */ (function () {
  54875. /**
  54876. * Creates a new Action
  54877. * @param triggerOptions the trigger, with or without parameters, for the action
  54878. * @param condition an optional determinant of action
  54879. */
  54880. function Action(
  54881. /** the trigger, with or without parameters, for the action */
  54882. triggerOptions, condition) {
  54883. this.triggerOptions = triggerOptions;
  54884. /**
  54885. * An event triggered prior to action being executed.
  54886. */
  54887. this.onBeforeExecuteObservable = new BABYLON.Observable();
  54888. if (triggerOptions.parameter) {
  54889. this.trigger = triggerOptions.trigger;
  54890. this._triggerParameter = triggerOptions.parameter;
  54891. }
  54892. else if (triggerOptions.trigger) {
  54893. this.trigger = triggerOptions.trigger;
  54894. }
  54895. else {
  54896. this.trigger = triggerOptions;
  54897. }
  54898. this._nextActiveAction = this;
  54899. this._condition = condition;
  54900. }
  54901. /**
  54902. * Internal only
  54903. * @hidden
  54904. */
  54905. Action.prototype._prepare = function () {
  54906. };
  54907. /**
  54908. * Gets the trigger parameters
  54909. * @returns the trigger parameters
  54910. */
  54911. Action.prototype.getTriggerParameter = function () {
  54912. return this._triggerParameter;
  54913. };
  54914. /**
  54915. * Internal only - executes current action event
  54916. * @hidden
  54917. */
  54918. Action.prototype._executeCurrent = function (evt) {
  54919. if (this._nextActiveAction._condition) {
  54920. var condition = this._nextActiveAction._condition;
  54921. var currentRenderId = this._actionManager.getScene().getRenderId();
  54922. // We cache the current evaluation for the current frame
  54923. if (condition._evaluationId === currentRenderId) {
  54924. if (!condition._currentResult) {
  54925. return;
  54926. }
  54927. }
  54928. else {
  54929. condition._evaluationId = currentRenderId;
  54930. if (!condition.isValid()) {
  54931. condition._currentResult = false;
  54932. return;
  54933. }
  54934. condition._currentResult = true;
  54935. }
  54936. }
  54937. this.onBeforeExecuteObservable.notifyObservers(this);
  54938. this._nextActiveAction.execute(evt);
  54939. this.skipToNextActiveAction();
  54940. };
  54941. /**
  54942. * Execute placeholder for child classes
  54943. * @param evt optional action event
  54944. */
  54945. Action.prototype.execute = function (evt) {
  54946. };
  54947. /**
  54948. * Skips to next active action
  54949. */
  54950. Action.prototype.skipToNextActiveAction = function () {
  54951. if (this._nextActiveAction._child) {
  54952. if (!this._nextActiveAction._child._actionManager) {
  54953. this._nextActiveAction._child._actionManager = this._actionManager;
  54954. }
  54955. this._nextActiveAction = this._nextActiveAction._child;
  54956. }
  54957. else {
  54958. this._nextActiveAction = this;
  54959. }
  54960. };
  54961. /**
  54962. * Adds action to chain of actions, may be a DoNothingAction
  54963. * @param action defines the next action to execute
  54964. * @returns The action passed in
  54965. * @see https://www.babylonjs-playground.com/#1T30HR#0
  54966. */
  54967. Action.prototype.then = function (action) {
  54968. this._child = action;
  54969. action._actionManager = this._actionManager;
  54970. action._prepare();
  54971. return action;
  54972. };
  54973. /**
  54974. * Internal only
  54975. * @hidden
  54976. */
  54977. Action.prototype._getProperty = function (propertyPath) {
  54978. return this._actionManager._getProperty(propertyPath);
  54979. };
  54980. /**
  54981. * Internal only
  54982. * @hidden
  54983. */
  54984. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  54985. return this._actionManager._getEffectiveTarget(target, propertyPath);
  54986. };
  54987. /**
  54988. * Serialize placeholder for child classes
  54989. * @param parent of child
  54990. * @returns the serialized object
  54991. */
  54992. Action.prototype.serialize = function (parent) {
  54993. };
  54994. /**
  54995. * Internal only called by serialize
  54996. * @hidden
  54997. */
  54998. Action.prototype._serialize = function (serializedAction, parent) {
  54999. var serializationObject = {
  55000. type: 1,
  55001. children: [],
  55002. name: serializedAction.name,
  55003. properties: serializedAction.properties || []
  55004. };
  55005. // Serialize child
  55006. if (this._child) {
  55007. this._child.serialize(serializationObject);
  55008. }
  55009. // Check if "this" has a condition
  55010. if (this._condition) {
  55011. var serializedCondition = this._condition.serialize();
  55012. serializedCondition.children.push(serializationObject);
  55013. if (parent) {
  55014. parent.children.push(serializedCondition);
  55015. }
  55016. return serializedCondition;
  55017. }
  55018. if (parent) {
  55019. parent.children.push(serializationObject);
  55020. }
  55021. return serializationObject;
  55022. };
  55023. /**
  55024. * Internal only
  55025. * @hidden
  55026. */
  55027. Action._SerializeValueAsString = function (value) {
  55028. if (typeof value === "number") {
  55029. return value.toString();
  55030. }
  55031. if (typeof value === "boolean") {
  55032. return value ? "true" : "false";
  55033. }
  55034. if (value instanceof BABYLON.Vector2) {
  55035. return value.x + ", " + value.y;
  55036. }
  55037. if (value instanceof BABYLON.Vector3) {
  55038. return value.x + ", " + value.y + ", " + value.z;
  55039. }
  55040. if (value instanceof BABYLON.Color3) {
  55041. return value.r + ", " + value.g + ", " + value.b;
  55042. }
  55043. if (value instanceof BABYLON.Color4) {
  55044. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  55045. }
  55046. return value; // string
  55047. };
  55048. /**
  55049. * Internal only
  55050. * @hidden
  55051. */
  55052. Action._GetTargetProperty = function (target) {
  55053. return {
  55054. name: "target",
  55055. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  55056. : target instanceof BABYLON.Light ? "LightProperties"
  55057. : target instanceof BABYLON.Camera ? "CameraProperties"
  55058. : "SceneProperties",
  55059. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  55060. };
  55061. };
  55062. return Action;
  55063. }());
  55064. BABYLON.Action = Action;
  55065. })(BABYLON || (BABYLON = {}));
  55066. //# sourceMappingURL=babylon.action.js.map
  55067. var BABYLON;
  55068. (function (BABYLON) {
  55069. /**
  55070. * ActionEvent is the event being sent when an action is triggered.
  55071. */
  55072. var ActionEvent = /** @class */ (function () {
  55073. /**
  55074. * Creates a new ActionEvent
  55075. * @param source The mesh or sprite that triggered the action
  55076. * @param pointerX The X mouse cursor position at the time of the event
  55077. * @param pointerY The Y mouse cursor position at the time of the event
  55078. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  55079. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  55080. * @param additionalData additional data for the event
  55081. */
  55082. function ActionEvent(
  55083. /** The mesh or sprite that triggered the action */
  55084. source,
  55085. /** The X mouse cursor position at the time of the event */
  55086. pointerX,
  55087. /** The Y mouse cursor position at the time of the event */
  55088. pointerY,
  55089. /** The mesh that is currently pointed at (can be null) */
  55090. meshUnderPointer,
  55091. /** the original (browser) event that triggered the ActionEvent */
  55092. sourceEvent,
  55093. /** additional data for the event */
  55094. additionalData) {
  55095. this.source = source;
  55096. this.pointerX = pointerX;
  55097. this.pointerY = pointerY;
  55098. this.meshUnderPointer = meshUnderPointer;
  55099. this.sourceEvent = sourceEvent;
  55100. this.additionalData = additionalData;
  55101. }
  55102. /**
  55103. * Helper function to auto-create an ActionEvent from a source mesh.
  55104. * @param source The source mesh that triggered the event
  55105. * @param evt The original (browser) event
  55106. * @param additionalData additional data for the event
  55107. * @returns the new ActionEvent
  55108. */
  55109. ActionEvent.CreateNew = function (source, evt, additionalData) {
  55110. var scene = source.getScene();
  55111. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55112. };
  55113. /**
  55114. * Helper function to auto-create an ActionEvent from a source sprite
  55115. * @param source The source sprite that triggered the event
  55116. * @param scene Scene associated with the sprite
  55117. * @param evt The original (browser) event
  55118. * @param additionalData additional data for the event
  55119. * @returns the new ActionEvent
  55120. */
  55121. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  55122. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  55123. };
  55124. /**
  55125. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  55126. * @param scene the scene where the event occurred
  55127. * @param evt The original (browser) event
  55128. * @returns the new ActionEvent
  55129. */
  55130. ActionEvent.CreateNewFromScene = function (scene, evt) {
  55131. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  55132. };
  55133. /**
  55134. * Helper function to auto-create an ActionEvent from a primitive
  55135. * @param prim defines the target primitive
  55136. * @param pointerPos defines the pointer position
  55137. * @param evt The original (browser) event
  55138. * @param additionalData additional data for the event
  55139. * @returns the new ActionEvent
  55140. */
  55141. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  55142. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  55143. };
  55144. return ActionEvent;
  55145. }());
  55146. BABYLON.ActionEvent = ActionEvent;
  55147. /**
  55148. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  55149. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  55150. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55151. */
  55152. var ActionManager = /** @class */ (function () {
  55153. /**
  55154. * Creates a new action manager
  55155. * @param scene defines the hosting scene
  55156. */
  55157. function ActionManager(scene) {
  55158. // Members
  55159. /** Gets the list of actions */
  55160. this.actions = new Array();
  55161. /** Gets the cursor to use when hovering items */
  55162. this.hoverCursor = '';
  55163. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55164. scene.actionManagers.push(this);
  55165. }
  55166. // Methods
  55167. /**
  55168. * Releases all associated resources
  55169. */
  55170. ActionManager.prototype.dispose = function () {
  55171. var index = this._scene.actionManagers.indexOf(this);
  55172. for (var i = 0; i < this.actions.length; i++) {
  55173. var action = this.actions[i];
  55174. ActionManager.Triggers[action.trigger]--;
  55175. if (ActionManager.Triggers[action.trigger] === 0) {
  55176. delete ActionManager.Triggers[action.trigger];
  55177. }
  55178. }
  55179. if (index > -1) {
  55180. this._scene.actionManagers.splice(index, 1);
  55181. }
  55182. };
  55183. /**
  55184. * Gets hosting scene
  55185. * @returns the hosting scene
  55186. */
  55187. ActionManager.prototype.getScene = function () {
  55188. return this._scene;
  55189. };
  55190. /**
  55191. * Does this action manager handles actions of any of the given triggers
  55192. * @param triggers defines the triggers to be tested
  55193. * @return a boolean indicating whether one (or more) of the triggers is handled
  55194. */
  55195. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  55196. for (var index = 0; index < this.actions.length; index++) {
  55197. var action = this.actions[index];
  55198. if (triggers.indexOf(action.trigger) > -1) {
  55199. return true;
  55200. }
  55201. }
  55202. return false;
  55203. };
  55204. /**
  55205. * Does this action manager handles actions of any of the given triggers. This function takes two arguments for
  55206. * speed.
  55207. * @param triggerA defines the trigger to be tested
  55208. * @param triggerB defines the trigger to be tested
  55209. * @return a boolean indicating whether one (or more) of the triggers is handled
  55210. */
  55211. ActionManager.prototype.hasSpecificTriggers2 = function (triggerA, triggerB) {
  55212. for (var index = 0; index < this.actions.length; index++) {
  55213. var action = this.actions[index];
  55214. if (triggerA == action.trigger || triggerB == action.trigger) {
  55215. return true;
  55216. }
  55217. }
  55218. return false;
  55219. };
  55220. /**
  55221. * Does this action manager handles actions of a given trigger
  55222. * @param trigger defines the trigger to be tested
  55223. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  55224. * @return whether the trigger is handled
  55225. */
  55226. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  55227. for (var index = 0; index < this.actions.length; index++) {
  55228. var action = this.actions[index];
  55229. if (action.trigger === trigger) {
  55230. if (parameterPredicate) {
  55231. if (parameterPredicate(action.getTriggerParameter())) {
  55232. return true;
  55233. }
  55234. }
  55235. else {
  55236. return true;
  55237. }
  55238. }
  55239. }
  55240. return false;
  55241. };
  55242. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  55243. /**
  55244. * Does this action manager has pointer triggers
  55245. */
  55246. get: function () {
  55247. for (var index = 0; index < this.actions.length; index++) {
  55248. var action = this.actions[index];
  55249. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPointerOutTrigger) {
  55250. return true;
  55251. }
  55252. }
  55253. return false;
  55254. },
  55255. enumerable: true,
  55256. configurable: true
  55257. });
  55258. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  55259. /**
  55260. * Does this action manager has pick triggers
  55261. */
  55262. get: function () {
  55263. for (var index = 0; index < this.actions.length; index++) {
  55264. var action = this.actions[index];
  55265. if (action.trigger >= ActionManager.OnPickTrigger && action.trigger <= ActionManager.OnPickUpTrigger) {
  55266. return true;
  55267. }
  55268. }
  55269. return false;
  55270. },
  55271. enumerable: true,
  55272. configurable: true
  55273. });
  55274. Object.defineProperty(ActionManager, "HasTriggers", {
  55275. /**
  55276. * Does exist one action manager with at least one trigger
  55277. **/
  55278. get: function () {
  55279. for (var t in ActionManager.Triggers) {
  55280. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55281. return true;
  55282. }
  55283. }
  55284. return false;
  55285. },
  55286. enumerable: true,
  55287. configurable: true
  55288. });
  55289. Object.defineProperty(ActionManager, "HasPickTriggers", {
  55290. /**
  55291. * Does exist one action manager with at least one pick trigger
  55292. **/
  55293. get: function () {
  55294. for (var t in ActionManager.Triggers) {
  55295. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55296. var t_int = parseInt(t);
  55297. if (t_int >= ActionManager.OnPickTrigger && t_int <= ActionManager.OnPickUpTrigger) {
  55298. return true;
  55299. }
  55300. }
  55301. }
  55302. return false;
  55303. },
  55304. enumerable: true,
  55305. configurable: true
  55306. });
  55307. /**
  55308. * Does exist one action manager that handles actions of a given trigger
  55309. * @param trigger defines the trigger to be tested
  55310. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  55311. **/
  55312. ActionManager.HasSpecificTrigger = function (trigger) {
  55313. for (var t in ActionManager.Triggers) {
  55314. if (ActionManager.Triggers.hasOwnProperty(t)) {
  55315. var t_int = parseInt(t);
  55316. if (t_int === trigger) {
  55317. return true;
  55318. }
  55319. }
  55320. }
  55321. return false;
  55322. };
  55323. /**
  55324. * Registers an action to this action manager
  55325. * @param action defines the action to be registered
  55326. * @return the action amended (prepared) after registration
  55327. */
  55328. ActionManager.prototype.registerAction = function (action) {
  55329. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  55330. if (this.getScene().actionManager !== this) {
  55331. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  55332. return null;
  55333. }
  55334. }
  55335. this.actions.push(action);
  55336. if (ActionManager.Triggers[action.trigger]) {
  55337. ActionManager.Triggers[action.trigger]++;
  55338. }
  55339. else {
  55340. ActionManager.Triggers[action.trigger] = 1;
  55341. }
  55342. action._actionManager = this;
  55343. action._prepare();
  55344. return action;
  55345. };
  55346. /**
  55347. * Unregisters an action to this action manager
  55348. * @param action defines the action to be unregistered
  55349. * @return a boolean indicating whether the action has been unregistered
  55350. */
  55351. ActionManager.prototype.unregisterAction = function (action) {
  55352. var index = this.actions.indexOf(action);
  55353. if (index !== -1) {
  55354. this.actions.splice(index, 1);
  55355. ActionManager.Triggers[action.trigger] -= 1;
  55356. if (ActionManager.Triggers[action.trigger] === 0) {
  55357. delete ActionManager.Triggers[action.trigger];
  55358. }
  55359. delete action._actionManager;
  55360. return true;
  55361. }
  55362. return false;
  55363. };
  55364. /**
  55365. * Process a specific trigger
  55366. * @param trigger defines the trigger to process
  55367. * @param evt defines the event details to be processed
  55368. */
  55369. ActionManager.prototype.processTrigger = function (trigger, evt) {
  55370. for (var index = 0; index < this.actions.length; index++) {
  55371. var action = this.actions[index];
  55372. if (action.trigger === trigger) {
  55373. if (evt) {
  55374. if (trigger === ActionManager.OnKeyUpTrigger
  55375. || trigger === ActionManager.OnKeyDownTrigger) {
  55376. var parameter = action.getTriggerParameter();
  55377. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  55378. if (!parameter.toLowerCase) {
  55379. continue;
  55380. }
  55381. var lowerCase = parameter.toLowerCase();
  55382. if (lowerCase !== evt.sourceEvent.key) {
  55383. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  55384. var actualkey = String.fromCharCode(unicode).toLowerCase();
  55385. if (actualkey !== lowerCase) {
  55386. continue;
  55387. }
  55388. }
  55389. }
  55390. }
  55391. }
  55392. action._executeCurrent(evt);
  55393. }
  55394. }
  55395. };
  55396. /** @hidden */
  55397. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  55398. var properties = propertyPath.split(".");
  55399. for (var index = 0; index < properties.length - 1; index++) {
  55400. target = target[properties[index]];
  55401. }
  55402. return target;
  55403. };
  55404. /** @hidden */
  55405. ActionManager.prototype._getProperty = function (propertyPath) {
  55406. var properties = propertyPath.split(".");
  55407. return properties[properties.length - 1];
  55408. };
  55409. /**
  55410. * Serialize this manager to a JSON object
  55411. * @param name defines the property name to store this manager
  55412. * @returns a JSON representation of this manager
  55413. */
  55414. ActionManager.prototype.serialize = function (name) {
  55415. var root = {
  55416. children: new Array(),
  55417. name: name,
  55418. type: 3,
  55419. properties: new Array() // Empty for root but required
  55420. };
  55421. for (var i = 0; i < this.actions.length; i++) {
  55422. var triggerObject = {
  55423. type: 0,
  55424. children: new Array(),
  55425. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  55426. properties: new Array()
  55427. };
  55428. var triggerOptions = this.actions[i].triggerOptions;
  55429. if (triggerOptions && typeof triggerOptions !== "number") {
  55430. if (triggerOptions.parameter instanceof BABYLON.Node) {
  55431. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  55432. }
  55433. else {
  55434. var parameter = {};
  55435. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  55436. if (triggerOptions.parameter && triggerOptions.parameter.mesh) {
  55437. parameter._meshId = triggerOptions.parameter.mesh.id;
  55438. }
  55439. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  55440. }
  55441. }
  55442. // Serialize child action, recursively
  55443. this.actions[i].serialize(triggerObject);
  55444. // Add serialized trigger
  55445. root.children.push(triggerObject);
  55446. }
  55447. return root;
  55448. };
  55449. /**
  55450. * Creates a new ActionManager from a JSON data
  55451. * @param parsedActions defines the JSON data to read from
  55452. * @param object defines the hosting mesh
  55453. * @param scene defines the hosting scene
  55454. */
  55455. ActionManager.Parse = function (parsedActions, object, scene) {
  55456. var actionManager = new ActionManager(scene);
  55457. if (object === null)
  55458. scene.actionManager = actionManager;
  55459. else
  55460. object.actionManager = actionManager;
  55461. // instanciate a new object
  55462. var instanciate = function (name, params) {
  55463. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  55464. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  55465. newInstance.constructor.apply(newInstance, params);
  55466. return newInstance;
  55467. };
  55468. var parseParameter = function (name, value, target, propertyPath) {
  55469. if (propertyPath === null) {
  55470. // String, boolean or float
  55471. var floatValue = parseFloat(value);
  55472. if (value === "true" || value === "false")
  55473. return value === "true";
  55474. else
  55475. return isNaN(floatValue) ? value : floatValue;
  55476. }
  55477. var effectiveTarget = propertyPath.split(".");
  55478. var values = value.split(",");
  55479. // Get effective Target
  55480. for (var i = 0; i < effectiveTarget.length; i++) {
  55481. target = target[effectiveTarget[i]];
  55482. }
  55483. // Return appropriate value with its type
  55484. if (typeof (target) === "boolean")
  55485. return values[0] === "true";
  55486. if (typeof (target) === "string")
  55487. return values[0];
  55488. // Parameters with multiple values such as Vector3 etc.
  55489. var split = new Array();
  55490. for (var i = 0; i < values.length; i++)
  55491. split.push(parseFloat(values[i]));
  55492. if (target instanceof BABYLON.Vector3)
  55493. return BABYLON.Vector3.FromArray(split);
  55494. if (target instanceof BABYLON.Vector4)
  55495. return BABYLON.Vector4.FromArray(split);
  55496. if (target instanceof BABYLON.Color3)
  55497. return BABYLON.Color3.FromArray(split);
  55498. if (target instanceof BABYLON.Color4)
  55499. return BABYLON.Color4.FromArray(split);
  55500. return parseFloat(values[0]);
  55501. };
  55502. // traverse graph per trigger
  55503. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  55504. if (combineArray === void 0) { combineArray = null; }
  55505. if (parsedAction.detached)
  55506. return;
  55507. var parameters = new Array();
  55508. var target = null;
  55509. var propertyPath = null;
  55510. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  55511. // Parameters
  55512. if (parsedAction.type === 2)
  55513. parameters.push(actionManager);
  55514. else
  55515. parameters.push(trigger);
  55516. if (combine) {
  55517. var actions = new Array();
  55518. for (var j = 0; j < parsedAction.combine.length; j++) {
  55519. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  55520. }
  55521. parameters.push(actions);
  55522. }
  55523. else {
  55524. for (var i = 0; i < parsedAction.properties.length; i++) {
  55525. var value = parsedAction.properties[i].value;
  55526. var name = parsedAction.properties[i].name;
  55527. var targetType = parsedAction.properties[i].targetType;
  55528. if (name === "target")
  55529. if (targetType !== null && targetType === "SceneProperties")
  55530. value = target = scene;
  55531. else
  55532. value = target = scene.getNodeByName(value);
  55533. else if (name === "parent")
  55534. value = scene.getNodeByName(value);
  55535. else if (name === "sound") {
  55536. // Can not externalize to component, so only checks for the presence off the API.
  55537. if (scene.getSoundByName) {
  55538. value = scene.getSoundByName(value);
  55539. }
  55540. }
  55541. else if (name !== "propertyPath") {
  55542. if (parsedAction.type === 2 && name === "operator")
  55543. value = BABYLON.ValueCondition[value];
  55544. else
  55545. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  55546. }
  55547. else {
  55548. propertyPath = value;
  55549. }
  55550. parameters.push(value);
  55551. }
  55552. }
  55553. if (combineArray === null) {
  55554. parameters.push(condition);
  55555. }
  55556. else {
  55557. parameters.push(null);
  55558. }
  55559. // If interpolate value action
  55560. if (parsedAction.name === "InterpolateValueAction") {
  55561. var param = parameters[parameters.length - 2];
  55562. parameters[parameters.length - 1] = param;
  55563. parameters[parameters.length - 2] = condition;
  55564. }
  55565. // Action or condition(s) and not CombineAction
  55566. var newAction = instanciate(parsedAction.name, parameters);
  55567. if (newAction instanceof BABYLON.Condition && condition !== null) {
  55568. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  55569. if (action)
  55570. action.then(nothing);
  55571. else
  55572. actionManager.registerAction(nothing);
  55573. action = nothing;
  55574. }
  55575. if (combineArray === null) {
  55576. if (newAction instanceof BABYLON.Condition) {
  55577. condition = newAction;
  55578. newAction = action;
  55579. }
  55580. else {
  55581. condition = null;
  55582. if (action)
  55583. action.then(newAction);
  55584. else
  55585. actionManager.registerAction(newAction);
  55586. }
  55587. }
  55588. else {
  55589. combineArray.push(newAction);
  55590. }
  55591. for (var i = 0; i < parsedAction.children.length; i++)
  55592. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  55593. };
  55594. // triggers
  55595. for (var i = 0; i < parsedActions.children.length; i++) {
  55596. var triggerParams;
  55597. var trigger = parsedActions.children[i];
  55598. if (trigger.properties.length > 0) {
  55599. var param = trigger.properties[0].value;
  55600. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  55601. if (value._meshId) {
  55602. value.mesh = scene.getMeshByID(value._meshId);
  55603. }
  55604. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  55605. }
  55606. else
  55607. triggerParams = ActionManager[trigger.name];
  55608. for (var j = 0; j < trigger.children.length; j++) {
  55609. if (!trigger.detached)
  55610. traverse(trigger.children[j], triggerParams, null, null);
  55611. }
  55612. }
  55613. };
  55614. /**
  55615. * Get a trigger name by index
  55616. * @param trigger defines the trigger index
  55617. * @returns a trigger name
  55618. */
  55619. ActionManager.GetTriggerName = function (trigger) {
  55620. switch (trigger) {
  55621. case 0: return "NothingTrigger";
  55622. case 1: return "OnPickTrigger";
  55623. case 2: return "OnLeftPickTrigger";
  55624. case 3: return "OnRightPickTrigger";
  55625. case 4: return "OnCenterPickTrigger";
  55626. case 5: return "OnPickDownTrigger";
  55627. case 6: return "OnPickUpTrigger";
  55628. case 7: return "OnLongPressTrigger";
  55629. case 8: return "OnPointerOverTrigger";
  55630. case 9: return "OnPointerOutTrigger";
  55631. case 10: return "OnEveryFrameTrigger";
  55632. case 11: return "OnIntersectionEnterTrigger";
  55633. case 12: return "OnIntersectionExitTrigger";
  55634. case 13: return "OnKeyDownTrigger";
  55635. case 14: return "OnKeyUpTrigger";
  55636. case 15: return "OnPickOutTrigger";
  55637. default: return "";
  55638. }
  55639. };
  55640. /**
  55641. * Nothing
  55642. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55643. */
  55644. ActionManager.NothingTrigger = 0;
  55645. /**
  55646. * On pick
  55647. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55648. */
  55649. ActionManager.OnPickTrigger = 1;
  55650. /**
  55651. * On left pick
  55652. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55653. */
  55654. ActionManager.OnLeftPickTrigger = 2;
  55655. /**
  55656. * On right pick
  55657. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55658. */
  55659. ActionManager.OnRightPickTrigger = 3;
  55660. /**
  55661. * On center pick
  55662. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55663. */
  55664. ActionManager.OnCenterPickTrigger = 4;
  55665. /**
  55666. * On pick down
  55667. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55668. */
  55669. ActionManager.OnPickDownTrigger = 5;
  55670. /**
  55671. * On double pick
  55672. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55673. */
  55674. ActionManager.OnDoublePickTrigger = 6;
  55675. /**
  55676. * On pick up
  55677. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55678. */
  55679. ActionManager.OnPickUpTrigger = 7;
  55680. /**
  55681. * On pick out.
  55682. * This trigger will only be raised if you also declared a OnPickDown
  55683. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55684. */
  55685. ActionManager.OnPickOutTrigger = 16;
  55686. /**
  55687. * On long press
  55688. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55689. */
  55690. ActionManager.OnLongPressTrigger = 8;
  55691. /**
  55692. * On pointer over
  55693. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55694. */
  55695. ActionManager.OnPointerOverTrigger = 9;
  55696. /**
  55697. * On pointer out
  55698. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55699. */
  55700. ActionManager.OnPointerOutTrigger = 10;
  55701. /**
  55702. * On every frame
  55703. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55704. */
  55705. ActionManager.OnEveryFrameTrigger = 11;
  55706. /**
  55707. * On intersection enter
  55708. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55709. */
  55710. ActionManager.OnIntersectionEnterTrigger = 12;
  55711. /**
  55712. * On intersection exit
  55713. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55714. */
  55715. ActionManager.OnIntersectionExitTrigger = 13;
  55716. /**
  55717. * On key down
  55718. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55719. */
  55720. ActionManager.OnKeyDownTrigger = 14;
  55721. /**
  55722. * On key up
  55723. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  55724. */
  55725. ActionManager.OnKeyUpTrigger = 15;
  55726. /** Gets the list of active triggers */
  55727. ActionManager.Triggers = {};
  55728. return ActionManager;
  55729. }());
  55730. BABYLON.ActionManager = ActionManager;
  55731. })(BABYLON || (BABYLON = {}));
  55732. //# sourceMappingURL=babylon.actionManager.js.map
  55733. var BABYLON;
  55734. (function (BABYLON) {
  55735. /**
  55736. * This defines an action responsible to change the value of a property
  55737. * by interpolating between its current value and the newly set one once triggered.
  55738. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55739. */
  55740. var InterpolateValueAction = /** @class */ (function (_super) {
  55741. __extends(InterpolateValueAction, _super);
  55742. /**
  55743. * Instantiate the action
  55744. * @param triggerOptions defines the trigger options
  55745. * @param target defines the object containing the value to interpolate
  55746. * @param propertyPath defines the path to the property in the target object
  55747. * @param value defines the target value at the end of the interpolation
  55748. * @param duration deines the time it will take for the property to interpolate to the value.
  55749. * @param condition defines the trigger related conditions
  55750. * @param stopOtherAnimations defines if the other scene animations should be stopped when the action has been triggered
  55751. * @param onInterpolationDone defines a callback raised once the interpolation animation has been done
  55752. */
  55753. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  55754. if (duration === void 0) { duration = 1000; }
  55755. var _this = _super.call(this, triggerOptions, condition) || this;
  55756. /**
  55757. * Defines the time it will take for the property to interpolate to the value.
  55758. */
  55759. _this.duration = 1000;
  55760. /**
  55761. * Observable triggered once the interpolation animation has been done.
  55762. */
  55763. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  55764. _this.propertyPath = propertyPath;
  55765. _this.value = value;
  55766. _this.duration = duration;
  55767. _this.stopOtherAnimations = stopOtherAnimations;
  55768. _this.onInterpolationDone = onInterpolationDone;
  55769. _this._target = _this._effectiveTarget = target;
  55770. return _this;
  55771. }
  55772. /** @hidden */
  55773. InterpolateValueAction.prototype._prepare = function () {
  55774. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55775. this._property = this._getProperty(this.propertyPath);
  55776. };
  55777. /**
  55778. * Execute the action starts the value interpolation.
  55779. */
  55780. InterpolateValueAction.prototype.execute = function () {
  55781. var _this = this;
  55782. var scene = this._actionManager.getScene();
  55783. var keys = [
  55784. {
  55785. frame: 0,
  55786. value: this._effectiveTarget[this._property]
  55787. }, {
  55788. frame: 100,
  55789. value: this.value
  55790. }
  55791. ];
  55792. var dataType;
  55793. if (typeof this.value === "number") {
  55794. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  55795. }
  55796. else if (this.value instanceof BABYLON.Color3) {
  55797. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  55798. }
  55799. else if (this.value instanceof BABYLON.Vector3) {
  55800. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  55801. }
  55802. else if (this.value instanceof BABYLON.Matrix) {
  55803. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  55804. }
  55805. else if (this.value instanceof BABYLON.Quaternion) {
  55806. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  55807. }
  55808. else {
  55809. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  55810. return;
  55811. }
  55812. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  55813. animation.setKeys(keys);
  55814. if (this.stopOtherAnimations) {
  55815. scene.stopAnimation(this._effectiveTarget);
  55816. }
  55817. var wrapper = function () {
  55818. _this.onInterpolationDoneObservable.notifyObservers(_this);
  55819. if (_this.onInterpolationDone) {
  55820. _this.onInterpolationDone();
  55821. }
  55822. };
  55823. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  55824. };
  55825. /**
  55826. * Serializes the actions and its related information.
  55827. * @param parent defines the object to serialize in
  55828. * @returns the serialized object
  55829. */
  55830. InterpolateValueAction.prototype.serialize = function (parent) {
  55831. return _super.prototype._serialize.call(this, {
  55832. name: "InterpolateValueAction",
  55833. properties: [
  55834. BABYLON.Action._GetTargetProperty(this._target),
  55835. { name: "propertyPath", value: this.propertyPath },
  55836. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  55837. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  55838. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  55839. ]
  55840. }, parent);
  55841. };
  55842. return InterpolateValueAction;
  55843. }(BABYLON.Action));
  55844. BABYLON.InterpolateValueAction = InterpolateValueAction;
  55845. })(BABYLON || (BABYLON = {}));
  55846. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  55847. var BABYLON;
  55848. (function (BABYLON) {
  55849. /**
  55850. * This defines an action responsible to toggle a boolean once triggered.
  55851. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55852. */
  55853. var SwitchBooleanAction = /** @class */ (function (_super) {
  55854. __extends(SwitchBooleanAction, _super);
  55855. /**
  55856. * Instantiate the action
  55857. * @param triggerOptions defines the trigger options
  55858. * @param target defines the object containing the boolean
  55859. * @param propertyPath defines the path to the boolean property in the target object
  55860. * @param condition defines the trigger related conditions
  55861. */
  55862. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  55863. var _this = _super.call(this, triggerOptions, condition) || this;
  55864. _this.propertyPath = propertyPath;
  55865. _this._target = _this._effectiveTarget = target;
  55866. return _this;
  55867. }
  55868. /** @hidden */
  55869. SwitchBooleanAction.prototype._prepare = function () {
  55870. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55871. this._property = this._getProperty(this.propertyPath);
  55872. };
  55873. /**
  55874. * Execute the action toggle the boolean value.
  55875. */
  55876. SwitchBooleanAction.prototype.execute = function () {
  55877. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  55878. };
  55879. /**
  55880. * Serializes the actions and its related information.
  55881. * @param parent defines the object to serialize in
  55882. * @returns the serialized object
  55883. */
  55884. SwitchBooleanAction.prototype.serialize = function (parent) {
  55885. return _super.prototype._serialize.call(this, {
  55886. name: "SwitchBooleanAction",
  55887. properties: [
  55888. BABYLON.Action._GetTargetProperty(this._target),
  55889. { name: "propertyPath", value: this.propertyPath }
  55890. ]
  55891. }, parent);
  55892. };
  55893. return SwitchBooleanAction;
  55894. }(BABYLON.Action));
  55895. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  55896. /**
  55897. * This defines an action responsible to set a the state field of the target
  55898. * to a desired value once triggered.
  55899. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55900. */
  55901. var SetStateAction = /** @class */ (function (_super) {
  55902. __extends(SetStateAction, _super);
  55903. /**
  55904. * Instantiate the action
  55905. * @param triggerOptions defines the trigger options
  55906. * @param target defines the object containing the state property
  55907. * @param value defines the value to store in the state field
  55908. * @param condition defines the trigger related conditions
  55909. */
  55910. function SetStateAction(triggerOptions, target, value, condition) {
  55911. var _this = _super.call(this, triggerOptions, condition) || this;
  55912. _this.value = value;
  55913. _this._target = target;
  55914. return _this;
  55915. }
  55916. /**
  55917. * Execute the action and store the value on the target state property.
  55918. */
  55919. SetStateAction.prototype.execute = function () {
  55920. this._target.state = this.value;
  55921. };
  55922. /**
  55923. * Serializes the actions and its related information.
  55924. * @param parent defines the object to serialize in
  55925. * @returns the serialized object
  55926. */
  55927. SetStateAction.prototype.serialize = function (parent) {
  55928. return _super.prototype._serialize.call(this, {
  55929. name: "SetStateAction",
  55930. properties: [
  55931. BABYLON.Action._GetTargetProperty(this._target),
  55932. { name: "value", value: this.value }
  55933. ]
  55934. }, parent);
  55935. };
  55936. return SetStateAction;
  55937. }(BABYLON.Action));
  55938. BABYLON.SetStateAction = SetStateAction;
  55939. /**
  55940. * This defines an action responsible to set a property of the target
  55941. * to a desired value once triggered.
  55942. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55943. */
  55944. var SetValueAction = /** @class */ (function (_super) {
  55945. __extends(SetValueAction, _super);
  55946. /**
  55947. * Instantiate the action
  55948. * @param triggerOptions defines the trigger options
  55949. * @param target defines the object containing the property
  55950. * @param propertyPath defines the path of the property to set in the target
  55951. * @param value defines the value to set in the property
  55952. * @param condition defines the trigger related conditions
  55953. */
  55954. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  55955. var _this = _super.call(this, triggerOptions, condition) || this;
  55956. _this.propertyPath = propertyPath;
  55957. _this.value = value;
  55958. _this._target = _this._effectiveTarget = target;
  55959. return _this;
  55960. }
  55961. /** @hidden */
  55962. SetValueAction.prototype._prepare = function () {
  55963. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  55964. this._property = this._getProperty(this.propertyPath);
  55965. };
  55966. /**
  55967. * Execute the action and set the targetted property to the desired value.
  55968. */
  55969. SetValueAction.prototype.execute = function () {
  55970. this._effectiveTarget[this._property] = this.value;
  55971. if (this._target.markAsDirty) {
  55972. this._target.markAsDirty(this._property);
  55973. }
  55974. };
  55975. /**
  55976. * Serializes the actions and its related information.
  55977. * @param parent defines the object to serialize in
  55978. * @returns the serialized object
  55979. */
  55980. SetValueAction.prototype.serialize = function (parent) {
  55981. return _super.prototype._serialize.call(this, {
  55982. name: "SetValueAction",
  55983. properties: [
  55984. BABYLON.Action._GetTargetProperty(this._target),
  55985. { name: "propertyPath", value: this.propertyPath },
  55986. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  55987. ]
  55988. }, parent);
  55989. };
  55990. return SetValueAction;
  55991. }(BABYLON.Action));
  55992. BABYLON.SetValueAction = SetValueAction;
  55993. /**
  55994. * This defines an action responsible to increment the target value
  55995. * to a desired value once triggered.
  55996. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  55997. */
  55998. var IncrementValueAction = /** @class */ (function (_super) {
  55999. __extends(IncrementValueAction, _super);
  56000. /**
  56001. * Instantiate the action
  56002. * @param triggerOptions defines the trigger options
  56003. * @param target defines the object containing the property
  56004. * @param propertyPath defines the path of the property to increment in the target
  56005. * @param value defines the value value we should increment the property by
  56006. * @param condition defines the trigger related conditions
  56007. */
  56008. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  56009. var _this = _super.call(this, triggerOptions, condition) || this;
  56010. _this.propertyPath = propertyPath;
  56011. _this.value = value;
  56012. _this._target = _this._effectiveTarget = target;
  56013. return _this;
  56014. }
  56015. /** @hidden */
  56016. IncrementValueAction.prototype._prepare = function () {
  56017. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  56018. this._property = this._getProperty(this.propertyPath);
  56019. if (typeof this._effectiveTarget[this._property] !== "number") {
  56020. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  56021. }
  56022. };
  56023. /**
  56024. * Execute the action and increment the target of the value amount.
  56025. */
  56026. IncrementValueAction.prototype.execute = function () {
  56027. this._effectiveTarget[this._property] += this.value;
  56028. if (this._target.markAsDirty) {
  56029. this._target.markAsDirty(this._property);
  56030. }
  56031. };
  56032. /**
  56033. * Serializes the actions and its related information.
  56034. * @param parent defines the object to serialize in
  56035. * @returns the serialized object
  56036. */
  56037. IncrementValueAction.prototype.serialize = function (parent) {
  56038. return _super.prototype._serialize.call(this, {
  56039. name: "IncrementValueAction",
  56040. properties: [
  56041. BABYLON.Action._GetTargetProperty(this._target),
  56042. { name: "propertyPath", value: this.propertyPath },
  56043. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  56044. ]
  56045. }, parent);
  56046. };
  56047. return IncrementValueAction;
  56048. }(BABYLON.Action));
  56049. BABYLON.IncrementValueAction = IncrementValueAction;
  56050. /**
  56051. * This defines an action responsible to start an animation once triggered.
  56052. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56053. */
  56054. var PlayAnimationAction = /** @class */ (function (_super) {
  56055. __extends(PlayAnimationAction, _super);
  56056. /**
  56057. * Instantiate the action
  56058. * @param triggerOptions defines the trigger options
  56059. * @param target defines the target animation or animation name
  56060. * @param from defines from where the animation should start (animation frame)
  56061. * @param end defines where the animation should stop (animation frame)
  56062. * @param loop defines if the animation should loop or stop after the first play
  56063. * @param condition defines the trigger related conditions
  56064. */
  56065. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  56066. var _this = _super.call(this, triggerOptions, condition) || this;
  56067. _this.from = from;
  56068. _this.to = to;
  56069. _this.loop = loop;
  56070. _this._target = target;
  56071. return _this;
  56072. }
  56073. /** @hidden */
  56074. PlayAnimationAction.prototype._prepare = function () {
  56075. };
  56076. /**
  56077. * Execute the action and play the animation.
  56078. */
  56079. PlayAnimationAction.prototype.execute = function () {
  56080. var scene = this._actionManager.getScene();
  56081. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  56082. };
  56083. /**
  56084. * Serializes the actions and its related information.
  56085. * @param parent defines the object to serialize in
  56086. * @returns the serialized object
  56087. */
  56088. PlayAnimationAction.prototype.serialize = function (parent) {
  56089. return _super.prototype._serialize.call(this, {
  56090. name: "PlayAnimationAction",
  56091. properties: [
  56092. BABYLON.Action._GetTargetProperty(this._target),
  56093. { name: "from", value: String(this.from) },
  56094. { name: "to", value: String(this.to) },
  56095. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  56096. ]
  56097. }, parent);
  56098. };
  56099. return PlayAnimationAction;
  56100. }(BABYLON.Action));
  56101. BABYLON.PlayAnimationAction = PlayAnimationAction;
  56102. /**
  56103. * This defines an action responsible to stop an animation once triggered.
  56104. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56105. */
  56106. var StopAnimationAction = /** @class */ (function (_super) {
  56107. __extends(StopAnimationAction, _super);
  56108. /**
  56109. * Instantiate the action
  56110. * @param triggerOptions defines the trigger options
  56111. * @param target defines the target animation or animation name
  56112. * @param condition defines the trigger related conditions
  56113. */
  56114. function StopAnimationAction(triggerOptions, target, condition) {
  56115. var _this = _super.call(this, triggerOptions, condition) || this;
  56116. _this._target = target;
  56117. return _this;
  56118. }
  56119. /** @hidden */
  56120. StopAnimationAction.prototype._prepare = function () {
  56121. };
  56122. /**
  56123. * Execute the action and stop the animation.
  56124. */
  56125. StopAnimationAction.prototype.execute = function () {
  56126. var scene = this._actionManager.getScene();
  56127. scene.stopAnimation(this._target);
  56128. };
  56129. /**
  56130. * Serializes the actions and its related information.
  56131. * @param parent defines the object to serialize in
  56132. * @returns the serialized object
  56133. */
  56134. StopAnimationAction.prototype.serialize = function (parent) {
  56135. return _super.prototype._serialize.call(this, {
  56136. name: "StopAnimationAction",
  56137. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  56138. }, parent);
  56139. };
  56140. return StopAnimationAction;
  56141. }(BABYLON.Action));
  56142. BABYLON.StopAnimationAction = StopAnimationAction;
  56143. /**
  56144. * This defines an action responsible that does nothing once triggered.
  56145. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56146. */
  56147. var DoNothingAction = /** @class */ (function (_super) {
  56148. __extends(DoNothingAction, _super);
  56149. /**
  56150. * Instantiate the action
  56151. * @param triggerOptions defines the trigger options
  56152. * @param condition defines the trigger related conditions
  56153. */
  56154. function DoNothingAction(triggerOptions, condition) {
  56155. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  56156. return _super.call(this, triggerOptions, condition) || this;
  56157. }
  56158. /**
  56159. * Execute the action and do nothing.
  56160. */
  56161. DoNothingAction.prototype.execute = function () {
  56162. };
  56163. /**
  56164. * Serializes the actions and its related information.
  56165. * @param parent defines the object to serialize in
  56166. * @returns the serialized object
  56167. */
  56168. DoNothingAction.prototype.serialize = function (parent) {
  56169. return _super.prototype._serialize.call(this, {
  56170. name: "DoNothingAction",
  56171. properties: []
  56172. }, parent);
  56173. };
  56174. return DoNothingAction;
  56175. }(BABYLON.Action));
  56176. BABYLON.DoNothingAction = DoNothingAction;
  56177. /**
  56178. * This defines an action responsible to trigger several actions once triggered.
  56179. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56180. */
  56181. var CombineAction = /** @class */ (function (_super) {
  56182. __extends(CombineAction, _super);
  56183. /**
  56184. * Instantiate the action
  56185. * @param triggerOptions defines the trigger options
  56186. * @param children defines the list of aggregated animations to run
  56187. * @param condition defines the trigger related conditions
  56188. */
  56189. function CombineAction(triggerOptions, children, condition) {
  56190. var _this = _super.call(this, triggerOptions, condition) || this;
  56191. _this.children = children;
  56192. return _this;
  56193. }
  56194. /** @hidden */
  56195. CombineAction.prototype._prepare = function () {
  56196. for (var index = 0; index < this.children.length; index++) {
  56197. this.children[index]._actionManager = this._actionManager;
  56198. this.children[index]._prepare();
  56199. }
  56200. };
  56201. /**
  56202. * Execute the action and executes all the aggregated actions.
  56203. */
  56204. CombineAction.prototype.execute = function (evt) {
  56205. for (var index = 0; index < this.children.length; index++) {
  56206. this.children[index].execute(evt);
  56207. }
  56208. };
  56209. /**
  56210. * Serializes the actions and its related information.
  56211. * @param parent defines the object to serialize in
  56212. * @returns the serialized object
  56213. */
  56214. CombineAction.prototype.serialize = function (parent) {
  56215. var serializationObject = _super.prototype._serialize.call(this, {
  56216. name: "CombineAction",
  56217. properties: [],
  56218. combine: []
  56219. }, parent);
  56220. for (var i = 0; i < this.children.length; i++) {
  56221. serializationObject.combine.push(this.children[i].serialize(null));
  56222. }
  56223. return serializationObject;
  56224. };
  56225. return CombineAction;
  56226. }(BABYLON.Action));
  56227. BABYLON.CombineAction = CombineAction;
  56228. /**
  56229. * This defines an action responsible to run code (external event) once triggered.
  56230. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56231. */
  56232. var ExecuteCodeAction = /** @class */ (function (_super) {
  56233. __extends(ExecuteCodeAction, _super);
  56234. /**
  56235. * Instantiate the action
  56236. * @param triggerOptions defines the trigger options
  56237. * @param func defines the callback function to run
  56238. * @param condition defines the trigger related conditions
  56239. */
  56240. function ExecuteCodeAction(triggerOptions, func, condition) {
  56241. var _this = _super.call(this, triggerOptions, condition) || this;
  56242. _this.func = func;
  56243. return _this;
  56244. }
  56245. /**
  56246. * Execute the action and run the attached code.
  56247. */
  56248. ExecuteCodeAction.prototype.execute = function (evt) {
  56249. this.func(evt);
  56250. };
  56251. return ExecuteCodeAction;
  56252. }(BABYLON.Action));
  56253. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  56254. /**
  56255. * This defines an action responsible to set the parent property of the target once triggered.
  56256. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  56257. */
  56258. var SetParentAction = /** @class */ (function (_super) {
  56259. __extends(SetParentAction, _super);
  56260. /**
  56261. * Instantiate the action
  56262. * @param triggerOptions defines the trigger options
  56263. * @param target defines the target containing the parent property
  56264. * @param parent defines from where the animation should start (animation frame)
  56265. * @param condition defines the trigger related conditions
  56266. */
  56267. function SetParentAction(triggerOptions, target, parent, condition) {
  56268. var _this = _super.call(this, triggerOptions, condition) || this;
  56269. _this._target = target;
  56270. _this._parent = parent;
  56271. return _this;
  56272. }
  56273. /** @hidden */
  56274. SetParentAction.prototype._prepare = function () {
  56275. };
  56276. /**
  56277. * Execute the action and set the parent property.
  56278. */
  56279. SetParentAction.prototype.execute = function () {
  56280. if (this._target.parent === this._parent) {
  56281. return;
  56282. }
  56283. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  56284. invertParentWorldMatrix.invert();
  56285. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  56286. this._target.parent = this._parent;
  56287. };
  56288. /**
  56289. * Serializes the actions and its related information.
  56290. * @param parent defines the object to serialize in
  56291. * @returns the serialized object
  56292. */
  56293. SetParentAction.prototype.serialize = function (parent) {
  56294. return _super.prototype._serialize.call(this, {
  56295. name: "SetParentAction",
  56296. properties: [
  56297. BABYLON.Action._GetTargetProperty(this._target),
  56298. BABYLON.Action._GetTargetProperty(this._parent),
  56299. ]
  56300. }, parent);
  56301. };
  56302. return SetParentAction;
  56303. }(BABYLON.Action));
  56304. BABYLON.SetParentAction = SetParentAction;
  56305. })(BABYLON || (BABYLON = {}));
  56306. //# sourceMappingURL=babylon.directActions.js.map
  56307. var BABYLON;
  56308. (function (BABYLON) {
  56309. /**
  56310. * Class used to manage multiple sprites on the same spritesheet
  56311. * @see http://doc.babylonjs.com/babylon101/sprites
  56312. */
  56313. var SpriteManager = /** @class */ (function () {
  56314. /**
  56315. * Creates a new sprite manager
  56316. * @param name defines the manager's name
  56317. * @param imgUrl defines the sprite sheet url
  56318. * @param capacity defines the maximum allowed number of sprites
  56319. * @param cellSize defines the size of a sprite cell
  56320. * @param scene defines the hosting scene
  56321. * @param epsilon defines the epsilon value to align texture (0.01 by default)
  56322. * @param samplingMode defines the smapling mode to use with spritesheet
  56323. */
  56324. function SpriteManager(
  56325. /** defines the manager's name */
  56326. name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  56327. if (epsilon === void 0) { epsilon = 0.01; }
  56328. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  56329. this.name = name;
  56330. /** Gets the list of sprites */
  56331. this.sprites = new Array();
  56332. /** Gets or sets the rendering group id (0 by default) */
  56333. this.renderingGroupId = 0;
  56334. /** Gets or sets camera layer mask */
  56335. this.layerMask = 0x0FFFFFFF;
  56336. /** Gets or sets a boolean indicating if the manager must consider scene fog when rendering */
  56337. this.fogEnabled = true;
  56338. /** Gets or sets a boolean indicating if the sprites are pickable */
  56339. this.isPickable = false;
  56340. /**
  56341. * An event triggered when the manager is disposed.
  56342. */
  56343. this.onDisposeObservable = new BABYLON.Observable();
  56344. this._vertexBuffers = {};
  56345. if (!scene._getComponent(BABYLON.SceneComponentConstants.NAME_SPRITE)) {
  56346. scene._addComponent(new BABYLON.SpriteSceneComponent(scene));
  56347. }
  56348. this._capacity = capacity;
  56349. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  56350. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56351. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  56352. if (cellSize.width && cellSize.height) {
  56353. this.cellWidth = cellSize.width;
  56354. this.cellHeight = cellSize.height;
  56355. }
  56356. else if (cellSize !== undefined) {
  56357. this.cellWidth = cellSize;
  56358. this.cellHeight = cellSize;
  56359. }
  56360. else {
  56361. return;
  56362. }
  56363. this._epsilon = epsilon;
  56364. this._scene = scene;
  56365. this._scene.spriteManagers.push(this);
  56366. var indices = [];
  56367. var index = 0;
  56368. for (var count = 0; count < capacity; count++) {
  56369. indices.push(index);
  56370. indices.push(index + 1);
  56371. indices.push(index + 2);
  56372. indices.push(index);
  56373. indices.push(index + 2);
  56374. indices.push(index + 3);
  56375. index += 4;
  56376. }
  56377. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  56378. // VBO
  56379. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  56380. this._vertexData = new Float32Array(capacity * 16 * 4);
  56381. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  56382. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  56383. var options = this._buffer.createVertexBuffer("options", 4, 4);
  56384. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  56385. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  56386. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56387. this._vertexBuffers["options"] = options;
  56388. this._vertexBuffers["cellInfo"] = cellInfo;
  56389. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56390. // Effects
  56391. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  56392. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  56393. }
  56394. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  56395. /**
  56396. * Callback called when the manager is disposed
  56397. */
  56398. set: function (callback) {
  56399. if (this._onDisposeObserver) {
  56400. this.onDisposeObservable.remove(this._onDisposeObserver);
  56401. }
  56402. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56403. },
  56404. enumerable: true,
  56405. configurable: true
  56406. });
  56407. Object.defineProperty(SpriteManager.prototype, "texture", {
  56408. /**
  56409. * Gets or sets the spritesheet texture
  56410. */
  56411. get: function () {
  56412. return this._spriteTexture;
  56413. },
  56414. set: function (value) {
  56415. this._spriteTexture = value;
  56416. },
  56417. enumerable: true,
  56418. configurable: true
  56419. });
  56420. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  56421. var arrayOffset = index * 16;
  56422. if (offsetX === 0)
  56423. offsetX = this._epsilon;
  56424. else if (offsetX === 1)
  56425. offsetX = 1 - this._epsilon;
  56426. if (offsetY === 0)
  56427. offsetY = this._epsilon;
  56428. else if (offsetY === 1)
  56429. offsetY = 1 - this._epsilon;
  56430. this._vertexData[arrayOffset] = sprite.position.x;
  56431. this._vertexData[arrayOffset + 1] = sprite.position.y;
  56432. this._vertexData[arrayOffset + 2] = sprite.position.z;
  56433. this._vertexData[arrayOffset + 3] = sprite.angle;
  56434. this._vertexData[arrayOffset + 4] = sprite.width;
  56435. this._vertexData[arrayOffset + 5] = sprite.height;
  56436. this._vertexData[arrayOffset + 6] = offsetX;
  56437. this._vertexData[arrayOffset + 7] = offsetY;
  56438. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  56439. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  56440. var offset = (sprite.cellIndex / rowSize) >> 0;
  56441. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  56442. this._vertexData[arrayOffset + 11] = offset;
  56443. // Color
  56444. this._vertexData[arrayOffset + 12] = sprite.color.r;
  56445. this._vertexData[arrayOffset + 13] = sprite.color.g;
  56446. this._vertexData[arrayOffset + 14] = sprite.color.b;
  56447. this._vertexData[arrayOffset + 15] = sprite.color.a;
  56448. };
  56449. /**
  56450. * Intersects the sprites with a ray
  56451. * @param ray defines the ray to intersect with
  56452. * @param camera defines the current active camera
  56453. * @param predicate defines a predicate used to select candidate sprites
  56454. * @param fastCheck defines if a fast check only must be done (the first potential sprite is will be used and not the closer)
  56455. * @returns null if no hit or a PickingInfo
  56456. */
  56457. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  56458. var count = Math.min(this._capacity, this.sprites.length);
  56459. var min = BABYLON.Vector3.Zero();
  56460. var max = BABYLON.Vector3.Zero();
  56461. var distance = Number.MAX_VALUE;
  56462. var currentSprite = null;
  56463. var cameraSpacePosition = BABYLON.Vector3.Zero();
  56464. var cameraView = camera.getViewMatrix();
  56465. for (var index = 0; index < count; index++) {
  56466. var sprite = this.sprites[index];
  56467. if (!sprite) {
  56468. continue;
  56469. }
  56470. if (predicate) {
  56471. if (!predicate(sprite)) {
  56472. continue;
  56473. }
  56474. }
  56475. else if (!sprite.isPickable) {
  56476. continue;
  56477. }
  56478. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  56479. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  56480. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  56481. if (ray.intersectsBoxMinMax(min, max)) {
  56482. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  56483. if (distance > currentDistance) {
  56484. distance = currentDistance;
  56485. currentSprite = sprite;
  56486. if (fastCheck) {
  56487. break;
  56488. }
  56489. }
  56490. }
  56491. }
  56492. if (currentSprite) {
  56493. var result = new BABYLON.PickingInfo();
  56494. result.hit = true;
  56495. result.pickedSprite = currentSprite;
  56496. result.distance = distance;
  56497. return result;
  56498. }
  56499. return null;
  56500. };
  56501. /**
  56502. * Render all child sprites
  56503. */
  56504. SpriteManager.prototype.render = function () {
  56505. // Check
  56506. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  56507. return;
  56508. var engine = this._scene.getEngine();
  56509. var baseSize = this._spriteTexture.getBaseSize();
  56510. // Sprites
  56511. var deltaTime = engine.getDeltaTime();
  56512. var max = Math.min(this._capacity, this.sprites.length);
  56513. var rowSize = baseSize.width / this.cellWidth;
  56514. var offset = 0;
  56515. for (var index = 0; index < max; index++) {
  56516. var sprite = this.sprites[index];
  56517. if (!sprite || !sprite.isVisible) {
  56518. continue;
  56519. }
  56520. sprite._animate(deltaTime);
  56521. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  56522. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  56523. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  56524. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  56525. }
  56526. this._buffer.update(this._vertexData);
  56527. // Render
  56528. var effect = this._effectBase;
  56529. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56530. effect = this._effectFog;
  56531. }
  56532. engine.enableEffect(effect);
  56533. var viewMatrix = this._scene.getViewMatrix();
  56534. effect.setTexture("diffuseSampler", this._spriteTexture);
  56535. effect.setMatrix("view", viewMatrix);
  56536. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56537. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  56538. // Fog
  56539. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  56540. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  56541. effect.setColor3("vFogColor", this._scene.fogColor);
  56542. }
  56543. // VBOs
  56544. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56545. // Draw order
  56546. engine.setDepthFunctionToLessOrEqual();
  56547. effect.setBool("alphaTest", true);
  56548. engine.setColorWrite(false);
  56549. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56550. engine.setColorWrite(true);
  56551. effect.setBool("alphaTest", false);
  56552. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56553. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  56554. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56555. };
  56556. /**
  56557. * Release associated resources
  56558. */
  56559. SpriteManager.prototype.dispose = function () {
  56560. if (this._buffer) {
  56561. this._buffer.dispose();
  56562. this._buffer = null;
  56563. }
  56564. if (this._indexBuffer) {
  56565. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56566. this._indexBuffer = null;
  56567. }
  56568. if (this._spriteTexture) {
  56569. this._spriteTexture.dispose();
  56570. this._spriteTexture = null;
  56571. }
  56572. // Remove from scene
  56573. var index = this._scene.spriteManagers.indexOf(this);
  56574. this._scene.spriteManagers.splice(index, 1);
  56575. // Callback
  56576. this.onDisposeObservable.notifyObservers(this);
  56577. this.onDisposeObservable.clear();
  56578. };
  56579. return SpriteManager;
  56580. }());
  56581. BABYLON.SpriteManager = SpriteManager;
  56582. })(BABYLON || (BABYLON = {}));
  56583. //# sourceMappingURL=babylon.spriteManager.js.map
  56584. var BABYLON;
  56585. (function (BABYLON) {
  56586. /**
  56587. * Class used to represent a sprite
  56588. * @see http://doc.babylonjs.com/babylon101/sprites
  56589. */
  56590. var Sprite = /** @class */ (function () {
  56591. /**
  56592. * Creates a new Sprite
  56593. * @param name defines the name
  56594. * @param manager defines the manager
  56595. */
  56596. function Sprite(
  56597. /** defines the name */
  56598. name, manager) {
  56599. this.name = name;
  56600. /** Gets or sets the main color */
  56601. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  56602. /** Gets or sets the width */
  56603. this.width = 1.0;
  56604. /** Gets or sets the height */
  56605. this.height = 1.0;
  56606. /** Gets or sets rotation angle */
  56607. this.angle = 0;
  56608. /** Gets or sets the cell index in the sprite sheet */
  56609. this.cellIndex = 0;
  56610. /** Gets or sets a boolean indicating if UV coordinates should be inverted in U axis */
  56611. this.invertU = 0;
  56612. /** Gets or sets a boolean indicating if UV coordinates should be inverted in B axis */
  56613. this.invertV = 0;
  56614. /** Gets the list of attached animations */
  56615. this.animations = new Array();
  56616. /** Gets or sets a boolean indicating if the sprite can be picked */
  56617. this.isPickable = false;
  56618. this._animationStarted = false;
  56619. this._loopAnimation = false;
  56620. this._fromIndex = 0;
  56621. this._toIndex = 0;
  56622. this._delay = 0;
  56623. this._direction = 1;
  56624. this._time = 0;
  56625. /**
  56626. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  56627. */
  56628. this.isVisible = true;
  56629. this._manager = manager;
  56630. this._manager.sprites.push(this);
  56631. this.position = BABYLON.Vector3.Zero();
  56632. }
  56633. Object.defineProperty(Sprite.prototype, "size", {
  56634. /**
  56635. * Gets or sets the sprite size
  56636. */
  56637. get: function () {
  56638. return this.width;
  56639. },
  56640. set: function (value) {
  56641. this.width = value;
  56642. this.height = value;
  56643. },
  56644. enumerable: true,
  56645. configurable: true
  56646. });
  56647. /**
  56648. * Starts an animation
  56649. * @param from defines the initial key
  56650. * @param to defines the end key
  56651. * @param loop defines if the animation must loop
  56652. * @param delay defines the start delay (in ms)
  56653. * @param onAnimationEnd defines a callback to call when animation ends
  56654. */
  56655. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  56656. this._fromIndex = from;
  56657. this._toIndex = to;
  56658. this._loopAnimation = loop;
  56659. this._delay = delay;
  56660. this._animationStarted = true;
  56661. this._direction = from < to ? 1 : -1;
  56662. this.cellIndex = from;
  56663. this._time = 0;
  56664. this._onAnimationEnd = onAnimationEnd;
  56665. };
  56666. /** Stops current animation (if any) */
  56667. Sprite.prototype.stopAnimation = function () {
  56668. this._animationStarted = false;
  56669. };
  56670. /** @hidden */
  56671. Sprite.prototype._animate = function (deltaTime) {
  56672. if (!this._animationStarted)
  56673. return;
  56674. this._time += deltaTime;
  56675. if (this._time > this._delay) {
  56676. this._time = this._time % this._delay;
  56677. this.cellIndex += this._direction;
  56678. if (this.cellIndex > this._toIndex) {
  56679. if (this._loopAnimation) {
  56680. this.cellIndex = this._fromIndex;
  56681. }
  56682. else {
  56683. this.cellIndex = this._toIndex;
  56684. this._animationStarted = false;
  56685. if (this._onAnimationEnd) {
  56686. this._onAnimationEnd();
  56687. }
  56688. if (this.disposeWhenFinishedAnimating) {
  56689. this.dispose();
  56690. }
  56691. }
  56692. }
  56693. }
  56694. };
  56695. /** Release associated resources */
  56696. Sprite.prototype.dispose = function () {
  56697. for (var i = 0; i < this._manager.sprites.length; i++) {
  56698. if (this._manager.sprites[i] == this) {
  56699. this._manager.sprites.splice(i, 1);
  56700. }
  56701. }
  56702. };
  56703. return Sprite;
  56704. }());
  56705. BABYLON.Sprite = Sprite;
  56706. })(BABYLON || (BABYLON = {}));
  56707. //# sourceMappingURL=babylon.sprite.js.map
  56708. var BABYLON;
  56709. (function (BABYLON) {
  56710. BABYLON.Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  56711. if (!BABYLON.PickingInfo) {
  56712. return null;
  56713. }
  56714. var pickingInfo = null;
  56715. if (!camera) {
  56716. if (!this.activeCamera) {
  56717. return null;
  56718. }
  56719. camera = this.activeCamera;
  56720. }
  56721. if (this.spriteManagers.length > 0) {
  56722. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  56723. var spriteManager = this.spriteManagers[spriteIndex];
  56724. if (!spriteManager.isPickable) {
  56725. continue;
  56726. }
  56727. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  56728. if (!result || !result.hit)
  56729. continue;
  56730. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  56731. continue;
  56732. pickingInfo = result;
  56733. if (fastCheck) {
  56734. break;
  56735. }
  56736. }
  56737. }
  56738. return pickingInfo || new BABYLON.PickingInfo();
  56739. };
  56740. BABYLON.Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  56741. this.createPickingRayInCameraSpaceToRef(x, y, this._tempSpritePickingRay, camera);
  56742. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56743. };
  56744. BABYLON.Scene.prototype.pickSpriteWithRay = function (ray, predicate, fastCheck, camera) {
  56745. if (!this._tempSpritePickingRay) {
  56746. return null;
  56747. }
  56748. if (!camera) {
  56749. if (!this.activeCamera) {
  56750. return null;
  56751. }
  56752. camera = this.activeCamera;
  56753. }
  56754. BABYLON.Ray.TransformToRef(ray, camera.getViewMatrix(), this._tempSpritePickingRay);
  56755. return this._internalPickSprites(this._tempSpritePickingRay, predicate, fastCheck, camera);
  56756. };
  56757. BABYLON.Scene.prototype.setPointerOverSprite = function (sprite) {
  56758. if (this._pointerOverSprite === sprite) {
  56759. return;
  56760. }
  56761. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56762. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56763. }
  56764. this._pointerOverSprite = sprite;
  56765. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  56766. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  56767. }
  56768. };
  56769. BABYLON.Scene.prototype.getPointerOverSprite = function () {
  56770. return this._pointerOverSprite;
  56771. };
  56772. /**
  56773. * Defines the sprite scene component responsible to manage sprites
  56774. * in a given scene.
  56775. */
  56776. var SpriteSceneComponent = /** @class */ (function () {
  56777. /**
  56778. * Creates a new instance of the component for the given scene
  56779. * @param scene Defines the scene to register the component in
  56780. */
  56781. function SpriteSceneComponent(scene) {
  56782. /**
  56783. * The component name helpfull to identify the component in the list of scene components.
  56784. */
  56785. this.name = BABYLON.SceneComponentConstants.NAME_SPRITE;
  56786. this.scene = scene;
  56787. this.scene.spriteManagers = new Array();
  56788. this.scene._tempSpritePickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  56789. this.scene.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  56790. this.scene.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  56791. this._spritePredicate = function (sprite) {
  56792. if (!sprite.actionManager) {
  56793. return false;
  56794. }
  56795. return sprite.isPickable && sprite.actionManager.hasPointerTriggers;
  56796. };
  56797. }
  56798. /**
  56799. * Registers the component in a given scene
  56800. */
  56801. SpriteSceneComponent.prototype.register = function () {
  56802. this.scene._pointerMoveStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERMOVE_SPRITE, this, this._pointerMove);
  56803. this.scene._pointerDownStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERDOWN_SPRITE, this, this._pointerDown);
  56804. this.scene._pointerUpStage.registerStep(BABYLON.SceneComponentConstants.STEP_POINTERUP_SPRITE, this, this._pointerUp);
  56805. };
  56806. /**
  56807. * Rebuilds the elements related to this component in case of
  56808. * context lost for instance.
  56809. */
  56810. SpriteSceneComponent.prototype.rebuild = function () {
  56811. /** Nothing to do for sprites */
  56812. };
  56813. /**
  56814. * Disposes the component and the associated ressources.
  56815. */
  56816. SpriteSceneComponent.prototype.dispose = function () {
  56817. this.scene.onBeforeSpritesRenderingObservable.clear();
  56818. this.scene.onAfterSpritesRenderingObservable.clear();
  56819. var spriteManagers = this.scene.spriteManagers;
  56820. while (spriteManagers.length) {
  56821. spriteManagers[0].dispose();
  56822. }
  56823. };
  56824. SpriteSceneComponent.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, fastCheck, camera) {
  56825. var result = this.scene.pickSprite(x, y, this._spritePredicate, fastCheck, camera);
  56826. if (result) {
  56827. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  56828. }
  56829. return result;
  56830. };
  56831. SpriteSceneComponent.prototype._pointerMove = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, isMeshPicked, canvas) {
  56832. var scene = this.scene;
  56833. if (isMeshPicked) {
  56834. scene.setPointerOverSprite(null);
  56835. }
  56836. else {
  56837. pickResult = this._pickSpriteButKeepRay(pickResult, unTranslatedPointerX, unTranslatedPointerY, false, scene.cameraToUseForPointers || undefined);
  56838. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56839. scene.setPointerOverSprite(pickResult.pickedSprite);
  56840. if (scene._pointerOverSprite && scene._pointerOverSprite.actionManager && scene._pointerOverSprite.actionManager.hoverCursor) {
  56841. canvas.style.cursor = scene._pointerOverSprite.actionManager.hoverCursor;
  56842. }
  56843. else {
  56844. canvas.style.cursor = scene.hoverCursor;
  56845. }
  56846. }
  56847. else {
  56848. scene.setPointerOverSprite(null);
  56849. }
  56850. }
  56851. return pickResult;
  56852. };
  56853. SpriteSceneComponent.prototype._pointerDown = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56854. var scene = this.scene;
  56855. scene._pickedDownSprite = null;
  56856. if (scene.spriteManagers.length > 0) {
  56857. pickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56858. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  56859. if (pickResult.pickedSprite.actionManager) {
  56860. scene._pickedDownSprite = pickResult.pickedSprite;
  56861. switch (evt.button) {
  56862. case 0:
  56863. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56864. break;
  56865. case 1:
  56866. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56867. break;
  56868. case 2:
  56869. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56870. break;
  56871. }
  56872. if (pickResult.pickedSprite.actionManager) {
  56873. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, scene, evt));
  56874. }
  56875. }
  56876. }
  56877. }
  56878. return pickResult;
  56879. };
  56880. SpriteSceneComponent.prototype._pointerUp = function (unTranslatedPointerX, unTranslatedPointerY, pickResult, evt) {
  56881. var scene = this.scene;
  56882. if (scene.spriteManagers.length > 0) {
  56883. var spritePickResult = scene.pickSprite(unTranslatedPointerX, unTranslatedPointerY, this._spritePredicate, false, scene.cameraToUseForPointers || undefined);
  56884. if (spritePickResult) {
  56885. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  56886. if (spritePickResult.pickedSprite.actionManager) {
  56887. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56888. if (spritePickResult.pickedSprite.actionManager) {
  56889. if (!this.scene._isPointerSwiping()) {
  56890. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, scene, evt));
  56891. }
  56892. }
  56893. }
  56894. }
  56895. if (scene._pickedDownSprite && scene._pickedDownSprite.actionManager && scene._pickedDownSprite !== spritePickResult.pickedSprite) {
  56896. scene._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(scene._pickedDownSprite, scene, evt));
  56897. }
  56898. }
  56899. }
  56900. return pickResult;
  56901. };
  56902. return SpriteSceneComponent;
  56903. }());
  56904. BABYLON.SpriteSceneComponent = SpriteSceneComponent;
  56905. })(BABYLON || (BABYLON = {}));
  56906. //# sourceMappingURL=babylon.spriteSceneComponent.js.map
  56907. var BABYLON;
  56908. (function (BABYLON) {
  56909. /**
  56910. * @hidden
  56911. */
  56912. var IntersectionInfo = /** @class */ (function () {
  56913. function IntersectionInfo(bu, bv, distance) {
  56914. this.bu = bu;
  56915. this.bv = bv;
  56916. this.distance = distance;
  56917. this.faceId = 0;
  56918. this.subMeshId = 0;
  56919. }
  56920. return IntersectionInfo;
  56921. }());
  56922. BABYLON.IntersectionInfo = IntersectionInfo;
  56923. /**
  56924. * Information about the result of picking within a scene
  56925. * @see https://doc.babylonjs.com/babylon101/picking_collisions
  56926. */
  56927. var PickingInfo = /** @class */ (function () {
  56928. function PickingInfo() {
  56929. /**
  56930. * If the pick collided with an object
  56931. */
  56932. this.hit = false;
  56933. /**
  56934. * Distance away where the pick collided
  56935. */
  56936. this.distance = 0;
  56937. /**
  56938. * The location of pick collision
  56939. */
  56940. this.pickedPoint = null;
  56941. /**
  56942. * The mesh corresponding the the pick collision
  56943. */
  56944. this.pickedMesh = null;
  56945. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  56946. this.bu = 0;
  56947. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  56948. this.bv = 0;
  56949. /** The id of the face on the mesh that was picked */
  56950. this.faceId = -1;
  56951. /** Id of the the submesh that was picked */
  56952. this.subMeshId = 0;
  56953. /** If a sprite was picked, this will be the sprite the pick collided with */
  56954. this.pickedSprite = null;
  56955. /**
  56956. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  56957. */
  56958. this.originMesh = null;
  56959. /**
  56960. * The ray that was used to perform the picking.
  56961. */
  56962. this.ray = null;
  56963. }
  56964. /**
  56965. * Gets the normal correspodning to the face the pick collided with
  56966. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  56967. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  56968. * @returns The normal correspodning to the face the pick collided with
  56969. */
  56970. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  56971. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  56972. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  56973. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  56974. return null;
  56975. }
  56976. var indices = this.pickedMesh.getIndices();
  56977. if (!indices) {
  56978. return null;
  56979. }
  56980. var result;
  56981. if (useVerticesNormals) {
  56982. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  56983. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  56984. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  56985. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  56986. normal0 = normal0.scale(this.bu);
  56987. normal1 = normal1.scale(this.bv);
  56988. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  56989. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  56990. }
  56991. else {
  56992. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  56993. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  56994. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  56995. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  56996. var p1p2 = vertex1.subtract(vertex2);
  56997. var p3p2 = vertex3.subtract(vertex2);
  56998. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  56999. }
  57000. if (useWorldCoordinates) {
  57001. var wm = this.pickedMesh.getWorldMatrix();
  57002. if (this.pickedMesh.nonUniformScaling) {
  57003. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  57004. wm = BABYLON.Tmp.Matrix[0];
  57005. wm.setTranslationFromFloats(0, 0, 0);
  57006. wm.invert();
  57007. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  57008. wm = BABYLON.Tmp.Matrix[1];
  57009. }
  57010. result = BABYLON.Vector3.TransformNormal(result, wm);
  57011. }
  57012. result.normalize();
  57013. return result;
  57014. };
  57015. /**
  57016. * Gets the texture coordinates of where the pick occured
  57017. * @returns the vector containing the coordnates of the texture
  57018. */
  57019. PickingInfo.prototype.getTextureCoordinates = function () {
  57020. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  57021. return null;
  57022. }
  57023. var indices = this.pickedMesh.getIndices();
  57024. if (!indices) {
  57025. return null;
  57026. }
  57027. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  57028. if (!uvs) {
  57029. return null;
  57030. }
  57031. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  57032. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  57033. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  57034. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  57035. uv1 = uv1.scale(this.bu);
  57036. uv2 = uv2.scale(this.bv);
  57037. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  57038. };
  57039. return PickingInfo;
  57040. }());
  57041. BABYLON.PickingInfo = PickingInfo;
  57042. })(BABYLON || (BABYLON = {}));
  57043. //# sourceMappingURL=babylon.pickingInfo.js.map
  57044. var BABYLON;
  57045. (function (BABYLON) {
  57046. /**
  57047. * Class representing a ray with position and direction
  57048. */
  57049. var Ray = /** @class */ (function () {
  57050. /**
  57051. * Creates a new ray
  57052. * @param origin origin point
  57053. * @param direction direction
  57054. * @param length length of the ray
  57055. */
  57056. function Ray(
  57057. /** origin point */
  57058. origin,
  57059. /** direction */
  57060. direction,
  57061. /** length of the ray */
  57062. length) {
  57063. if (length === void 0) { length = Number.MAX_VALUE; }
  57064. this.origin = origin;
  57065. this.direction = direction;
  57066. this.length = length;
  57067. }
  57068. // Methods
  57069. /**
  57070. * Checks if the ray intersects a box
  57071. * @param minimum bound of the box
  57072. * @param maximum bound of the box
  57073. * @returns if the box was hit
  57074. */
  57075. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  57076. var d = 0.0;
  57077. var maxValue = Number.MAX_VALUE;
  57078. var inv;
  57079. var min;
  57080. var max;
  57081. var temp;
  57082. if (Math.abs(this.direction.x) < 0.0000001) {
  57083. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  57084. return false;
  57085. }
  57086. }
  57087. else {
  57088. inv = 1.0 / this.direction.x;
  57089. min = (minimum.x - this.origin.x) * inv;
  57090. max = (maximum.x - this.origin.x) * inv;
  57091. if (max === -Infinity) {
  57092. max = Infinity;
  57093. }
  57094. if (min > max) {
  57095. temp = min;
  57096. min = max;
  57097. max = temp;
  57098. }
  57099. d = Math.max(min, d);
  57100. maxValue = Math.min(max, maxValue);
  57101. if (d > maxValue) {
  57102. return false;
  57103. }
  57104. }
  57105. if (Math.abs(this.direction.y) < 0.0000001) {
  57106. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  57107. return false;
  57108. }
  57109. }
  57110. else {
  57111. inv = 1.0 / this.direction.y;
  57112. min = (minimum.y - this.origin.y) * inv;
  57113. max = (maximum.y - this.origin.y) * inv;
  57114. if (max === -Infinity) {
  57115. max = Infinity;
  57116. }
  57117. if (min > max) {
  57118. temp = min;
  57119. min = max;
  57120. max = temp;
  57121. }
  57122. d = Math.max(min, d);
  57123. maxValue = Math.min(max, maxValue);
  57124. if (d > maxValue) {
  57125. return false;
  57126. }
  57127. }
  57128. if (Math.abs(this.direction.z) < 0.0000001) {
  57129. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  57130. return false;
  57131. }
  57132. }
  57133. else {
  57134. inv = 1.0 / this.direction.z;
  57135. min = (minimum.z - this.origin.z) * inv;
  57136. max = (maximum.z - this.origin.z) * inv;
  57137. if (max === -Infinity) {
  57138. max = Infinity;
  57139. }
  57140. if (min > max) {
  57141. temp = min;
  57142. min = max;
  57143. max = temp;
  57144. }
  57145. d = Math.max(min, d);
  57146. maxValue = Math.min(max, maxValue);
  57147. if (d > maxValue) {
  57148. return false;
  57149. }
  57150. }
  57151. return true;
  57152. };
  57153. /**
  57154. * Checks if the ray intersects a box
  57155. * @param box the bounding box to check
  57156. * @returns if the box was hit
  57157. */
  57158. Ray.prototype.intersectsBox = function (box) {
  57159. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  57160. };
  57161. /**
  57162. * If the ray hits a sphere
  57163. * @param sphere the bounding sphere to check
  57164. * @returns true if it hits the sphere
  57165. */
  57166. Ray.prototype.intersectsSphere = function (sphere) {
  57167. var x = sphere.center.x - this.origin.x;
  57168. var y = sphere.center.y - this.origin.y;
  57169. var z = sphere.center.z - this.origin.z;
  57170. var pyth = (x * x) + (y * y) + (z * z);
  57171. var rr = sphere.radius * sphere.radius;
  57172. if (pyth <= rr) {
  57173. return true;
  57174. }
  57175. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  57176. if (dot < 0.0) {
  57177. return false;
  57178. }
  57179. var temp = pyth - (dot * dot);
  57180. return temp <= rr;
  57181. };
  57182. /**
  57183. * If the ray hits a triange
  57184. * @param vertex0 triangle vertex
  57185. * @param vertex1 triangle vertex
  57186. * @param vertex2 triangle vertex
  57187. * @returns intersection information if hit
  57188. */
  57189. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  57190. if (!this._edge1) {
  57191. this._edge1 = BABYLON.Vector3.Zero();
  57192. this._edge2 = BABYLON.Vector3.Zero();
  57193. this._pvec = BABYLON.Vector3.Zero();
  57194. this._tvec = BABYLON.Vector3.Zero();
  57195. this._qvec = BABYLON.Vector3.Zero();
  57196. }
  57197. vertex1.subtractToRef(vertex0, this._edge1);
  57198. vertex2.subtractToRef(vertex0, this._edge2);
  57199. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  57200. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  57201. if (det === 0) {
  57202. return null;
  57203. }
  57204. var invdet = 1 / det;
  57205. this.origin.subtractToRef(vertex0, this._tvec);
  57206. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  57207. if (bu < 0 || bu > 1.0) {
  57208. return null;
  57209. }
  57210. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  57211. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  57212. if (bv < 0 || bu + bv > 1.0) {
  57213. return null;
  57214. }
  57215. //check if the distance is longer than the predefined length.
  57216. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  57217. if (distance > this.length) {
  57218. return null;
  57219. }
  57220. return new BABYLON.IntersectionInfo(bu, bv, distance);
  57221. };
  57222. /**
  57223. * Checks if ray intersects a plane
  57224. * @param plane the plane to check
  57225. * @returns the distance away it was hit
  57226. */
  57227. Ray.prototype.intersectsPlane = function (plane) {
  57228. var distance;
  57229. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  57230. if (Math.abs(result1) < 9.99999997475243E-07) {
  57231. return null;
  57232. }
  57233. else {
  57234. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  57235. distance = (-plane.d - result2) / result1;
  57236. if (distance < 0.0) {
  57237. if (distance < -9.99999997475243E-07) {
  57238. return null;
  57239. }
  57240. else {
  57241. return 0;
  57242. }
  57243. }
  57244. return distance;
  57245. }
  57246. };
  57247. /**
  57248. * Checks if ray intersects a mesh
  57249. * @param mesh the mesh to check
  57250. * @param fastCheck if only the bounding box should checked
  57251. * @returns picking info of the intersecton
  57252. */
  57253. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  57254. var tm = BABYLON.Tmp.Matrix[0];
  57255. mesh.getWorldMatrix().invertToRef(tm);
  57256. if (this._tmpRay) {
  57257. Ray.TransformToRef(this, tm, this._tmpRay);
  57258. }
  57259. else {
  57260. this._tmpRay = Ray.Transform(this, tm);
  57261. }
  57262. return mesh.intersects(this._tmpRay, fastCheck);
  57263. };
  57264. /**
  57265. * Checks if ray intersects a mesh
  57266. * @param meshes the meshes to check
  57267. * @param fastCheck if only the bounding box should checked
  57268. * @param results array to store result in
  57269. * @returns Array of picking infos
  57270. */
  57271. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  57272. if (results) {
  57273. results.length = 0;
  57274. }
  57275. else {
  57276. results = [];
  57277. }
  57278. for (var i = 0; i < meshes.length; i++) {
  57279. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  57280. if (pickInfo.hit) {
  57281. results.push(pickInfo);
  57282. }
  57283. }
  57284. results.sort(this._comparePickingInfo);
  57285. return results;
  57286. };
  57287. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  57288. if (pickingInfoA.distance < pickingInfoB.distance) {
  57289. return -1;
  57290. }
  57291. else if (pickingInfoA.distance > pickingInfoB.distance) {
  57292. return 1;
  57293. }
  57294. else {
  57295. return 0;
  57296. }
  57297. };
  57298. /**
  57299. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  57300. * @param sega the first point of the segment to test the intersection against
  57301. * @param segb the second point of the segment to test the intersection against
  57302. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  57303. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  57304. */
  57305. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  57306. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  57307. var u = segb.subtract(sega);
  57308. var v = rsegb.subtract(this.origin);
  57309. var w = sega.subtract(this.origin);
  57310. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  57311. var b = BABYLON.Vector3.Dot(u, v);
  57312. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  57313. var d = BABYLON.Vector3.Dot(u, w);
  57314. var e = BABYLON.Vector3.Dot(v, w);
  57315. var D = a * c - b * b; // always >= 0
  57316. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  57317. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  57318. // compute the line parameters of the two closest points
  57319. if (D < Ray.smallnum) { // the lines are almost parallel
  57320. sN = 0.0; // force using point P0 on segment S1
  57321. sD = 1.0; // to prevent possible division by 0.0 later
  57322. tN = e;
  57323. tD = c;
  57324. }
  57325. else { // get the closest points on the infinite lines
  57326. sN = (b * e - c * d);
  57327. tN = (a * e - b * d);
  57328. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  57329. sN = 0.0;
  57330. tN = e;
  57331. tD = c;
  57332. }
  57333. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  57334. sN = sD;
  57335. tN = e + b;
  57336. tD = c;
  57337. }
  57338. }
  57339. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  57340. tN = 0.0;
  57341. // recompute sc for this edge
  57342. if (-d < 0.0) {
  57343. sN = 0.0;
  57344. }
  57345. else if (-d > a)
  57346. sN = sD;
  57347. else {
  57348. sN = -d;
  57349. sD = a;
  57350. }
  57351. }
  57352. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  57353. tN = tD;
  57354. // recompute sc for this edge
  57355. if ((-d + b) < 0.0) {
  57356. sN = 0;
  57357. }
  57358. else if ((-d + b) > a) {
  57359. sN = sD;
  57360. }
  57361. else {
  57362. sN = (-d + b);
  57363. sD = a;
  57364. }
  57365. }
  57366. // finally do the division to get sc and tc
  57367. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  57368. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  57369. // get the difference of the two closest points
  57370. var qtc = v.multiplyByFloats(tc, tc, tc);
  57371. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  57372. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  57373. if (isIntersected) {
  57374. return qtc.length();
  57375. }
  57376. return -1;
  57377. };
  57378. /**
  57379. * Update the ray from viewport position
  57380. * @param x position
  57381. * @param y y position
  57382. * @param viewportWidth viewport width
  57383. * @param viewportHeight viewport height
  57384. * @param world world matrix
  57385. * @param view view matrix
  57386. * @param projection projection matrix
  57387. * @returns this ray updated
  57388. */
  57389. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57390. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  57391. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  57392. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  57393. this.direction.normalize();
  57394. return this;
  57395. };
  57396. // Statics
  57397. /**
  57398. * Creates a ray with origin and direction of 0,0,0
  57399. * @returns the new ray
  57400. */
  57401. Ray.Zero = function () {
  57402. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  57403. };
  57404. /**
  57405. * Creates a new ray from screen space and viewport
  57406. * @param x position
  57407. * @param y y position
  57408. * @param viewportWidth viewport width
  57409. * @param viewportHeight viewport height
  57410. * @param world world matrix
  57411. * @param view view matrix
  57412. * @param projection projection matrix
  57413. * @returns new ray
  57414. */
  57415. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  57416. var result = Ray.Zero();
  57417. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  57418. };
  57419. /**
  57420. * 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
  57421. * transformed to the given world matrix.
  57422. * @param origin The origin point
  57423. * @param end The end point
  57424. * @param world a matrix to transform the ray to. Default is the identity matrix.
  57425. * @returns the new ray
  57426. */
  57427. Ray.CreateNewFromTo = function (origin, end, world) {
  57428. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  57429. var direction = end.subtract(origin);
  57430. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  57431. direction.normalize();
  57432. return Ray.Transform(new Ray(origin, direction, length), world);
  57433. };
  57434. /**
  57435. * Transforms a ray by a matrix
  57436. * @param ray ray to transform
  57437. * @param matrix matrix to apply
  57438. * @returns the resulting new ray
  57439. */
  57440. Ray.Transform = function (ray, matrix) {
  57441. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  57442. Ray.TransformToRef(ray, matrix, result);
  57443. return result;
  57444. };
  57445. /**
  57446. * Transforms a ray by a matrix
  57447. * @param ray ray to transform
  57448. * @param matrix matrix to apply
  57449. * @param result ray to store result in
  57450. */
  57451. Ray.TransformToRef = function (ray, matrix, result) {
  57452. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  57453. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  57454. result.length = ray.length;
  57455. var dir = result.direction;
  57456. var len = dir.length();
  57457. if (!(len === 0 || len === 1)) {
  57458. var num = 1.0 / len;
  57459. dir.x *= num;
  57460. dir.y *= num;
  57461. dir.z *= num;
  57462. result.length *= len;
  57463. }
  57464. };
  57465. Ray.smallnum = 0.00000001;
  57466. Ray.rayl = 10e8;
  57467. return Ray;
  57468. }());
  57469. BABYLON.Ray = Ray;
  57470. })(BABYLON || (BABYLON = {}));
  57471. //# sourceMappingURL=babylon.ray.js.map
  57472. var BABYLON;
  57473. (function (BABYLON) {
  57474. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  57475. if (boxMin.x > sphereCenter.x + sphereRadius)
  57476. return false;
  57477. if (sphereCenter.x - sphereRadius > boxMax.x)
  57478. return false;
  57479. if (boxMin.y > sphereCenter.y + sphereRadius)
  57480. return false;
  57481. if (sphereCenter.y - sphereRadius > boxMax.y)
  57482. return false;
  57483. if (boxMin.z > sphereCenter.z + sphereRadius)
  57484. return false;
  57485. if (sphereCenter.z - sphereRadius > boxMax.z)
  57486. return false;
  57487. return true;
  57488. };
  57489. var getLowestRoot = (function () {
  57490. var result = { root: 0, found: false };
  57491. return function (a, b, c, maxR) {
  57492. result.root = 0;
  57493. result.found = false;
  57494. var determinant = b * b - 4.0 * a * c;
  57495. if (determinant < 0)
  57496. return result;
  57497. var sqrtD = Math.sqrt(determinant);
  57498. var r1 = (-b - sqrtD) / (2.0 * a);
  57499. var r2 = (-b + sqrtD) / (2.0 * a);
  57500. if (r1 > r2) {
  57501. var temp = r2;
  57502. r2 = r1;
  57503. r1 = temp;
  57504. }
  57505. if (r1 > 0 && r1 < maxR) {
  57506. result.root = r1;
  57507. result.found = true;
  57508. return result;
  57509. }
  57510. if (r2 > 0 && r2 < maxR) {
  57511. result.root = r2;
  57512. result.found = true;
  57513. return result;
  57514. }
  57515. return result;
  57516. };
  57517. })();
  57518. /** @hidden */
  57519. var Collider = /** @class */ (function () {
  57520. function Collider() {
  57521. this._collisionPoint = BABYLON.Vector3.Zero();
  57522. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  57523. this._tempVector = BABYLON.Vector3.Zero();
  57524. this._tempVector2 = BABYLON.Vector3.Zero();
  57525. this._tempVector3 = BABYLON.Vector3.Zero();
  57526. this._tempVector4 = BABYLON.Vector3.Zero();
  57527. this._edge = BABYLON.Vector3.Zero();
  57528. this._baseToVertex = BABYLON.Vector3.Zero();
  57529. this._destinationPoint = BABYLON.Vector3.Zero();
  57530. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  57531. this._displacementVector = BABYLON.Vector3.Zero();
  57532. /** @hidden */
  57533. this._radius = BABYLON.Vector3.One();
  57534. /** @hidden */
  57535. this._retry = 0;
  57536. /** @hidden */
  57537. this._basePointWorld = BABYLON.Vector3.Zero();
  57538. this._velocityWorld = BABYLON.Vector3.Zero();
  57539. this._normalizedVelocity = BABYLON.Vector3.Zero();
  57540. this._collisionMask = -1;
  57541. }
  57542. Object.defineProperty(Collider.prototype, "collisionMask", {
  57543. get: function () {
  57544. return this._collisionMask;
  57545. },
  57546. set: function (mask) {
  57547. this._collisionMask = !isNaN(mask) ? mask : -1;
  57548. },
  57549. enumerable: true,
  57550. configurable: true
  57551. });
  57552. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  57553. /**
  57554. * Gets the plane normal used to compute the sliding response (in local space)
  57555. */
  57556. get: function () {
  57557. return this._slidePlaneNormal;
  57558. },
  57559. enumerable: true,
  57560. configurable: true
  57561. });
  57562. // Methods
  57563. /** @hidden */
  57564. Collider.prototype._initialize = function (source, dir, e) {
  57565. this._velocity = dir;
  57566. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  57567. this._basePoint = source;
  57568. source.multiplyToRef(this._radius, this._basePointWorld);
  57569. dir.multiplyToRef(this._radius, this._velocityWorld);
  57570. this._velocityWorldLength = this._velocityWorld.length();
  57571. this._epsilon = e;
  57572. this.collisionFound = false;
  57573. };
  57574. /** @hidden */
  57575. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  57576. pa.subtractToRef(point, this._tempVector);
  57577. pb.subtractToRef(point, this._tempVector2);
  57578. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  57579. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57580. if (d < 0)
  57581. return false;
  57582. pc.subtractToRef(point, this._tempVector3);
  57583. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  57584. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57585. if (d < 0)
  57586. return false;
  57587. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  57588. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  57589. return d >= 0;
  57590. };
  57591. /** @hidden */
  57592. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  57593. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  57594. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  57595. if (distance > this._velocityWorldLength + max + sphereRadius) {
  57596. return false;
  57597. }
  57598. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  57599. return false;
  57600. return true;
  57601. };
  57602. /** @hidden */
  57603. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  57604. var t0;
  57605. var embeddedInPlane = false;
  57606. //defensive programming, actually not needed.
  57607. if (!trianglePlaneArray) {
  57608. trianglePlaneArray = [];
  57609. }
  57610. if (!trianglePlaneArray[faceIndex]) {
  57611. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  57612. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  57613. }
  57614. var trianglePlane = trianglePlaneArray[faceIndex];
  57615. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  57616. return;
  57617. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  57618. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  57619. if (normalDotVelocity == 0) {
  57620. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  57621. return;
  57622. embeddedInPlane = true;
  57623. t0 = 0;
  57624. }
  57625. else {
  57626. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57627. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  57628. if (t0 > t1) {
  57629. var temp = t1;
  57630. t1 = t0;
  57631. t0 = temp;
  57632. }
  57633. if (t0 > 1.0 || t1 < 0.0)
  57634. return;
  57635. if (t0 < 0)
  57636. t0 = 0;
  57637. if (t0 > 1.0)
  57638. t0 = 1.0;
  57639. }
  57640. this._collisionPoint.copyFromFloats(0, 0, 0);
  57641. var found = false;
  57642. var t = 1.0;
  57643. if (!embeddedInPlane) {
  57644. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  57645. this._velocity.scaleToRef(t0, this._tempVector);
  57646. this._planeIntersectionPoint.addInPlace(this._tempVector);
  57647. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  57648. found = true;
  57649. t = t0;
  57650. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  57651. }
  57652. }
  57653. if (!found) {
  57654. var velocitySquaredLength = this._velocity.lengthSquared();
  57655. var a = velocitySquaredLength;
  57656. this._basePoint.subtractToRef(p1, this._tempVector);
  57657. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57658. var c = this._tempVector.lengthSquared() - 1.0;
  57659. var lowestRoot = getLowestRoot(a, b, c, t);
  57660. if (lowestRoot.found) {
  57661. t = lowestRoot.root;
  57662. found = true;
  57663. this._collisionPoint.copyFrom(p1);
  57664. }
  57665. this._basePoint.subtractToRef(p2, this._tempVector);
  57666. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57667. c = this._tempVector.lengthSquared() - 1.0;
  57668. lowestRoot = getLowestRoot(a, b, c, t);
  57669. if (lowestRoot.found) {
  57670. t = lowestRoot.root;
  57671. found = true;
  57672. this._collisionPoint.copyFrom(p2);
  57673. }
  57674. this._basePoint.subtractToRef(p3, this._tempVector);
  57675. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  57676. c = this._tempVector.lengthSquared() - 1.0;
  57677. lowestRoot = getLowestRoot(a, b, c, t);
  57678. if (lowestRoot.found) {
  57679. t = lowestRoot.root;
  57680. found = true;
  57681. this._collisionPoint.copyFrom(p3);
  57682. }
  57683. p2.subtractToRef(p1, this._edge);
  57684. p1.subtractToRef(this._basePoint, this._baseToVertex);
  57685. var edgeSquaredLength = this._edge.lengthSquared();
  57686. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57687. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57688. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57689. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57690. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57691. lowestRoot = getLowestRoot(a, b, c, t);
  57692. if (lowestRoot.found) {
  57693. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57694. if (f >= 0.0 && f <= 1.0) {
  57695. t = lowestRoot.root;
  57696. found = true;
  57697. this._edge.scaleInPlace(f);
  57698. p1.addToRef(this._edge, this._collisionPoint);
  57699. }
  57700. }
  57701. p3.subtractToRef(p2, this._edge);
  57702. p2.subtractToRef(this._basePoint, this._baseToVertex);
  57703. edgeSquaredLength = this._edge.lengthSquared();
  57704. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57705. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57706. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57707. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57708. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57709. lowestRoot = getLowestRoot(a, b, c, t);
  57710. if (lowestRoot.found) {
  57711. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57712. if (f >= 0.0 && f <= 1.0) {
  57713. t = lowestRoot.root;
  57714. found = true;
  57715. this._edge.scaleInPlace(f);
  57716. p2.addToRef(this._edge, this._collisionPoint);
  57717. }
  57718. }
  57719. p1.subtractToRef(p3, this._edge);
  57720. p3.subtractToRef(this._basePoint, this._baseToVertex);
  57721. edgeSquaredLength = this._edge.lengthSquared();
  57722. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  57723. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  57724. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  57725. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  57726. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  57727. lowestRoot = getLowestRoot(a, b, c, t);
  57728. if (lowestRoot.found) {
  57729. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  57730. if (f >= 0.0 && f <= 1.0) {
  57731. t = lowestRoot.root;
  57732. found = true;
  57733. this._edge.scaleInPlace(f);
  57734. p3.addToRef(this._edge, this._collisionPoint);
  57735. }
  57736. }
  57737. }
  57738. if (found) {
  57739. var distToCollision = t * this._velocity.length();
  57740. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  57741. if (!this.intersectionPoint) {
  57742. this.intersectionPoint = this._collisionPoint.clone();
  57743. }
  57744. else {
  57745. this.intersectionPoint.copyFrom(this._collisionPoint);
  57746. }
  57747. this._nearestDistance = distToCollision;
  57748. this.collisionFound = true;
  57749. }
  57750. }
  57751. };
  57752. /** @hidden */
  57753. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  57754. for (var i = indexStart; i < indexEnd; i += 3) {
  57755. var p1 = pts[indices[i] - decal];
  57756. var p2 = pts[indices[i + 1] - decal];
  57757. var p3 = pts[indices[i + 2] - decal];
  57758. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  57759. }
  57760. };
  57761. /** @hidden */
  57762. Collider.prototype._getResponse = function (pos, vel) {
  57763. pos.addToRef(vel, this._destinationPoint);
  57764. vel.scaleInPlace((this._nearestDistance / vel.length()));
  57765. this._basePoint.addToRef(vel, pos);
  57766. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  57767. this._slidePlaneNormal.normalize();
  57768. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  57769. pos.addInPlace(this._displacementVector);
  57770. this.intersectionPoint.addInPlace(this._displacementVector);
  57771. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  57772. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  57773. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  57774. };
  57775. return Collider;
  57776. }());
  57777. BABYLON.Collider = Collider;
  57778. })(BABYLON || (BABYLON = {}));
  57779. //# sourceMappingURL=babylon.collider.js.map
  57780. var BABYLON;
  57781. (function (BABYLON) {
  57782. //WebWorker code will be inserted to this variable.
  57783. /** @hidden */
  57784. BABYLON.CollisionWorker = "";
  57785. /** Defines supported task for worker process */
  57786. var WorkerTaskType;
  57787. (function (WorkerTaskType) {
  57788. /** Initialization */
  57789. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  57790. /** Update of geometry */
  57791. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  57792. /** Evaluate collision */
  57793. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  57794. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  57795. /** Defines kind of replies returned by worker */
  57796. var WorkerReplyType;
  57797. (function (WorkerReplyType) {
  57798. /** Success */
  57799. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  57800. /** Unkown error */
  57801. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  57802. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  57803. /** @hidden */
  57804. var CollisionCoordinatorWorker = /** @class */ (function () {
  57805. function CollisionCoordinatorWorker() {
  57806. var _this = this;
  57807. this._scaledPosition = BABYLON.Vector3.Zero();
  57808. this._scaledVelocity = BABYLON.Vector3.Zero();
  57809. this.onMeshUpdated = function (transformNode) {
  57810. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  57811. };
  57812. this.onGeometryUpdated = function (geometry) {
  57813. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  57814. };
  57815. this._afterRender = function () {
  57816. if (!_this._init)
  57817. return;
  57818. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  57819. return;
  57820. }
  57821. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  57822. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  57823. if (_this._runningUpdated > 4) {
  57824. return;
  57825. }
  57826. ++_this._runningUpdated;
  57827. var payload = {
  57828. updatedMeshes: _this._addUpdateMeshesList,
  57829. updatedGeometries: _this._addUpdateGeometriesList,
  57830. removedGeometries: _this._toRemoveGeometryArray,
  57831. removedMeshes: _this._toRemoveMeshesArray
  57832. };
  57833. var message = {
  57834. payload: payload,
  57835. taskType: WorkerTaskType.UPDATE
  57836. };
  57837. var serializable = [];
  57838. for (var id in payload.updatedGeometries) {
  57839. if (payload.updatedGeometries.hasOwnProperty(id)) {
  57840. //prepare transferables
  57841. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  57842. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  57843. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  57844. }
  57845. }
  57846. _this._worker.postMessage(message, serializable);
  57847. _this._addUpdateMeshesList = {};
  57848. _this._addUpdateGeometriesList = {};
  57849. _this._toRemoveGeometryArray = [];
  57850. _this._toRemoveMeshesArray = [];
  57851. };
  57852. this._onMessageFromWorker = function (e) {
  57853. var returnData = e.data;
  57854. if (returnData.error != WorkerReplyType.SUCCESS) {
  57855. //TODO what errors can be returned from the worker?
  57856. BABYLON.Tools.Warn("error returned from worker!");
  57857. return;
  57858. }
  57859. switch (returnData.taskType) {
  57860. case WorkerTaskType.INIT:
  57861. _this._init = true;
  57862. //Update the worked with ALL of the scene's current state
  57863. _this._scene.meshes.forEach(function (mesh) {
  57864. _this.onMeshAdded(mesh);
  57865. });
  57866. _this._scene.getGeometries().forEach(function (geometry) {
  57867. _this.onGeometryAdded(geometry);
  57868. });
  57869. break;
  57870. case WorkerTaskType.UPDATE:
  57871. _this._runningUpdated--;
  57872. break;
  57873. case WorkerTaskType.COLLIDE:
  57874. var returnPayload = returnData.payload;
  57875. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  57876. return;
  57877. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  57878. if (callback) {
  57879. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  57880. if (mesh) {
  57881. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  57882. }
  57883. }
  57884. //cleanup
  57885. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  57886. break;
  57887. }
  57888. };
  57889. this._collisionsCallbackArray = [];
  57890. this._init = false;
  57891. this._runningUpdated = 0;
  57892. this._addUpdateMeshesList = {};
  57893. this._addUpdateGeometriesList = {};
  57894. this._toRemoveGeometryArray = [];
  57895. this._toRemoveMeshesArray = [];
  57896. }
  57897. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  57898. if (!this._init)
  57899. return;
  57900. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  57901. return;
  57902. position.divideToRef(collider._radius, this._scaledPosition);
  57903. displacement.divideToRef(collider._radius, this._scaledVelocity);
  57904. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  57905. var payload = {
  57906. collider: {
  57907. position: this._scaledPosition.asArray(),
  57908. velocity: this._scaledVelocity.asArray(),
  57909. radius: collider._radius.asArray()
  57910. },
  57911. collisionId: collisionIndex,
  57912. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  57913. maximumRetry: maximumRetry
  57914. };
  57915. var message = {
  57916. payload: payload,
  57917. taskType: WorkerTaskType.COLLIDE
  57918. };
  57919. this._worker.postMessage(message);
  57920. };
  57921. CollisionCoordinatorWorker.prototype.init = function (scene) {
  57922. this._scene = scene;
  57923. this._scene.registerAfterRender(this._afterRender);
  57924. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  57925. this._worker = new Worker(workerUrl);
  57926. this._worker.onmessage = this._onMessageFromWorker;
  57927. var message = {
  57928. payload: {},
  57929. taskType: WorkerTaskType.INIT
  57930. };
  57931. this._worker.postMessage(message);
  57932. };
  57933. CollisionCoordinatorWorker.prototype.destroy = function () {
  57934. this._scene.unregisterAfterRender(this._afterRender);
  57935. this._worker.terminate();
  57936. };
  57937. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  57938. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  57939. this.onMeshUpdated(mesh);
  57940. };
  57941. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  57942. this._toRemoveMeshesArray.push(mesh.uniqueId);
  57943. };
  57944. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  57945. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  57946. geometry.onGeometryUpdated = this.onGeometryUpdated;
  57947. this.onGeometryUpdated(geometry);
  57948. };
  57949. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  57950. this._toRemoveGeometryArray.push(geometry.id);
  57951. };
  57952. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  57953. var submeshes = [];
  57954. if (mesh.subMeshes) {
  57955. submeshes = mesh.subMeshes.map(function (sm, idx) {
  57956. var boundingInfo = sm.getBoundingInfo();
  57957. return {
  57958. position: idx,
  57959. verticesStart: sm.verticesStart,
  57960. verticesCount: sm.verticesCount,
  57961. indexStart: sm.indexStart,
  57962. indexCount: sm.indexCount,
  57963. hasMaterial: !!sm.getMaterial(),
  57964. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57965. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57966. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57967. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  57968. };
  57969. });
  57970. }
  57971. var geometryId = null;
  57972. if (mesh instanceof BABYLON.Mesh) {
  57973. var geometry = mesh.geometry;
  57974. geometryId = geometry ? geometry.id : null;
  57975. }
  57976. else if (mesh instanceof BABYLON.InstancedMesh) {
  57977. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  57978. geometryId = geometry ? geometry.id : null;
  57979. }
  57980. var boundingInfo = mesh.getBoundingInfo();
  57981. return {
  57982. uniqueId: mesh.uniqueId,
  57983. id: mesh.id,
  57984. name: mesh.name,
  57985. geometryId: geometryId,
  57986. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  57987. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  57988. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  57989. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  57990. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  57991. subMeshes: submeshes,
  57992. checkCollisions: mesh.checkCollisions
  57993. };
  57994. };
  57995. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  57996. return {
  57997. id: geometry.id,
  57998. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  57999. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  58000. indices: new Uint32Array(geometry.getIndices() || []),
  58001. };
  58002. };
  58003. return CollisionCoordinatorWorker;
  58004. }());
  58005. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  58006. /** @hidden */
  58007. var CollisionCoordinatorLegacy = /** @class */ (function () {
  58008. function CollisionCoordinatorLegacy() {
  58009. this._scaledPosition = BABYLON.Vector3.Zero();
  58010. this._scaledVelocity = BABYLON.Vector3.Zero();
  58011. this._finalPosition = BABYLON.Vector3.Zero();
  58012. }
  58013. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  58014. position.divideToRef(collider._radius, this._scaledPosition);
  58015. displacement.divideToRef(collider._radius, this._scaledVelocity);
  58016. collider.collidedMesh = null;
  58017. collider._retry = 0;
  58018. collider._initialVelocity = this._scaledVelocity;
  58019. collider._initialPosition = this._scaledPosition;
  58020. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  58021. this._finalPosition.multiplyInPlace(collider._radius);
  58022. //run the callback
  58023. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  58024. };
  58025. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  58026. this._scene = scene;
  58027. };
  58028. CollisionCoordinatorLegacy.prototype.destroy = function () {
  58029. //Legacy need no destruction method.
  58030. };
  58031. //No update in legacy mode
  58032. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  58033. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  58034. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  58035. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  58036. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  58037. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  58038. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  58039. if (excludedMesh === void 0) { excludedMesh = null; }
  58040. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  58041. if (collider._retry >= maximumRetry) {
  58042. finalPosition.copyFrom(position);
  58043. return;
  58044. }
  58045. // Check if this is a mesh else camera or -1
  58046. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  58047. collider._initialize(position, velocity, closeDistance);
  58048. // Check all meshes
  58049. for (var index = 0; index < this._scene.meshes.length; index++) {
  58050. var mesh = this._scene.meshes[index];
  58051. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  58052. mesh._checkCollision(collider);
  58053. }
  58054. }
  58055. if (!collider.collisionFound) {
  58056. position.addToRef(velocity, finalPosition);
  58057. return;
  58058. }
  58059. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  58060. collider._getResponse(position, velocity);
  58061. }
  58062. if (velocity.length() <= closeDistance) {
  58063. finalPosition.copyFrom(position);
  58064. return;
  58065. }
  58066. collider._retry++;
  58067. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  58068. };
  58069. return CollisionCoordinatorLegacy;
  58070. }());
  58071. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  58072. })(BABYLON || (BABYLON = {}));
  58073. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  58074. var BABYLON;
  58075. (function (BABYLON) {
  58076. /**
  58077. * A particle represents one of the element emitted by a particle system.
  58078. * This is mainly define by its coordinates, direction, velocity and age.
  58079. */
  58080. var Particle = /** @class */ (function () {
  58081. /**
  58082. * Creates a new instance Particle
  58083. * @param particleSystem the particle system the particle belongs to
  58084. */
  58085. function Particle(
  58086. /**
  58087. * The particle system the particle belongs to.
  58088. */
  58089. particleSystem) {
  58090. this.particleSystem = particleSystem;
  58091. /**
  58092. * The world position of the particle in the scene.
  58093. */
  58094. this.position = BABYLON.Vector3.Zero();
  58095. /**
  58096. * The world direction of the particle in the scene.
  58097. */
  58098. this.direction = BABYLON.Vector3.Zero();
  58099. /**
  58100. * The color of the particle.
  58101. */
  58102. this.color = new BABYLON.Color4(0, 0, 0, 0);
  58103. /**
  58104. * The color change of the particle per step.
  58105. */
  58106. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  58107. /**
  58108. * Defines how long will the life of the particle be.
  58109. */
  58110. this.lifeTime = 1.0;
  58111. /**
  58112. * The current age of the particle.
  58113. */
  58114. this.age = 0;
  58115. /**
  58116. * The current size of the particle.
  58117. */
  58118. this.size = 0;
  58119. /**
  58120. * The current scale of the particle.
  58121. */
  58122. this.scale = new BABYLON.Vector2(1, 1);
  58123. /**
  58124. * The current angle of the particle.
  58125. */
  58126. this.angle = 0;
  58127. /**
  58128. * Defines how fast is the angle changing.
  58129. */
  58130. this.angularSpeed = 0;
  58131. /**
  58132. * Defines the cell index used by the particle to be rendered from a sprite.
  58133. */
  58134. this.cellIndex = 0;
  58135. /** @hidden */
  58136. this._attachedSubEmitters = null;
  58137. /** @hidden */
  58138. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  58139. /** @hidden */
  58140. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  58141. /** @hidden */
  58142. this._currentSize1 = 0;
  58143. /** @hidden */
  58144. this._currentSize2 = 0;
  58145. /** @hidden */
  58146. this._currentAngularSpeed1 = 0;
  58147. /** @hidden */
  58148. this._currentAngularSpeed2 = 0;
  58149. /** @hidden */
  58150. this._currentVelocity1 = 0;
  58151. /** @hidden */
  58152. this._currentVelocity2 = 0;
  58153. /** @hidden */
  58154. this._currentLimitVelocity1 = 0;
  58155. /** @hidden */
  58156. this._currentLimitVelocity2 = 0;
  58157. /** @hidden */
  58158. this._currentDrag1 = 0;
  58159. /** @hidden */
  58160. this._currentDrag2 = 0;
  58161. this.id = Particle._Count++;
  58162. if (!this.particleSystem.isAnimationSheetEnabled) {
  58163. return;
  58164. }
  58165. this.updateCellInfoFromSystem();
  58166. }
  58167. Particle.prototype.updateCellInfoFromSystem = function () {
  58168. this.cellIndex = this.particleSystem.startSpriteCellID;
  58169. };
  58170. /**
  58171. * Defines how the sprite cell index is updated for the particle
  58172. */
  58173. Particle.prototype.updateCellIndex = function () {
  58174. var offsetAge = this.age;
  58175. var changeSpeed = this.particleSystem.spriteCellChangeSpeed;
  58176. if (this.particleSystem.spriteRandomStartCell) {
  58177. if (this._randomCellOffset === undefined) {
  58178. this._randomCellOffset = Math.random() * this.lifeTime;
  58179. }
  58180. if (changeSpeed === 0) { // Special case when speed = 0 meaning we want to stay on initial cell
  58181. changeSpeed = 1;
  58182. offsetAge = this._randomCellOffset;
  58183. }
  58184. else {
  58185. offsetAge += this._randomCellOffset;
  58186. }
  58187. }
  58188. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  58189. var ratio = BABYLON.Scalar.Clamp(((offsetAge * changeSpeed) % this.lifeTime) / this.lifeTime);
  58190. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  58191. };
  58192. /** @hidden */
  58193. Particle.prototype._inheritParticleInfoToSubEmitter = function (subEmitter) {
  58194. if (subEmitter.particleSystem.emitter.position) {
  58195. var emitterMesh = subEmitter.particleSystem.emitter;
  58196. emitterMesh.position.copyFrom(this.position);
  58197. if (subEmitter.inheritDirection) {
  58198. emitterMesh.position.subtractToRef(this.direction, BABYLON.Tmp.Vector3[0]);
  58199. // Look at using Y as forward
  58200. emitterMesh.lookAt(BABYLON.Tmp.Vector3[0], 0, Math.PI / 2);
  58201. }
  58202. }
  58203. else {
  58204. var emitterPosition = subEmitter.particleSystem.emitter;
  58205. emitterPosition.copyFrom(this.position);
  58206. }
  58207. // Set inheritedVelocityOffset to be used when new particles are created
  58208. this.direction.scaleToRef(subEmitter.inheritedVelocityAmount / 2, BABYLON.Tmp.Vector3[0]);
  58209. subEmitter.particleSystem._inheritedVelocityOffset.copyFrom(BABYLON.Tmp.Vector3[0]);
  58210. };
  58211. /** @hidden */
  58212. Particle.prototype._inheritParticleInfoToSubEmitters = function () {
  58213. var _this = this;
  58214. if (this._attachedSubEmitters && this._attachedSubEmitters.length > 0) {
  58215. this._attachedSubEmitters.forEach(function (subEmitter) {
  58216. _this._inheritParticleInfoToSubEmitter(subEmitter);
  58217. });
  58218. }
  58219. };
  58220. /** @hidden */
  58221. Particle.prototype._reset = function () {
  58222. this.age = 0;
  58223. this._currentColorGradient = null;
  58224. this._currentSizeGradient = null;
  58225. this._currentAngularSpeedGradient = null;
  58226. this._currentVelocityGradient = null;
  58227. this._currentLimitVelocityGradient = null;
  58228. this._currentDragGradient = null;
  58229. this.cellIndex = this.particleSystem.startSpriteCellID;
  58230. this._randomCellOffset = undefined;
  58231. };
  58232. /**
  58233. * Copy the properties of particle to another one.
  58234. * @param other the particle to copy the information to.
  58235. */
  58236. Particle.prototype.copyTo = function (other) {
  58237. other.position.copyFrom(this.position);
  58238. if (this._initialDirection) {
  58239. if (other._initialDirection) {
  58240. other._initialDirection.copyFrom(this._initialDirection);
  58241. }
  58242. else {
  58243. other._initialDirection = this._initialDirection.clone();
  58244. }
  58245. }
  58246. else {
  58247. other._initialDirection = null;
  58248. }
  58249. other.direction.copyFrom(this.direction);
  58250. other.color.copyFrom(this.color);
  58251. other.colorStep.copyFrom(this.colorStep);
  58252. other.lifeTime = this.lifeTime;
  58253. other.age = this.age;
  58254. other._randomCellOffset = this._randomCellOffset;
  58255. other.size = this.size;
  58256. other.scale.copyFrom(this.scale);
  58257. other.angle = this.angle;
  58258. other.angularSpeed = this.angularSpeed;
  58259. other.particleSystem = this.particleSystem;
  58260. other.cellIndex = this.cellIndex;
  58261. other.id = this.id;
  58262. other._attachedSubEmitters = this._attachedSubEmitters;
  58263. if (this._currentColorGradient) {
  58264. other._currentColorGradient = this._currentColorGradient;
  58265. other._currentColor1.copyFrom(this._currentColor1);
  58266. other._currentColor2.copyFrom(this._currentColor2);
  58267. }
  58268. if (this._currentSizeGradient) {
  58269. other._currentSizeGradient = this._currentSizeGradient;
  58270. other._currentSize1 = this._currentSize1;
  58271. other._currentSize2 = this._currentSize2;
  58272. }
  58273. if (this._currentAngularSpeedGradient) {
  58274. other._currentAngularSpeedGradient = this._currentAngularSpeedGradient;
  58275. other._currentAngularSpeed1 = this._currentAngularSpeed1;
  58276. other._currentAngularSpeed2 = this._currentAngularSpeed2;
  58277. }
  58278. if (this._currentVelocityGradient) {
  58279. other._currentVelocityGradient = this._currentVelocityGradient;
  58280. other._currentVelocity1 = this._currentVelocity1;
  58281. other._currentVelocity2 = this._currentVelocity2;
  58282. }
  58283. if (this._currentLimitVelocityGradient) {
  58284. other._currentLimitVelocityGradient = this._currentLimitVelocityGradient;
  58285. other._currentLimitVelocity1 = this._currentLimitVelocity1;
  58286. other._currentLimitVelocity2 = this._currentLimitVelocity2;
  58287. }
  58288. if (this._currentDragGradient) {
  58289. other._currentDragGradient = this._currentDragGradient;
  58290. other._currentDrag1 = this._currentDrag1;
  58291. other._currentDrag2 = this._currentDrag2;
  58292. }
  58293. if (this.particleSystem.isAnimationSheetEnabled) {
  58294. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  58295. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  58296. }
  58297. if (this.particleSystem.useRampGradients) {
  58298. other.remapData.copyFrom(this.remapData);
  58299. }
  58300. if (this._randomNoiseCoordinates1) {
  58301. if (other._randomNoiseCoordinates1) {
  58302. other._randomNoiseCoordinates1.copyFrom(this._randomNoiseCoordinates1);
  58303. other._randomNoiseCoordinates2.copyFrom(this._randomNoiseCoordinates2);
  58304. }
  58305. else {
  58306. other._randomNoiseCoordinates1 = this._randomNoiseCoordinates1.clone();
  58307. other._randomNoiseCoordinates2 = this._randomNoiseCoordinates2.clone();
  58308. }
  58309. }
  58310. };
  58311. Particle._Count = 0;
  58312. return Particle;
  58313. }());
  58314. BABYLON.Particle = Particle;
  58315. })(BABYLON || (BABYLON = {}));
  58316. //# sourceMappingURL=babylon.particle.js.map
  58317. var BABYLON;
  58318. (function (BABYLON) {
  58319. /**
  58320. * This represents the base class for particle system in Babylon.
  58321. * 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.
  58322. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58323. * @example https://doc.babylonjs.com/babylon101/particles
  58324. */
  58325. var BaseParticleSystem = /** @class */ (function () {
  58326. /**
  58327. * Instantiates a particle system.
  58328. * 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.
  58329. * @param name The name of the particle system
  58330. */
  58331. function BaseParticleSystem(name) {
  58332. /**
  58333. * List of animations used by the particle system.
  58334. */
  58335. this.animations = [];
  58336. /**
  58337. * The rendering group used by the Particle system to chose when to render.
  58338. */
  58339. this.renderingGroupId = 0;
  58340. /**
  58341. * The emitter represents the Mesh or position we are attaching the particle system to.
  58342. */
  58343. this.emitter = null;
  58344. /**
  58345. * The maximum number of particles to emit per frame
  58346. */
  58347. this.emitRate = 10;
  58348. /**
  58349. * If you want to launch only a few particles at once, that can be done, as well.
  58350. */
  58351. this.manualEmitCount = -1;
  58352. /**
  58353. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  58354. */
  58355. this.updateSpeed = 0.01;
  58356. /**
  58357. * The amount of time the particle system is running (depends of the overall update speed).
  58358. */
  58359. this.targetStopDuration = 0;
  58360. /**
  58361. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  58362. */
  58363. this.disposeOnStop = false;
  58364. /**
  58365. * Minimum power of emitting particles.
  58366. */
  58367. this.minEmitPower = 1;
  58368. /**
  58369. * Maximum power of emitting particles.
  58370. */
  58371. this.maxEmitPower = 1;
  58372. /**
  58373. * Minimum life time of emitting particles.
  58374. */
  58375. this.minLifeTime = 1;
  58376. /**
  58377. * Maximum life time of emitting particles.
  58378. */
  58379. this.maxLifeTime = 1;
  58380. /**
  58381. * Minimum Size of emitting particles.
  58382. */
  58383. this.minSize = 1;
  58384. /**
  58385. * Maximum Size of emitting particles.
  58386. */
  58387. this.maxSize = 1;
  58388. /**
  58389. * Minimum scale of emitting particles on X axis.
  58390. */
  58391. this.minScaleX = 1;
  58392. /**
  58393. * Maximum scale of emitting particles on X axis.
  58394. */
  58395. this.maxScaleX = 1;
  58396. /**
  58397. * Minimum scale of emitting particles on Y axis.
  58398. */
  58399. this.minScaleY = 1;
  58400. /**
  58401. * Maximum scale of emitting particles on Y axis.
  58402. */
  58403. this.maxScaleY = 1;
  58404. /**
  58405. * Gets or sets the minimal initial rotation in radians.
  58406. */
  58407. this.minInitialRotation = 0;
  58408. /**
  58409. * Gets or sets the maximal initial rotation in radians.
  58410. */
  58411. this.maxInitialRotation = 0;
  58412. /**
  58413. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  58414. */
  58415. this.minAngularSpeed = 0;
  58416. /**
  58417. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  58418. */
  58419. this.maxAngularSpeed = 0;
  58420. /**
  58421. * The layer mask we are rendering the particles through.
  58422. */
  58423. this.layerMask = 0x0FFFFFFF;
  58424. /**
  58425. * This can help using your own shader to render the particle system.
  58426. * The according effect will be created
  58427. */
  58428. this.customShader = null;
  58429. /**
  58430. * By default particle system starts as soon as they are created. This prevents the
  58431. * automatic start to happen and let you decide when to start emitting particles.
  58432. */
  58433. this.preventAutoStart = false;
  58434. /** Gets or sets the strength to apply to the noise value (default is (10, 10, 10)) */
  58435. this.noiseStrength = new BABYLON.Vector3(10, 10, 10);
  58436. /**
  58437. * Callback triggered when the particle animation is ending.
  58438. */
  58439. this.onAnimationEnd = null;
  58440. /**
  58441. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  58442. */
  58443. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  58444. /**
  58445. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  58446. * to override the particles.
  58447. */
  58448. this.forceDepthWrite = false;
  58449. /** 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 */
  58450. this.preWarmCycles = 0;
  58451. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  58452. this.preWarmStepOffset = 1;
  58453. /**
  58454. * 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)
  58455. */
  58456. this.spriteCellChangeSpeed = 1;
  58457. /**
  58458. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  58459. */
  58460. this.startSpriteCellID = 0;
  58461. /**
  58462. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  58463. */
  58464. this.endSpriteCellID = 0;
  58465. /**
  58466. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  58467. */
  58468. this.spriteCellWidth = 0;
  58469. /**
  58470. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  58471. */
  58472. this.spriteCellHeight = 0;
  58473. /**
  58474. * This allows the system to random pick the start cell ID between startSpriteCellID and endSpriteCellID
  58475. */
  58476. this.spriteRandomStartCell = false;
  58477. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  58478. this.translationPivot = new BABYLON.Vector2(0, 0);
  58479. /**
  58480. * Gets or sets a boolean indicating that hosted animations (in the system.animations array) must be started when system.start() is called
  58481. */
  58482. this.beginAnimationOnStart = false;
  58483. /**
  58484. * Gets or sets the frame to start the animation from when beginAnimationOnStart is true
  58485. */
  58486. this.beginAnimationFrom = 0;
  58487. /**
  58488. * Gets or sets the frame to end the animation on when beginAnimationOnStart is true
  58489. */
  58490. this.beginAnimationTo = 60;
  58491. /**
  58492. * Gets or sets a boolean indicating if animations must loop when beginAnimationOnStart is true
  58493. */
  58494. this.beginAnimationLoop = false;
  58495. /**
  58496. * You can use gravity if you want to give an orientation to your particles.
  58497. */
  58498. this.gravity = BABYLON.Vector3.Zero();
  58499. this._colorGradients = null;
  58500. this._sizeGradients = null;
  58501. this._lifeTimeGradients = null;
  58502. this._angularSpeedGradients = null;
  58503. this._velocityGradients = null;
  58504. this._limitVelocityGradients = null;
  58505. this._dragGradients = null;
  58506. this._emitRateGradients = null;
  58507. this._startSizeGradients = null;
  58508. this._rampGradients = null;
  58509. this._colorRemapGradients = null;
  58510. this._alphaRemapGradients = null;
  58511. /**
  58512. * Defines the delay in milliseconds before starting the system (0 by default)
  58513. */
  58514. this.startDelay = 0;
  58515. /** Gets or sets a value indicating the damping to apply if the limit velocity factor is reached */
  58516. this.limitVelocityDamping = 0.4;
  58517. /**
  58518. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58519. */
  58520. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58521. /**
  58522. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  58523. */
  58524. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58525. /**
  58526. * Color the particle will have at the end of its lifetime
  58527. */
  58528. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  58529. /**
  58530. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  58531. */
  58532. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58533. /** @hidden */
  58534. this._isSubEmitter = false;
  58535. /**
  58536. * Gets or sets the billboard mode to use when isBillboardBased = true.
  58537. * Value can be: ParticleSystem.BILLBOARDMODE_ALL, ParticleSystem.BILLBOARDMODE_Y, ParticleSystem.BILLBOARDMODE_STRETCHED
  58538. */
  58539. this.billboardMode = BABYLON.ParticleSystem.BILLBOARDMODE_ALL;
  58540. this._isBillboardBased = true;
  58541. /**
  58542. * Local cache of defines for image processing.
  58543. */
  58544. this._imageProcessingConfigurationDefines = new BABYLON.ImageProcessingConfigurationDefines();
  58545. this.id = name;
  58546. this.name = name;
  58547. }
  58548. Object.defineProperty(BaseParticleSystem.prototype, "isAnimationSheetEnabled", {
  58549. /**
  58550. * Gets or sets whether an animation sprite sheet is enabled or not on the particle system
  58551. */
  58552. get: function () {
  58553. return this._isAnimationSheetEnabled;
  58554. },
  58555. set: function (value) {
  58556. if (this._isAnimationSheetEnabled == value) {
  58557. return;
  58558. }
  58559. this._isAnimationSheetEnabled = value;
  58560. this._reset();
  58561. },
  58562. enumerable: true,
  58563. configurable: true
  58564. });
  58565. /**
  58566. * Get hosting scene
  58567. * @returns the scene
  58568. */
  58569. BaseParticleSystem.prototype.getScene = function () {
  58570. return this._scene;
  58571. };
  58572. BaseParticleSystem.prototype._hasTargetStopDurationDependantGradient = function () {
  58573. return (this._startSizeGradients && this._startSizeGradients.length > 0)
  58574. || (this._emitRateGradients && this._emitRateGradients.length > 0)
  58575. || (this._lifeTimeGradients && this._lifeTimeGradients.length > 0);
  58576. };
  58577. /**
  58578. * Gets the current list of drag gradients.
  58579. * You must use addDragGradient and removeDragGradient to udpate this list
  58580. * @returns the list of drag gradients
  58581. */
  58582. BaseParticleSystem.prototype.getDragGradients = function () {
  58583. return this._dragGradients;
  58584. };
  58585. /**
  58586. * Gets the current list of limit velocity gradients.
  58587. * You must use addLimitVelocityGradient and removeLimitVelocityGradient to udpate this list
  58588. * @returns the list of limit velocity gradients
  58589. */
  58590. BaseParticleSystem.prototype.getLimitVelocityGradients = function () {
  58591. return this._limitVelocityGradients;
  58592. };
  58593. /**
  58594. * Gets the current list of color gradients.
  58595. * You must use addColorGradient and removeColorGradient to udpate this list
  58596. * @returns the list of color gradients
  58597. */
  58598. BaseParticleSystem.prototype.getColorGradients = function () {
  58599. return this._colorGradients;
  58600. };
  58601. /**
  58602. * Gets the current list of size gradients.
  58603. * You must use addSizeGradient and removeSizeGradient to udpate this list
  58604. * @returns the list of size gradients
  58605. */
  58606. BaseParticleSystem.prototype.getSizeGradients = function () {
  58607. return this._sizeGradients;
  58608. };
  58609. /**
  58610. * Gets the current list of color remap gradients.
  58611. * You must use addColorRemapGradient and removeColorRemapGradient to udpate this list
  58612. * @returns the list of color remap gradients
  58613. */
  58614. BaseParticleSystem.prototype.getColorRemapGradients = function () {
  58615. return this._colorRemapGradients;
  58616. };
  58617. /**
  58618. * Gets the current list of alpha remap gradients.
  58619. * You must use addAlphaRemapGradient and removeAlphaRemapGradient to udpate this list
  58620. * @returns the list of alpha remap gradients
  58621. */
  58622. BaseParticleSystem.prototype.getAlphaRemapGradients = function () {
  58623. return this._alphaRemapGradients;
  58624. };
  58625. /**
  58626. * Gets the current list of life time gradients.
  58627. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  58628. * @returns the list of life time gradients
  58629. */
  58630. BaseParticleSystem.prototype.getLifeTimeGradients = function () {
  58631. return this._lifeTimeGradients;
  58632. };
  58633. /**
  58634. * Gets the current list of angular speed gradients.
  58635. * You must use addAngularSpeedGradient and removeAngularSpeedGradient to udpate this list
  58636. * @returns the list of angular speed gradients
  58637. */
  58638. BaseParticleSystem.prototype.getAngularSpeedGradients = function () {
  58639. return this._angularSpeedGradients;
  58640. };
  58641. /**
  58642. * Gets the current list of velocity gradients.
  58643. * You must use addVelocityGradient and removeVelocityGradient to udpate this list
  58644. * @returns the list of velocity gradients
  58645. */
  58646. BaseParticleSystem.prototype.getVelocityGradients = function () {
  58647. return this._velocityGradients;
  58648. };
  58649. /**
  58650. * Gets the current list of start size gradients.
  58651. * You must use addStartSizeGradient and removeStartSizeGradient to udpate this list
  58652. * @returns the list of start size gradients
  58653. */
  58654. BaseParticleSystem.prototype.getStartSizeGradients = function () {
  58655. return this._startSizeGradients;
  58656. };
  58657. /**
  58658. * Gets the current list of emit rate gradients.
  58659. * You must use addEmitRateGradient and removeEmitRateGradient to udpate this list
  58660. * @returns the list of emit rate gradients
  58661. */
  58662. BaseParticleSystem.prototype.getEmitRateGradients = function () {
  58663. return this._emitRateGradients;
  58664. };
  58665. Object.defineProperty(BaseParticleSystem.prototype, "direction1", {
  58666. /**
  58667. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58668. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58669. */
  58670. get: function () {
  58671. if (this.particleEmitterType.direction1) {
  58672. return this.particleEmitterType.direction1;
  58673. }
  58674. return BABYLON.Vector3.Zero();
  58675. },
  58676. set: function (value) {
  58677. if (this.particleEmitterType.direction1) {
  58678. this.particleEmitterType.direction1 = value;
  58679. }
  58680. },
  58681. enumerable: true,
  58682. configurable: true
  58683. });
  58684. Object.defineProperty(BaseParticleSystem.prototype, "direction2", {
  58685. /**
  58686. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  58687. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58688. */
  58689. get: function () {
  58690. if (this.particleEmitterType.direction2) {
  58691. return this.particleEmitterType.direction2;
  58692. }
  58693. return BABYLON.Vector3.Zero();
  58694. },
  58695. set: function (value) {
  58696. if (this.particleEmitterType.direction2) {
  58697. this.particleEmitterType.direction2 = value;
  58698. }
  58699. },
  58700. enumerable: true,
  58701. configurable: true
  58702. });
  58703. Object.defineProperty(BaseParticleSystem.prototype, "minEmitBox", {
  58704. /**
  58705. * 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.
  58706. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58707. */
  58708. get: function () {
  58709. if (this.particleEmitterType.minEmitBox) {
  58710. return this.particleEmitterType.minEmitBox;
  58711. }
  58712. return BABYLON.Vector3.Zero();
  58713. },
  58714. set: function (value) {
  58715. if (this.particleEmitterType.minEmitBox) {
  58716. this.particleEmitterType.minEmitBox = value;
  58717. }
  58718. },
  58719. enumerable: true,
  58720. configurable: true
  58721. });
  58722. Object.defineProperty(BaseParticleSystem.prototype, "maxEmitBox", {
  58723. /**
  58724. * 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.
  58725. * This only works when particleEmitterTyps is a BoxParticleEmitter
  58726. */
  58727. get: function () {
  58728. if (this.particleEmitterType.maxEmitBox) {
  58729. return this.particleEmitterType.maxEmitBox;
  58730. }
  58731. return BABYLON.Vector3.Zero();
  58732. },
  58733. set: function (value) {
  58734. if (this.particleEmitterType.maxEmitBox) {
  58735. this.particleEmitterType.maxEmitBox = value;
  58736. }
  58737. },
  58738. enumerable: true,
  58739. configurable: true
  58740. });
  58741. Object.defineProperty(BaseParticleSystem.prototype, "isBillboardBased", {
  58742. /**
  58743. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  58744. */
  58745. get: function () {
  58746. return this._isBillboardBased;
  58747. },
  58748. set: function (value) {
  58749. if (this._isBillboardBased === value) {
  58750. return;
  58751. }
  58752. this._isBillboardBased = value;
  58753. this._reset();
  58754. },
  58755. enumerable: true,
  58756. configurable: true
  58757. });
  58758. Object.defineProperty(BaseParticleSystem.prototype, "imageProcessingConfiguration", {
  58759. /**
  58760. * Gets the image processing configuration used either in this material.
  58761. */
  58762. get: function () {
  58763. return this._imageProcessingConfiguration;
  58764. },
  58765. /**
  58766. * Sets the Default image processing configuration used either in the this material.
  58767. *
  58768. * If sets to null, the scene one is in use.
  58769. */
  58770. set: function (value) {
  58771. this._attachImageProcessingConfiguration(value);
  58772. },
  58773. enumerable: true,
  58774. configurable: true
  58775. });
  58776. /**
  58777. * Attaches a new image processing configuration to the Standard Material.
  58778. * @param configuration
  58779. */
  58780. BaseParticleSystem.prototype._attachImageProcessingConfiguration = function (configuration) {
  58781. if (configuration === this._imageProcessingConfiguration) {
  58782. return;
  58783. }
  58784. // Pick the scene configuration if needed.
  58785. if (!configuration) {
  58786. this._imageProcessingConfiguration = this._scene.imageProcessingConfiguration;
  58787. }
  58788. else {
  58789. this._imageProcessingConfiguration = configuration;
  58790. }
  58791. };
  58792. /** @hidden */
  58793. BaseParticleSystem.prototype._reset = function () {
  58794. };
  58795. /** @hidden */
  58796. BaseParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  58797. if (!gradients) {
  58798. return this;
  58799. }
  58800. var index = 0;
  58801. for (var _i = 0, gradients_1 = gradients; _i < gradients_1.length; _i++) {
  58802. var valueGradient = gradients_1[_i];
  58803. if (valueGradient.gradient === gradient) {
  58804. gradients.splice(index, 1);
  58805. break;
  58806. }
  58807. index++;
  58808. }
  58809. if (texture) {
  58810. texture.dispose();
  58811. }
  58812. return this;
  58813. };
  58814. /**
  58815. * Creates a Point Emitter for the particle system (emits directly from the emitter position)
  58816. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58817. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58818. * @returns the emitter
  58819. */
  58820. BaseParticleSystem.prototype.createPointEmitter = function (direction1, direction2) {
  58821. var particleEmitter = new BABYLON.PointParticleEmitter();
  58822. particleEmitter.direction1 = direction1;
  58823. particleEmitter.direction2 = direction2;
  58824. this.particleEmitterType = particleEmitter;
  58825. return particleEmitter;
  58826. };
  58827. /**
  58828. * Creates a Hemisphere Emitter for the particle system (emits along the hemisphere radius)
  58829. * @param radius The radius of the hemisphere to emit from
  58830. * @param radiusRange The range of the hemisphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58831. * @returns the emitter
  58832. */
  58833. BaseParticleSystem.prototype.createHemisphericEmitter = function (radius, radiusRange) {
  58834. if (radius === void 0) { radius = 1; }
  58835. if (radiusRange === void 0) { radiusRange = 1; }
  58836. var particleEmitter = new BABYLON.HemisphericParticleEmitter(radius, radiusRange);
  58837. this.particleEmitterType = particleEmitter;
  58838. return particleEmitter;
  58839. };
  58840. /**
  58841. * Creates a Sphere Emitter for the particle system (emits along the sphere radius)
  58842. * @param radius The radius of the sphere to emit from
  58843. * @param radiusRange The range of the sphere to emit from [0-1] 0 Surface Only, 1 Entire Radius
  58844. * @returns the emitter
  58845. */
  58846. BaseParticleSystem.prototype.createSphereEmitter = function (radius, radiusRange) {
  58847. if (radius === void 0) { radius = 1; }
  58848. if (radiusRange === void 0) { radiusRange = 1; }
  58849. var particleEmitter = new BABYLON.SphereParticleEmitter(radius, radiusRange);
  58850. this.particleEmitterType = particleEmitter;
  58851. return particleEmitter;
  58852. };
  58853. /**
  58854. * Creates a Directed Sphere Emitter for the particle system (emits between direction1 and direction2)
  58855. * @param radius The radius of the sphere to emit from
  58856. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  58857. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  58858. * @returns the emitter
  58859. */
  58860. BaseParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  58861. if (radius === void 0) { radius = 1; }
  58862. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58863. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58864. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  58865. this.particleEmitterType = particleEmitter;
  58866. return particleEmitter;
  58867. };
  58868. /**
  58869. * Creates a Cylinder Emitter for the particle system (emits from the cylinder to the particle position)
  58870. * @param radius The radius of the emission cylinder
  58871. * @param height The height of the emission cylinder
  58872. * @param radiusRange The range of emission [0-1] 0 Surface only, 1 Entire Radius
  58873. * @param directionRandomizer How much to randomize the particle direction [0-1]
  58874. * @returns the emitter
  58875. */
  58876. BaseParticleSystem.prototype.createCylinderEmitter = function (radius, height, radiusRange, directionRandomizer) {
  58877. if (radius === void 0) { radius = 1; }
  58878. if (height === void 0) { height = 1; }
  58879. if (radiusRange === void 0) { radiusRange = 1; }
  58880. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  58881. var particleEmitter = new BABYLON.CylinderParticleEmitter(radius, height, radiusRange, directionRandomizer);
  58882. this.particleEmitterType = particleEmitter;
  58883. return particleEmitter;
  58884. };
  58885. /**
  58886. * Creates a Directed Cylinder Emitter for the particle system (emits between direction1 and direction2)
  58887. * @param radius The radius of the cylinder to emit from
  58888. * @param height The height of the emission cylinder
  58889. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  58890. * @param direction1 Particles are emitted between the direction1 and direction2 from within the cylinder
  58891. * @param direction2 Particles are emitted between the direction1 and direction2 from within the cylinder
  58892. * @returns the emitter
  58893. */
  58894. BaseParticleSystem.prototype.createDirectedCylinderEmitter = function (radius, height, radiusRange, direction1, direction2) {
  58895. if (radius === void 0) { radius = 1; }
  58896. if (height === void 0) { height = 1; }
  58897. if (radiusRange === void 0) { radiusRange = 1; }
  58898. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  58899. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  58900. var particleEmitter = new BABYLON.CylinderDirectedParticleEmitter(radius, height, radiusRange, direction1, direction2);
  58901. this.particleEmitterType = particleEmitter;
  58902. return particleEmitter;
  58903. };
  58904. /**
  58905. * Creates a Cone Emitter for the particle system (emits from the cone to the particle position)
  58906. * @param radius The radius of the cone to emit from
  58907. * @param angle The base angle of the cone
  58908. * @returns the emitter
  58909. */
  58910. BaseParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  58911. if (radius === void 0) { radius = 1; }
  58912. if (angle === void 0) { angle = Math.PI / 4; }
  58913. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  58914. this.particleEmitterType = particleEmitter;
  58915. return particleEmitter;
  58916. };
  58917. /**
  58918. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  58919. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  58920. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  58921. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58922. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  58923. * @returns the emitter
  58924. */
  58925. BaseParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  58926. var particleEmitter = new BABYLON.BoxParticleEmitter();
  58927. this.particleEmitterType = particleEmitter;
  58928. this.direction1 = direction1;
  58929. this.direction2 = direction2;
  58930. this.minEmitBox = minEmitBox;
  58931. this.maxEmitBox = maxEmitBox;
  58932. return particleEmitter;
  58933. };
  58934. /**
  58935. * Source color is added to the destination color without alpha affecting the result
  58936. */
  58937. BaseParticleSystem.BLENDMODE_ONEONE = 0;
  58938. /**
  58939. * Blend current color and particle color using particle’s alpha
  58940. */
  58941. BaseParticleSystem.BLENDMODE_STANDARD = 1;
  58942. /**
  58943. * Add current color and particle color multiplied by particle’s alpha
  58944. */
  58945. BaseParticleSystem.BLENDMODE_ADD = 2;
  58946. /**
  58947. * Multiply current color with particle color
  58948. */
  58949. BaseParticleSystem.BLENDMODE_MULTIPLY = 3;
  58950. /**
  58951. * Multiply current color with particle color then add current color and particle color multiplied by particle’s alpha
  58952. */
  58953. BaseParticleSystem.BLENDMODE_MULTIPLYADD = 4;
  58954. return BaseParticleSystem;
  58955. }());
  58956. BABYLON.BaseParticleSystem = BaseParticleSystem;
  58957. })(BABYLON || (BABYLON = {}));
  58958. //# sourceMappingURL=babylon.baseParticleSystem.js.map
  58959. var BABYLON;
  58960. (function (BABYLON) {
  58961. /**
  58962. * This represents a particle system in Babylon.
  58963. * 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.
  58964. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  58965. * @example https://doc.babylonjs.com/babylon101/particles
  58966. */
  58967. var ParticleSystem = /** @class */ (function (_super) {
  58968. __extends(ParticleSystem, _super);
  58969. /**
  58970. * Instantiates a particle system.
  58971. * 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.
  58972. * @param name The name of the particle system
  58973. * @param capacity The max number of particles alive at the same time
  58974. * @param scene The scene the particle system belongs to
  58975. * @param customEffect a custom effect used to change the way particles are rendered by default
  58976. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  58977. * @param epsilon Offset used to render the particles
  58978. */
  58979. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  58980. if (customEffect === void 0) { customEffect = null; }
  58981. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  58982. if (epsilon === void 0) { epsilon = 0.01; }
  58983. var _this = _super.call(this, name) || this;
  58984. /**
  58985. * @hidden
  58986. */
  58987. _this._inheritedVelocityOffset = new BABYLON.Vector3();
  58988. /**
  58989. * An event triggered when the system is disposed
  58990. */
  58991. _this.onDisposeObservable = new BABYLON.Observable();
  58992. _this._particles = new Array();
  58993. _this._stockParticles = new Array();
  58994. _this._newPartsExcess = 0;
  58995. _this._vertexBuffers = {};
  58996. _this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  58997. _this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  58998. _this._scaledDirection = BABYLON.Vector3.Zero();
  58999. _this._scaledGravity = BABYLON.Vector3.Zero();
  59000. _this._currentRenderId = -1;
  59001. _this._useInstancing = false;
  59002. _this._started = false;
  59003. _this._stopped = false;
  59004. _this._actualFrame = 0;
  59005. /** @hidden */
  59006. _this._currentEmitRate1 = 0;
  59007. /** @hidden */
  59008. _this._currentEmitRate2 = 0;
  59009. /** @hidden */
  59010. _this._currentStartSize1 = 0;
  59011. /** @hidden */
  59012. _this._currentStartSize2 = 0;
  59013. _this._rawTextureWidth = 256;
  59014. _this._useRampGradients = false;
  59015. /**
  59016. * @hidden
  59017. * If the particle systems emitter should be disposed when the particle system is disposed
  59018. */
  59019. _this._disposeEmitterOnDispose = false;
  59020. // start of sub system methods
  59021. /**
  59022. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  59023. * Its lifetime will start back at 0.
  59024. */
  59025. _this.recycleParticle = function (particle) {
  59026. // move particle from activeParticle list to stock particles
  59027. var lastParticle = _this._particles.pop();
  59028. if (lastParticle !== particle) {
  59029. lastParticle.copyTo(particle);
  59030. }
  59031. _this._stockParticles.push(lastParticle);
  59032. };
  59033. _this._createParticle = function () {
  59034. var particle;
  59035. if (_this._stockParticles.length !== 0) {
  59036. particle = _this._stockParticles.pop();
  59037. particle._reset();
  59038. }
  59039. else {
  59040. particle = new BABYLON.Particle(_this);
  59041. }
  59042. // Attach emitters
  59043. if (_this._subEmitters && _this._subEmitters.length > 0) {
  59044. var subEmitters = _this._subEmitters[Math.floor(Math.random() * _this._subEmitters.length)];
  59045. particle._attachedSubEmitters = [];
  59046. subEmitters.forEach(function (subEmitter) {
  59047. if (subEmitter.type === BABYLON.SubEmitterType.ATTACHED) {
  59048. var newEmitter = subEmitter.clone();
  59049. particle._attachedSubEmitters.push(newEmitter);
  59050. newEmitter.particleSystem.start();
  59051. }
  59052. });
  59053. }
  59054. return particle;
  59055. };
  59056. _this._emitFromParticle = function (particle) {
  59057. if (!_this._subEmitters || _this._subEmitters.length === 0) {
  59058. return;
  59059. }
  59060. var templateIndex = Math.floor(Math.random() * _this._subEmitters.length);
  59061. _this._subEmitters[templateIndex].forEach(function (subEmitter) {
  59062. if (subEmitter.type === BABYLON.SubEmitterType.END) {
  59063. var subSystem = subEmitter.clone();
  59064. particle._inheritParticleInfoToSubEmitter(subSystem);
  59065. subSystem.particleSystem._rootParticleSystem = _this;
  59066. _this.activeSubSystems.push(subSystem.particleSystem);
  59067. subSystem.particleSystem.start();
  59068. }
  59069. });
  59070. };
  59071. _this._capacity = capacity;
  59072. _this._epsilon = epsilon;
  59073. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  59074. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59075. // Setup the default processing configuration to the scene.
  59076. _this._attachImageProcessingConfiguration(null);
  59077. _this._customEffect = customEffect;
  59078. _this._scene.particleSystems.push(_this);
  59079. _this._useInstancing = _this._scene.getEngine().getCaps().instancedArrays;
  59080. _this._createIndexBuffer();
  59081. _this._createVertexBuffers();
  59082. // Default emitter type
  59083. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  59084. // Update
  59085. _this.updateFunction = function (particles) {
  59086. var noiseTextureSize = null;
  59087. var noiseTextureData = null;
  59088. if (_this.noiseTexture) { // We need to get texture data back to CPU
  59089. noiseTextureSize = _this.noiseTexture.getSize();
  59090. noiseTextureData = (_this.noiseTexture.getContent());
  59091. }
  59092. var _loop_1 = function () {
  59093. particle = particles[index];
  59094. var scaledUpdateSpeed = _this._scaledUpdateSpeed;
  59095. var previousAge = particle.age;
  59096. particle.age += scaledUpdateSpeed;
  59097. // Evaluate step to death
  59098. if (particle.age > particle.lifeTime) {
  59099. var diff = particle.age - previousAge;
  59100. var oldDiff = particle.lifeTime - previousAge;
  59101. scaledUpdateSpeed = (oldDiff * scaledUpdateSpeed) / diff;
  59102. particle.age = particle.lifeTime;
  59103. }
  59104. var ratio = particle.age / particle.lifeTime;
  59105. // Color
  59106. if (_this._colorGradients && _this._colorGradients.length > 0) {
  59107. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  59108. if (currentGradient !== particle._currentColorGradient) {
  59109. particle._currentColor1.copyFrom(particle._currentColor2);
  59110. nextGradient.getColorToRef(particle._currentColor2);
  59111. particle._currentColorGradient = currentGradient;
  59112. }
  59113. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  59114. });
  59115. }
  59116. else {
  59117. particle.colorStep.scaleToRef(scaledUpdateSpeed, _this._scaledColorStep);
  59118. particle.color.addInPlace(_this._scaledColorStep);
  59119. if (particle.color.a < 0) {
  59120. particle.color.a = 0;
  59121. }
  59122. }
  59123. // Angular speed
  59124. if (_this._angularSpeedGradients && _this._angularSpeedGradients.length > 0) {
  59125. BABYLON.Tools.GetCurrentGradient(ratio, _this._angularSpeedGradients, function (currentGradient, nextGradient, scale) {
  59126. if (currentGradient !== particle._currentAngularSpeedGradient) {
  59127. particle._currentAngularSpeed1 = particle._currentAngularSpeed2;
  59128. particle._currentAngularSpeed2 = nextGradient.getFactor();
  59129. particle._currentAngularSpeedGradient = currentGradient;
  59130. }
  59131. particle.angularSpeed = BABYLON.Scalar.Lerp(particle._currentAngularSpeed1, particle._currentAngularSpeed2, scale);
  59132. });
  59133. }
  59134. particle.angle += particle.angularSpeed * scaledUpdateSpeed;
  59135. // Direction
  59136. var directionScale = scaledUpdateSpeed;
  59137. /// Velocity
  59138. if (_this._velocityGradients && _this._velocityGradients.length > 0) {
  59139. BABYLON.Tools.GetCurrentGradient(ratio, _this._velocityGradients, function (currentGradient, nextGradient, scale) {
  59140. if (currentGradient !== particle._currentVelocityGradient) {
  59141. particle._currentVelocity1 = particle._currentVelocity2;
  59142. particle._currentVelocity2 = nextGradient.getFactor();
  59143. particle._currentVelocityGradient = currentGradient;
  59144. }
  59145. directionScale *= BABYLON.Scalar.Lerp(particle._currentVelocity1, particle._currentVelocity2, scale);
  59146. });
  59147. }
  59148. particle.direction.scaleToRef(directionScale, _this._scaledDirection);
  59149. /// Limit velocity
  59150. if (_this._limitVelocityGradients && _this._limitVelocityGradients.length > 0) {
  59151. BABYLON.Tools.GetCurrentGradient(ratio, _this._limitVelocityGradients, function (currentGradient, nextGradient, scale) {
  59152. if (currentGradient !== particle._currentLimitVelocityGradient) {
  59153. particle._currentLimitVelocity1 = particle._currentLimitVelocity2;
  59154. particle._currentLimitVelocity2 = nextGradient.getFactor();
  59155. particle._currentLimitVelocityGradient = currentGradient;
  59156. }
  59157. var limitVelocity = BABYLON.Scalar.Lerp(particle._currentLimitVelocity1, particle._currentLimitVelocity2, scale);
  59158. var currentVelocity = particle.direction.length();
  59159. if (currentVelocity > limitVelocity) {
  59160. particle.direction.scaleInPlace(_this.limitVelocityDamping);
  59161. }
  59162. });
  59163. }
  59164. /// Drag
  59165. if (_this._dragGradients && _this._dragGradients.length > 0) {
  59166. BABYLON.Tools.GetCurrentGradient(ratio, _this._dragGradients, function (currentGradient, nextGradient, scale) {
  59167. if (currentGradient !== particle._currentDragGradient) {
  59168. particle._currentDrag1 = particle._currentDrag2;
  59169. particle._currentDrag2 = nextGradient.getFactor();
  59170. particle._currentDragGradient = currentGradient;
  59171. }
  59172. var drag = BABYLON.Scalar.Lerp(particle._currentDrag1, particle._currentDrag2, scale);
  59173. _this._scaledDirection.scaleInPlace(1.0 - drag);
  59174. });
  59175. }
  59176. particle.position.addInPlace(_this._scaledDirection);
  59177. // Noise
  59178. if (noiseTextureData && noiseTextureSize) {
  59179. var fetchedColorR = _this._fetchR(particle._randomNoiseCoordinates1.x, particle._randomNoiseCoordinates1.y, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59180. var fetchedColorG = _this._fetchR(particle._randomNoiseCoordinates1.z, particle._randomNoiseCoordinates2.x, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59181. var fetchedColorB = _this._fetchR(particle._randomNoiseCoordinates2.y, particle._randomNoiseCoordinates2.z, noiseTextureSize.width, noiseTextureSize.height, noiseTextureData);
  59182. var force = BABYLON.Tmp.Vector3[0];
  59183. var scaledForce = BABYLON.Tmp.Vector3[1];
  59184. force.copyFromFloats((2 * fetchedColorR - 1) * _this.noiseStrength.x, (2 * fetchedColorG - 1) * _this.noiseStrength.y, (2 * fetchedColorB - 1) * _this.noiseStrength.z);
  59185. force.scaleToRef(scaledUpdateSpeed, scaledForce);
  59186. particle.direction.addInPlace(scaledForce);
  59187. }
  59188. // Gravity
  59189. _this.gravity.scaleToRef(scaledUpdateSpeed, _this._scaledGravity);
  59190. particle.direction.addInPlace(_this._scaledGravity);
  59191. // Size
  59192. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  59193. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  59194. if (currentGradient !== particle._currentSizeGradient) {
  59195. particle._currentSize1 = particle._currentSize2;
  59196. particle._currentSize2 = nextGradient.getFactor();
  59197. particle._currentSizeGradient = currentGradient;
  59198. }
  59199. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  59200. });
  59201. }
  59202. // Remap data
  59203. if (_this._useRampGradients) {
  59204. if (_this._colorRemapGradients && _this._colorRemapGradients.length > 0) {
  59205. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorRemapGradients, function (currentGradient, nextGradient, scale) {
  59206. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59207. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59208. particle.remapData.x = min;
  59209. particle.remapData.y = max - min;
  59210. });
  59211. }
  59212. if (_this._alphaRemapGradients && _this._alphaRemapGradients.length > 0) {
  59213. BABYLON.Tools.GetCurrentGradient(ratio, _this._alphaRemapGradients, function (currentGradient, nextGradient, scale) {
  59214. var min = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  59215. var max = BABYLON.Scalar.Lerp(currentGradient.factor2, nextGradient.factor2, scale);
  59216. particle.remapData.z = min;
  59217. particle.remapData.w = max - min;
  59218. });
  59219. }
  59220. }
  59221. if (_this._isAnimationSheetEnabled) {
  59222. particle.updateCellIndex();
  59223. }
  59224. // Update the position of the attached sub-emitters to match their attached particle
  59225. particle._inheritParticleInfoToSubEmitters();
  59226. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  59227. _this._emitFromParticle(particle);
  59228. if (particle._attachedSubEmitters) {
  59229. particle._attachedSubEmitters.forEach(function (subEmitter) {
  59230. subEmitter.particleSystem.disposeOnStop = true;
  59231. subEmitter.particleSystem.stop();
  59232. });
  59233. particle._attachedSubEmitters = null;
  59234. }
  59235. _this.recycleParticle(particle);
  59236. index--;
  59237. return "continue";
  59238. }
  59239. };
  59240. var particle;
  59241. for (var index = 0; index < particles.length; index++) {
  59242. _loop_1();
  59243. }
  59244. };
  59245. return _this;
  59246. }
  59247. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  59248. /**
  59249. * Sets a callback that will be triggered when the system is disposed
  59250. */
  59251. set: function (callback) {
  59252. if (this._onDisposeObserver) {
  59253. this.onDisposeObservable.remove(this._onDisposeObserver);
  59254. }
  59255. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  59256. },
  59257. enumerable: true,
  59258. configurable: true
  59259. });
  59260. Object.defineProperty(ParticleSystem.prototype, "useRampGradients", {
  59261. /** Gets or sets a boolean indicating that ramp gradients must be used
  59262. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  59263. */
  59264. get: function () {
  59265. return this._useRampGradients;
  59266. },
  59267. set: function (value) {
  59268. if (this._useRampGradients === value) {
  59269. return;
  59270. }
  59271. this._useRampGradients = value;
  59272. this._resetEffect();
  59273. },
  59274. enumerable: true,
  59275. configurable: true
  59276. });
  59277. Object.defineProperty(ParticleSystem.prototype, "particles", {
  59278. //end of Sub-emitter
  59279. /**
  59280. * Gets the current list of active particles
  59281. */
  59282. get: function () {
  59283. return this._particles;
  59284. },
  59285. enumerable: true,
  59286. configurable: true
  59287. });
  59288. /**
  59289. * Returns the string "ParticleSystem"
  59290. * @returns a string containing the class name
  59291. */
  59292. ParticleSystem.prototype.getClassName = function () {
  59293. return "ParticleSystem";
  59294. };
  59295. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  59296. var newGradient = new BABYLON.FactorGradient();
  59297. newGradient.gradient = gradient;
  59298. newGradient.factor1 = factor;
  59299. newGradient.factor2 = factor2;
  59300. factorGradients.push(newGradient);
  59301. factorGradients.sort(function (a, b) {
  59302. if (a.gradient < b.gradient) {
  59303. return -1;
  59304. }
  59305. else if (a.gradient > b.gradient) {
  59306. return 1;
  59307. }
  59308. return 0;
  59309. });
  59310. };
  59311. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  59312. if (!factorGradients) {
  59313. return;
  59314. }
  59315. var index = 0;
  59316. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  59317. var factorGradient = factorGradients_1[_i];
  59318. if (factorGradient.gradient === gradient) {
  59319. factorGradients.splice(index, 1);
  59320. break;
  59321. }
  59322. index++;
  59323. }
  59324. };
  59325. /**
  59326. * Adds a new life time gradient
  59327. * @param gradient defines the gradient to use (between 0 and 1)
  59328. * @param factor defines the life time factor to affect to the specified gradient
  59329. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59330. * @returns the current particle system
  59331. */
  59332. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  59333. if (!this._lifeTimeGradients) {
  59334. this._lifeTimeGradients = [];
  59335. }
  59336. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  59337. return this;
  59338. };
  59339. /**
  59340. * Remove a specific life time gradient
  59341. * @param gradient defines the gradient to remove
  59342. * @returns the current particle system
  59343. */
  59344. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  59345. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  59346. return this;
  59347. };
  59348. /**
  59349. * Adds a new size gradient
  59350. * @param gradient defines the gradient to use (between 0 and 1)
  59351. * @param factor defines the size factor to affect to the specified gradient
  59352. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59353. * @returns the current particle system
  59354. */
  59355. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  59356. if (!this._sizeGradients) {
  59357. this._sizeGradients = [];
  59358. }
  59359. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  59360. return this;
  59361. };
  59362. /**
  59363. * Remove a specific size gradient
  59364. * @param gradient defines the gradient to remove
  59365. * @returns the current particle system
  59366. */
  59367. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  59368. this._removeFactorGradient(this._sizeGradients, gradient);
  59369. return this;
  59370. };
  59371. /**
  59372. * Adds a new color remap gradient
  59373. * @param gradient defines the gradient to use (between 0 and 1)
  59374. * @param min defines the color remap minimal range
  59375. * @param max defines the color remap maximal range
  59376. * @returns the current particle system
  59377. */
  59378. ParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  59379. if (!this._colorRemapGradients) {
  59380. this._colorRemapGradients = [];
  59381. }
  59382. this._addFactorGradient(this._colorRemapGradients, gradient, min, max);
  59383. return this;
  59384. };
  59385. /**
  59386. * Remove a specific color remap gradient
  59387. * @param gradient defines the gradient to remove
  59388. * @returns the current particle system
  59389. */
  59390. ParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  59391. this._removeFactorGradient(this._colorRemapGradients, gradient);
  59392. return this;
  59393. };
  59394. /**
  59395. * Adds a new alpha remap gradient
  59396. * @param gradient defines the gradient to use (between 0 and 1)
  59397. * @param min defines the alpha remap minimal range
  59398. * @param max defines the alpha remap maximal range
  59399. * @returns the current particle system
  59400. */
  59401. ParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  59402. if (!this._alphaRemapGradients) {
  59403. this._alphaRemapGradients = [];
  59404. }
  59405. this._addFactorGradient(this._alphaRemapGradients, gradient, min, max);
  59406. return this;
  59407. };
  59408. /**
  59409. * Remove a specific alpha remap gradient
  59410. * @param gradient defines the gradient to remove
  59411. * @returns the current particle system
  59412. */
  59413. ParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  59414. this._removeFactorGradient(this._alphaRemapGradients, gradient);
  59415. return this;
  59416. };
  59417. /**
  59418. * Adds a new angular speed gradient
  59419. * @param gradient defines the gradient to use (between 0 and 1)
  59420. * @param factor defines the angular speed to affect to the specified gradient
  59421. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59422. * @returns the current particle system
  59423. */
  59424. ParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor, factor2) {
  59425. if (!this._angularSpeedGradients) {
  59426. this._angularSpeedGradients = [];
  59427. }
  59428. this._addFactorGradient(this._angularSpeedGradients, gradient, factor, factor2);
  59429. return this;
  59430. };
  59431. /**
  59432. * Remove a specific angular speed gradient
  59433. * @param gradient defines the gradient to remove
  59434. * @returns the current particle system
  59435. */
  59436. ParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  59437. this._removeFactorGradient(this._angularSpeedGradients, gradient);
  59438. return this;
  59439. };
  59440. /**
  59441. * Adds a new velocity gradient
  59442. * @param gradient defines the gradient to use (between 0 and 1)
  59443. * @param factor defines the velocity to affect to the specified gradient
  59444. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59445. * @returns the current particle system
  59446. */
  59447. ParticleSystem.prototype.addVelocityGradient = function (gradient, factor, factor2) {
  59448. if (!this._velocityGradients) {
  59449. this._velocityGradients = [];
  59450. }
  59451. this._addFactorGradient(this._velocityGradients, gradient, factor, factor2);
  59452. return this;
  59453. };
  59454. /**
  59455. * Remove a specific velocity gradient
  59456. * @param gradient defines the gradient to remove
  59457. * @returns the current particle system
  59458. */
  59459. ParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  59460. this._removeFactorGradient(this._velocityGradients, gradient);
  59461. return this;
  59462. };
  59463. /**
  59464. * Adds a new limit velocity gradient
  59465. * @param gradient defines the gradient to use (between 0 and 1)
  59466. * @param factor defines the limit velocity value to affect to the specified gradient
  59467. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59468. * @returns the current particle system
  59469. */
  59470. ParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor, factor2) {
  59471. if (!this._limitVelocityGradients) {
  59472. this._limitVelocityGradients = [];
  59473. }
  59474. this._addFactorGradient(this._limitVelocityGradients, gradient, factor, factor2);
  59475. return this;
  59476. };
  59477. /**
  59478. * Remove a specific limit velocity gradient
  59479. * @param gradient defines the gradient to remove
  59480. * @returns the current particle system
  59481. */
  59482. ParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  59483. this._removeFactorGradient(this._limitVelocityGradients, gradient);
  59484. return this;
  59485. };
  59486. /**
  59487. * Adds a new drag gradient
  59488. * @param gradient defines the gradient to use (between 0 and 1)
  59489. * @param factor defines the drag value to affect to the specified gradient
  59490. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59491. * @returns the current particle system
  59492. */
  59493. ParticleSystem.prototype.addDragGradient = function (gradient, factor, factor2) {
  59494. if (!this._dragGradients) {
  59495. this._dragGradients = [];
  59496. }
  59497. this._addFactorGradient(this._dragGradients, gradient, factor, factor2);
  59498. return this;
  59499. };
  59500. /**
  59501. * Remove a specific drag gradient
  59502. * @param gradient defines the gradient to remove
  59503. * @returns the current particle system
  59504. */
  59505. ParticleSystem.prototype.removeDragGradient = function (gradient) {
  59506. this._removeFactorGradient(this._dragGradients, gradient);
  59507. return this;
  59508. };
  59509. /**
  59510. * Adds a new emit rate gradient (please note that this will only work if you set the targetStopDuration property)
  59511. * @param gradient defines the gradient to use (between 0 and 1)
  59512. * @param factor defines the emit rate value to affect to the specified gradient
  59513. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59514. * @returns the current particle system
  59515. */
  59516. ParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  59517. if (!this._emitRateGradients) {
  59518. this._emitRateGradients = [];
  59519. }
  59520. this._addFactorGradient(this._emitRateGradients, gradient, factor, factor2);
  59521. return this;
  59522. };
  59523. /**
  59524. * Remove a specific emit rate gradient
  59525. * @param gradient defines the gradient to remove
  59526. * @returns the current particle system
  59527. */
  59528. ParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  59529. this._removeFactorGradient(this._emitRateGradients, gradient);
  59530. return this;
  59531. };
  59532. /**
  59533. * Adds a new start size gradient (please note that this will only work if you set the targetStopDuration property)
  59534. * @param gradient defines the gradient to use (between 0 and 1)
  59535. * @param factor defines the start size value to affect to the specified gradient
  59536. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  59537. * @returns the current particle system
  59538. */
  59539. ParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  59540. if (!this._startSizeGradients) {
  59541. this._startSizeGradients = [];
  59542. }
  59543. this._addFactorGradient(this._startSizeGradients, gradient, factor, factor2);
  59544. return this;
  59545. };
  59546. /**
  59547. * Remove a specific start size gradient
  59548. * @param gradient defines the gradient to remove
  59549. * @returns the current particle system
  59550. */
  59551. ParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  59552. this._removeFactorGradient(this._emitRateGradients, gradient);
  59553. return this;
  59554. };
  59555. ParticleSystem.prototype._createRampGradientTexture = function () {
  59556. if (!this._rampGradients || !this._rampGradients.length || this._rampGradientsTexture) {
  59557. return;
  59558. }
  59559. var data = new Uint8Array(this._rawTextureWidth * 4);
  59560. var tmpColor = BABYLON.Tmp.Color3[0];
  59561. for (var x = 0; x < this._rawTextureWidth; x++) {
  59562. var ratio = x / this._rawTextureWidth;
  59563. BABYLON.Tools.GetCurrentGradient(ratio, this._rampGradients, function (currentGradient, nextGradient, scale) {
  59564. BABYLON.Color3.LerpToRef(currentGradient.color, nextGradient.color, scale, tmpColor);
  59565. data[x * 4] = tmpColor.r * 255;
  59566. data[x * 4 + 1] = tmpColor.g * 255;
  59567. data[x * 4 + 2] = tmpColor.b * 255;
  59568. data[x * 4 + 3] = 255;
  59569. });
  59570. }
  59571. this._rampGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  59572. };
  59573. /**
  59574. * Gets the current list of ramp gradients.
  59575. * You must use addRampGradient and removeRampGradient to udpate this list
  59576. * @returns the list of ramp gradients
  59577. */
  59578. ParticleSystem.prototype.getRampGradients = function () {
  59579. return this._rampGradients;
  59580. };
  59581. /**
  59582. * Adds a new ramp gradient used to remap particle colors
  59583. * @param gradient defines the gradient to use (between 0 and 1)
  59584. * @param color defines the color to affect to the specified gradient
  59585. * @returns the current particle system
  59586. */
  59587. ParticleSystem.prototype.addRampGradient = function (gradient, color) {
  59588. if (!this._rampGradients) {
  59589. this._rampGradients = [];
  59590. }
  59591. var rampGradient = new BABYLON.Color3Gradient();
  59592. rampGradient.gradient = gradient;
  59593. rampGradient.color = color;
  59594. this._rampGradients.push(rampGradient);
  59595. this._rampGradients.sort(function (a, b) {
  59596. if (a.gradient < b.gradient) {
  59597. return -1;
  59598. }
  59599. else if (a.gradient > b.gradient) {
  59600. return 1;
  59601. }
  59602. return 0;
  59603. });
  59604. if (this._rampGradientsTexture) {
  59605. this._rampGradientsTexture.dispose();
  59606. this._rampGradientsTexture = null;
  59607. }
  59608. this._createRampGradientTexture();
  59609. return this;
  59610. };
  59611. /**
  59612. * Remove a specific ramp gradient
  59613. * @param gradient defines the gradient to remove
  59614. * @returns the current particle system
  59615. */
  59616. ParticleSystem.prototype.removeRampGradient = function (gradient) {
  59617. this._removeGradientAndTexture(gradient, this._rampGradients, this._rampGradientsTexture);
  59618. this._rampGradientsTexture = null;
  59619. if (this._rampGradients && this._rampGradients.length > 0) {
  59620. this._createRampGradientTexture();
  59621. }
  59622. return this;
  59623. };
  59624. /**
  59625. * Adds a new color gradient
  59626. * @param gradient defines the gradient to use (between 0 and 1)
  59627. * @param color1 defines the color to affect to the specified gradient
  59628. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  59629. * @returns this particle system
  59630. */
  59631. ParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  59632. if (!this._colorGradients) {
  59633. this._colorGradients = [];
  59634. }
  59635. var colorGradient = new BABYLON.ColorGradient();
  59636. colorGradient.gradient = gradient;
  59637. colorGradient.color1 = color1;
  59638. colorGradient.color2 = color2;
  59639. this._colorGradients.push(colorGradient);
  59640. this._colorGradients.sort(function (a, b) {
  59641. if (a.gradient < b.gradient) {
  59642. return -1;
  59643. }
  59644. else if (a.gradient > b.gradient) {
  59645. return 1;
  59646. }
  59647. return 0;
  59648. });
  59649. return this;
  59650. };
  59651. /**
  59652. * Remove a specific color gradient
  59653. * @param gradient defines the gradient to remove
  59654. * @returns this particle system
  59655. */
  59656. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  59657. if (!this._colorGradients) {
  59658. return this;
  59659. }
  59660. var index = 0;
  59661. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  59662. var colorGradient = _a[_i];
  59663. if (colorGradient.gradient === gradient) {
  59664. this._colorGradients.splice(index, 1);
  59665. break;
  59666. }
  59667. index++;
  59668. }
  59669. return this;
  59670. };
  59671. ParticleSystem.prototype._fetchR = function (u, v, width, height, pixels) {
  59672. u = Math.abs(u) * 0.5 + 0.5;
  59673. v = Math.abs(v) * 0.5 + 0.5;
  59674. var wrappedU = ((u * width) % width) | 0;
  59675. var wrappedV = ((v * height) % height) | 0;
  59676. var position = (wrappedU + wrappedV * width) * 4;
  59677. return pixels[position] / 255;
  59678. };
  59679. ParticleSystem.prototype._reset = function () {
  59680. this._resetEffect();
  59681. };
  59682. ParticleSystem.prototype._resetEffect = function () {
  59683. if (this._vertexBuffer) {
  59684. this._vertexBuffer.dispose();
  59685. this._vertexBuffer = null;
  59686. }
  59687. if (this._spriteBuffer) {
  59688. this._spriteBuffer.dispose();
  59689. this._spriteBuffer = null;
  59690. }
  59691. this._createVertexBuffers();
  59692. };
  59693. ParticleSystem.prototype._createVertexBuffers = function () {
  59694. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  59695. if (this._isAnimationSheetEnabled) {
  59696. this._vertexBufferSize += 1;
  59697. }
  59698. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59699. this._vertexBufferSize += 3;
  59700. }
  59701. if (this._useRampGradients) {
  59702. this._vertexBufferSize += 4;
  59703. }
  59704. var engine = this._scene.getEngine();
  59705. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  59706. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  59707. var dataOffset = 0;
  59708. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59709. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  59710. dataOffset += 3;
  59711. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59712. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  59713. dataOffset += 4;
  59714. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59715. this._vertexBuffers["angle"] = options;
  59716. dataOffset += 1;
  59717. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59718. this._vertexBuffers["size"] = size;
  59719. dataOffset += 2;
  59720. if (this._isAnimationSheetEnabled) {
  59721. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  59722. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  59723. dataOffset += 1;
  59724. }
  59725. if (!this._isBillboardBased || this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59726. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  59727. this._vertexBuffers["direction"] = directionBuffer;
  59728. dataOffset += 3;
  59729. }
  59730. if (this._useRampGradients) {
  59731. var rampDataBuffer = this._vertexBuffer.createVertexBuffer("remapData", dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  59732. this._vertexBuffers["remapData"] = rampDataBuffer;
  59733. dataOffset += 4;
  59734. }
  59735. var offsets;
  59736. if (this._useInstancing) {
  59737. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  59738. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  59739. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  59740. }
  59741. else {
  59742. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  59743. dataOffset += 2;
  59744. }
  59745. this._vertexBuffers["offset"] = offsets;
  59746. };
  59747. ParticleSystem.prototype._createIndexBuffer = function () {
  59748. if (this._useInstancing) {
  59749. return;
  59750. }
  59751. var indices = [];
  59752. var index = 0;
  59753. for (var count = 0; count < this._capacity; count++) {
  59754. indices.push(index);
  59755. indices.push(index + 1);
  59756. indices.push(index + 2);
  59757. indices.push(index);
  59758. indices.push(index + 2);
  59759. indices.push(index + 3);
  59760. index += 4;
  59761. }
  59762. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  59763. };
  59764. /**
  59765. * Gets the maximum number of particles active at the same time.
  59766. * @returns The max number of active particles.
  59767. */
  59768. ParticleSystem.prototype.getCapacity = function () {
  59769. return this._capacity;
  59770. };
  59771. /**
  59772. * Gets whether there are still active particles in the system.
  59773. * @returns True if it is alive, otherwise false.
  59774. */
  59775. ParticleSystem.prototype.isAlive = function () {
  59776. return this._alive;
  59777. };
  59778. /**
  59779. * Gets if the system has been started. (Note: this will still be true after stop is called)
  59780. * @returns True if it has been started, otherwise false.
  59781. */
  59782. ParticleSystem.prototype.isStarted = function () {
  59783. return this._started;
  59784. };
  59785. ParticleSystem.prototype._prepareSubEmitterInternalArray = function () {
  59786. var _this = this;
  59787. this._subEmitters = new Array();
  59788. if (this.subEmitters) {
  59789. this.subEmitters.forEach(function (subEmitter) {
  59790. if (subEmitter instanceof ParticleSystem) {
  59791. _this._subEmitters.push([new BABYLON.SubEmitter(subEmitter)]);
  59792. }
  59793. else if (subEmitter instanceof BABYLON.SubEmitter) {
  59794. _this._subEmitters.push([subEmitter]);
  59795. }
  59796. else if (subEmitter instanceof Array) {
  59797. _this._subEmitters.push(subEmitter);
  59798. }
  59799. });
  59800. }
  59801. };
  59802. /**
  59803. * Starts the particle system and begins to emit
  59804. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  59805. */
  59806. ParticleSystem.prototype.start = function (delay) {
  59807. var _this = this;
  59808. if (delay === void 0) { delay = this.startDelay; }
  59809. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  59810. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  59811. }
  59812. if (delay) {
  59813. setTimeout(function () {
  59814. _this.start(0);
  59815. }, delay);
  59816. return;
  59817. }
  59818. // Convert the subEmitters field to the constant type field _subEmitters
  59819. this._prepareSubEmitterInternalArray();
  59820. this._started = true;
  59821. this._stopped = false;
  59822. this._actualFrame = 0;
  59823. if (this._subEmitters && this._subEmitters.length != 0) {
  59824. this.activeSubSystems = new Array();
  59825. }
  59826. // Reset emit gradient so it acts the same on every start
  59827. if (this._emitRateGradients) {
  59828. if (this._emitRateGradients.length > 0) {
  59829. this._currentEmitRateGradient = this._emitRateGradients[0];
  59830. this._currentEmitRate1 = this._currentEmitRateGradient.getFactor();
  59831. this._currentEmitRate2 = this._currentEmitRate1;
  59832. }
  59833. if (this._emitRateGradients.length > 1) {
  59834. this._currentEmitRate2 = this._emitRateGradients[1].getFactor();
  59835. }
  59836. }
  59837. // Reset start size gradient so it acts the same on every start
  59838. if (this._startSizeGradients) {
  59839. if (this._startSizeGradients.length > 0) {
  59840. this._currentStartSizeGradient = this._startSizeGradients[0];
  59841. this._currentStartSize1 = this._currentStartSizeGradient.getFactor();
  59842. this._currentStartSize2 = this._currentStartSize1;
  59843. }
  59844. if (this._startSizeGradients.length > 1) {
  59845. this._currentStartSize2 = this._startSizeGradients[1].getFactor();
  59846. }
  59847. }
  59848. if (this.preWarmCycles) {
  59849. if (this.emitter instanceof BABYLON.AbstractMesh) {
  59850. this.emitter.computeWorldMatrix(true);
  59851. }
  59852. var noiseTextureAsProcedural_1 = this.noiseTexture;
  59853. if (noiseTextureAsProcedural_1 && noiseTextureAsProcedural_1.onGeneratedObservable) {
  59854. noiseTextureAsProcedural_1.onGeneratedObservable.addOnce(function () {
  59855. setTimeout(function () {
  59856. for (var index = 0; index < _this.preWarmCycles; index++) {
  59857. _this.animate(true);
  59858. noiseTextureAsProcedural_1.render();
  59859. }
  59860. });
  59861. });
  59862. }
  59863. else {
  59864. for (var index = 0; index < this.preWarmCycles; index++) {
  59865. this.animate(true);
  59866. }
  59867. }
  59868. }
  59869. // Animations
  59870. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  59871. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  59872. }
  59873. };
  59874. /**
  59875. * Stops the particle system.
  59876. * @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.
  59877. */
  59878. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  59879. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  59880. this._stopped = true;
  59881. if (stopSubEmitters) {
  59882. this._stopSubEmitters();
  59883. }
  59884. };
  59885. // animation sheet
  59886. /**
  59887. * Remove all active particles
  59888. */
  59889. ParticleSystem.prototype.reset = function () {
  59890. this._stockParticles = [];
  59891. this._particles = [];
  59892. };
  59893. /**
  59894. * @hidden (for internal use only)
  59895. */
  59896. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  59897. var offset = index * this._vertexBufferSize;
  59898. this._vertexData[offset++] = particle.position.x;
  59899. this._vertexData[offset++] = particle.position.y;
  59900. this._vertexData[offset++] = particle.position.z;
  59901. this._vertexData[offset++] = particle.color.r;
  59902. this._vertexData[offset++] = particle.color.g;
  59903. this._vertexData[offset++] = particle.color.b;
  59904. this._vertexData[offset++] = particle.color.a;
  59905. this._vertexData[offset++] = particle.angle;
  59906. this._vertexData[offset++] = particle.scale.x * particle.size;
  59907. this._vertexData[offset++] = particle.scale.y * particle.size;
  59908. if (this._isAnimationSheetEnabled) {
  59909. this._vertexData[offset++] = particle.cellIndex;
  59910. }
  59911. if (!this._isBillboardBased) {
  59912. if (particle._initialDirection) {
  59913. this._vertexData[offset++] = particle._initialDirection.x;
  59914. this._vertexData[offset++] = particle._initialDirection.y;
  59915. this._vertexData[offset++] = particle._initialDirection.z;
  59916. }
  59917. else {
  59918. this._vertexData[offset++] = particle.direction.x;
  59919. this._vertexData[offset++] = particle.direction.y;
  59920. this._vertexData[offset++] = particle.direction.z;
  59921. }
  59922. }
  59923. else if (this.billboardMode === ParticleSystem.BILLBOARDMODE_STRETCHED) {
  59924. this._vertexData[offset++] = particle.direction.x;
  59925. this._vertexData[offset++] = particle.direction.y;
  59926. this._vertexData[offset++] = particle.direction.z;
  59927. }
  59928. if (this._useRampGradients) {
  59929. this._vertexData[offset++] = particle.remapData.x;
  59930. this._vertexData[offset++] = particle.remapData.y;
  59931. this._vertexData[offset++] = particle.remapData.z;
  59932. this._vertexData[offset++] = particle.remapData.w;
  59933. }
  59934. if (!this._useInstancing) {
  59935. if (this._isAnimationSheetEnabled) {
  59936. if (offsetX === 0)
  59937. offsetX = this._epsilon;
  59938. else if (offsetX === 1)
  59939. offsetX = 1 - this._epsilon;
  59940. if (offsetY === 0)
  59941. offsetY = this._epsilon;
  59942. else if (offsetY === 1)
  59943. offsetY = 1 - this._epsilon;
  59944. }
  59945. this._vertexData[offset++] = offsetX;
  59946. this._vertexData[offset++] = offsetY;
  59947. }
  59948. };
  59949. ParticleSystem.prototype._stopSubEmitters = function () {
  59950. if (!this.activeSubSystems) {
  59951. return;
  59952. }
  59953. this.activeSubSystems.forEach(function (subSystem) {
  59954. subSystem.stop(true);
  59955. });
  59956. this.activeSubSystems = new Array();
  59957. };
  59958. ParticleSystem.prototype._removeFromRoot = function () {
  59959. if (!this._rootParticleSystem) {
  59960. return;
  59961. }
  59962. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  59963. if (index !== -1) {
  59964. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  59965. }
  59966. this._rootParticleSystem = null;
  59967. };
  59968. // End of sub system methods
  59969. ParticleSystem.prototype._update = function (newParticles) {
  59970. var _this = this;
  59971. // Update current
  59972. this._alive = this._particles.length > 0;
  59973. if (this.emitter.position) {
  59974. var emitterMesh = this.emitter;
  59975. this._emitterWorldMatrix = emitterMesh.getWorldMatrix();
  59976. }
  59977. else {
  59978. var emitterPosition = this.emitter;
  59979. this._emitterWorldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  59980. }
  59981. this.updateFunction(this._particles);
  59982. // Add new ones
  59983. var particle;
  59984. var _loop_2 = function () {
  59985. if (this_1._particles.length === this_1._capacity) {
  59986. return "break";
  59987. }
  59988. particle = this_1._createParticle();
  59989. this_1._particles.push(particle);
  59990. // Emitter
  59991. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  59992. if (this_1.startPositionFunction) {
  59993. this_1.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59994. }
  59995. else {
  59996. this_1.particleEmitterType.startPositionFunction(this_1._emitterWorldMatrix, particle.position, particle);
  59997. }
  59998. if (this_1.startDirectionFunction) {
  59999. this_1.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60000. }
  60001. else {
  60002. this_1.particleEmitterType.startDirectionFunction(this_1._emitterWorldMatrix, particle.direction, particle);
  60003. }
  60004. if (emitPower === 0) {
  60005. if (!particle._initialDirection) {
  60006. particle._initialDirection = particle.direction.clone();
  60007. }
  60008. else {
  60009. particle._initialDirection.copyFrom(particle.direction);
  60010. }
  60011. }
  60012. else {
  60013. particle._initialDirection = null;
  60014. }
  60015. particle.direction.scaleInPlace(emitPower);
  60016. // Life time
  60017. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  60018. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  60019. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  60020. var factorGradient1 = currentGradient;
  60021. var factorGradient2 = nextGradient;
  60022. var lifeTime1 = factorGradient1.getFactor();
  60023. var lifeTime2 = factorGradient2.getFactor();
  60024. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  60025. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  60026. });
  60027. }
  60028. else {
  60029. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  60030. }
  60031. // Size
  60032. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  60033. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  60034. }
  60035. else {
  60036. particle._currentSizeGradient = this_1._sizeGradients[0];
  60037. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  60038. particle.size = particle._currentSize1;
  60039. if (this_1._sizeGradients.length > 1) {
  60040. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  60041. }
  60042. else {
  60043. particle._currentSize2 = particle._currentSize1;
  60044. }
  60045. }
  60046. // Size and scale
  60047. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  60048. // Adjust scale by start size
  60049. if (this_1._startSizeGradients && this_1._startSizeGradients[0] && this_1.targetStopDuration) {
  60050. var ratio = this_1._actualFrame / this_1.targetStopDuration;
  60051. BABYLON.Tools.GetCurrentGradient(ratio, this_1._startSizeGradients, function (currentGradient, nextGradient, scale) {
  60052. if (currentGradient !== _this._currentStartSizeGradient) {
  60053. _this._currentStartSize1 = _this._currentStartSize2;
  60054. _this._currentStartSize2 = nextGradient.getFactor();
  60055. _this._currentStartSizeGradient = currentGradient;
  60056. }
  60057. var value = BABYLON.Scalar.Lerp(_this._currentStartSize1, _this._currentStartSize2, scale);
  60058. particle.scale.scaleInPlace(value);
  60059. });
  60060. }
  60061. // Angle
  60062. if (!this_1._angularSpeedGradients || this_1._angularSpeedGradients.length === 0) {
  60063. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  60064. }
  60065. else {
  60066. particle._currentAngularSpeedGradient = this_1._angularSpeedGradients[0];
  60067. particle.angularSpeed = particle._currentAngularSpeedGradient.getFactor();
  60068. particle._currentAngularSpeed1 = particle.angularSpeed;
  60069. if (this_1._angularSpeedGradients.length > 1) {
  60070. particle._currentAngularSpeed2 = this_1._angularSpeedGradients[1].getFactor();
  60071. }
  60072. else {
  60073. particle._currentAngularSpeed2 = particle._currentAngularSpeed1;
  60074. }
  60075. }
  60076. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  60077. // Velocity
  60078. if (this_1._velocityGradients && this_1._velocityGradients.length > 0) {
  60079. particle._currentVelocityGradient = this_1._velocityGradients[0];
  60080. particle._currentVelocity1 = particle._currentVelocityGradient.getFactor();
  60081. if (this_1._velocityGradients.length > 1) {
  60082. particle._currentVelocity2 = this_1._velocityGradients[1].getFactor();
  60083. }
  60084. else {
  60085. particle._currentVelocity2 = particle._currentVelocity1;
  60086. }
  60087. }
  60088. // Limit velocity
  60089. if (this_1._limitVelocityGradients && this_1._limitVelocityGradients.length > 0) {
  60090. particle._currentLimitVelocityGradient = this_1._limitVelocityGradients[0];
  60091. particle._currentLimitVelocity1 = particle._currentLimitVelocityGradient.getFactor();
  60092. if (this_1._limitVelocityGradients.length > 1) {
  60093. particle._currentLimitVelocity2 = this_1._limitVelocityGradients[1].getFactor();
  60094. }
  60095. else {
  60096. particle._currentLimitVelocity2 = particle._currentLimitVelocity1;
  60097. }
  60098. }
  60099. // Drag
  60100. if (this_1._dragGradients && this_1._dragGradients.length > 0) {
  60101. particle._currentDragGradient = this_1._dragGradients[0];
  60102. particle._currentDrag1 = particle._currentDragGradient.getFactor();
  60103. if (this_1._dragGradients.length > 1) {
  60104. particle._currentDrag2 = this_1._dragGradients[1].getFactor();
  60105. }
  60106. else {
  60107. particle._currentDrag2 = particle._currentDrag1;
  60108. }
  60109. }
  60110. // Color
  60111. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  60112. step = BABYLON.Scalar.RandomRange(0, 1.0);
  60113. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  60114. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  60115. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  60116. }
  60117. else {
  60118. particle._currentColorGradient = this_1._colorGradients[0];
  60119. particle._currentColorGradient.getColorToRef(particle.color);
  60120. particle._currentColor1.copyFrom(particle.color);
  60121. if (this_1._colorGradients.length > 1) {
  60122. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  60123. }
  60124. else {
  60125. particle._currentColor2.copyFrom(particle.color);
  60126. }
  60127. }
  60128. // Sheet
  60129. if (this_1._isAnimationSheetEnabled) {
  60130. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  60131. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  60132. }
  60133. // Inherited Velocity
  60134. particle.direction.addInPlace(this_1._inheritedVelocityOffset);
  60135. // Ramp
  60136. if (this_1._useRampGradients) {
  60137. particle.remapData = new BABYLON.Vector4(0, 1, 0, 1);
  60138. }
  60139. // Noise texture coordinates
  60140. if (this_1.noiseTexture) {
  60141. if (particle._randomNoiseCoordinates1) {
  60142. particle._randomNoiseCoordinates1.copyFromFloats(Math.random(), Math.random(), Math.random());
  60143. particle._randomNoiseCoordinates2.copyFromFloats(Math.random(), Math.random(), Math.random());
  60144. }
  60145. else {
  60146. particle._randomNoiseCoordinates1 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60147. particle._randomNoiseCoordinates2 = new BABYLON.Vector3(Math.random(), Math.random(), Math.random());
  60148. }
  60149. }
  60150. // Update the position of the attached sub-emitters to match their attached particle
  60151. particle._inheritParticleInfoToSubEmitters();
  60152. };
  60153. var this_1 = this, step;
  60154. for (var index = 0; index < newParticles; index++) {
  60155. var state_1 = _loop_2();
  60156. if (state_1 === "break")
  60157. break;
  60158. }
  60159. };
  60160. /** @hidden */
  60161. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased, useRampGradients) {
  60162. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60163. if (isBillboardBased === void 0) { isBillboardBased = false; }
  60164. if (useRampGradients === void 0) { useRampGradients = false; }
  60165. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  60166. if (isAnimationSheetEnabled) {
  60167. attributeNamesOrOptions.push("cellIndex");
  60168. }
  60169. if (!isBillboardBased) {
  60170. attributeNamesOrOptions.push("direction");
  60171. }
  60172. if (useRampGradients) {
  60173. attributeNamesOrOptions.push("remapData");
  60174. }
  60175. return attributeNamesOrOptions;
  60176. };
  60177. /** @hidden */
  60178. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  60179. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  60180. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "textureMask", "translationPivot", "eyePosition"];
  60181. if (isAnimationSheetEnabled) {
  60182. effectCreationOption.push("particlesInfos");
  60183. }
  60184. return effectCreationOption;
  60185. };
  60186. /** @hidden */
  60187. ParticleSystem.prototype._getEffect = function (blendMode) {
  60188. if (this._customEffect) {
  60189. return this._customEffect;
  60190. }
  60191. ;
  60192. var defines = [];
  60193. if (this._scene.clipPlane) {
  60194. defines.push("#define CLIPPLANE");
  60195. }
  60196. if (this._scene.clipPlane2) {
  60197. defines.push("#define CLIPPLANE2");
  60198. }
  60199. if (this._scene.clipPlane3) {
  60200. defines.push("#define CLIPPLANE3");
  60201. }
  60202. if (this._scene.clipPlane4) {
  60203. defines.push("#define CLIPPLANE4");
  60204. }
  60205. if (this._isAnimationSheetEnabled) {
  60206. defines.push("#define ANIMATESHEET");
  60207. }
  60208. if (blendMode === ParticleSystem.BLENDMODE_MULTIPLY) {
  60209. defines.push("#define BLENDMULTIPLYMODE");
  60210. }
  60211. if (this._useRampGradients) {
  60212. defines.push("#define RAMPGRADIENT");
  60213. }
  60214. if (this._isBillboardBased) {
  60215. defines.push("#define BILLBOARD");
  60216. switch (this.billboardMode) {
  60217. case ParticleSystem.BILLBOARDMODE_Y:
  60218. defines.push("#define BILLBOARDY");
  60219. break;
  60220. case ParticleSystem.BILLBOARDMODE_STRETCHED:
  60221. defines.push("#define BILLBOARDSTRETCHED");
  60222. break;
  60223. case ParticleSystem.BILLBOARDMODE_ALL:
  60224. default:
  60225. break;
  60226. }
  60227. }
  60228. if (this._imageProcessingConfiguration) {
  60229. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  60230. defines.push(this._imageProcessingConfigurationDefines.toString());
  60231. }
  60232. // Effect
  60233. var join = defines.join("\n");
  60234. if (this._cachedDefines !== join) {
  60235. this._cachedDefines = join;
  60236. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased && this.billboardMode !== ParticleSystem.BILLBOARDMODE_STRETCHED, this._useRampGradients);
  60237. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  60238. var samplers = ["diffuseSampler", "rampSampler"];
  60239. if (BABYLON.ImageProcessingConfiguration) {
  60240. BABYLON.ImageProcessingConfiguration.PrepareUniforms(effectCreationOption, this._imageProcessingConfigurationDefines);
  60241. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  60242. }
  60243. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, samplers, join);
  60244. }
  60245. return this._effect;
  60246. };
  60247. /**
  60248. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  60249. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  60250. */
  60251. ParticleSystem.prototype.animate = function (preWarmOnly) {
  60252. var _this = this;
  60253. if (preWarmOnly === void 0) { preWarmOnly = false; }
  60254. if (!this._started)
  60255. return;
  60256. if (!preWarmOnly) {
  60257. // Check
  60258. if (!this.isReady())
  60259. return;
  60260. if (this._currentRenderId === this._scene.getRenderId()) {
  60261. return;
  60262. }
  60263. this._currentRenderId = this._scene.getRenderId();
  60264. }
  60265. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  60266. // Determine the number of particles we need to create
  60267. var newParticles;
  60268. if (this.manualEmitCount > -1) {
  60269. newParticles = this.manualEmitCount;
  60270. this._newPartsExcess = 0;
  60271. this.manualEmitCount = 0;
  60272. }
  60273. else {
  60274. var rate_1 = this.emitRate;
  60275. if (this._emitRateGradients && this._emitRateGradients.length > 0 && this.targetStopDuration) {
  60276. var ratio = this._actualFrame / this.targetStopDuration;
  60277. BABYLON.Tools.GetCurrentGradient(ratio, this._emitRateGradients, function (currentGradient, nextGradient, scale) {
  60278. if (currentGradient !== _this._currentEmitRateGradient) {
  60279. _this._currentEmitRate1 = _this._currentEmitRate2;
  60280. _this._currentEmitRate2 = nextGradient.getFactor();
  60281. _this._currentEmitRateGradient = currentGradient;
  60282. }
  60283. rate_1 = BABYLON.Scalar.Lerp(_this._currentEmitRate1, _this._currentEmitRate2, scale);
  60284. });
  60285. }
  60286. newParticles = ((rate_1 * this._scaledUpdateSpeed) >> 0);
  60287. this._newPartsExcess += rate_1 * this._scaledUpdateSpeed - newParticles;
  60288. }
  60289. if (this._newPartsExcess > 1.0) {
  60290. newParticles += this._newPartsExcess >> 0;
  60291. this._newPartsExcess -= this._newPartsExcess >> 0;
  60292. }
  60293. this._alive = false;
  60294. if (!this._stopped) {
  60295. this._actualFrame += this._scaledUpdateSpeed;
  60296. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  60297. this.stop();
  60298. }
  60299. else {
  60300. newParticles = 0;
  60301. }
  60302. this._update(newParticles);
  60303. // Stopped?
  60304. if (this._stopped) {
  60305. if (!this._alive) {
  60306. this._started = false;
  60307. if (this.onAnimationEnd) {
  60308. this.onAnimationEnd();
  60309. }
  60310. if (this.disposeOnStop) {
  60311. this._scene._toBeDisposed.push(this);
  60312. }
  60313. }
  60314. }
  60315. if (!preWarmOnly) {
  60316. // Update VBO
  60317. var offset = 0;
  60318. for (var index = 0; index < this._particles.length; index++) {
  60319. var particle = this._particles[index];
  60320. this._appendParticleVertices(offset, particle);
  60321. offset += this._useInstancing ? 1 : 4;
  60322. }
  60323. if (this._vertexBuffer) {
  60324. this._vertexBuffer.update(this._vertexData);
  60325. }
  60326. }
  60327. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  60328. this.stop();
  60329. }
  60330. };
  60331. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  60332. this._appendParticleVertex(offset++, particle, 0, 0);
  60333. if (!this._useInstancing) {
  60334. this._appendParticleVertex(offset++, particle, 1, 0);
  60335. this._appendParticleVertex(offset++, particle, 1, 1);
  60336. this._appendParticleVertex(offset++, particle, 0, 1);
  60337. }
  60338. };
  60339. /**
  60340. * Rebuilds the particle system.
  60341. */
  60342. ParticleSystem.prototype.rebuild = function () {
  60343. this._createIndexBuffer();
  60344. if (this._vertexBuffer) {
  60345. this._vertexBuffer._rebuild();
  60346. }
  60347. };
  60348. /**
  60349. * Is this system ready to be used/rendered
  60350. * @return true if the system is ready
  60351. */
  60352. ParticleSystem.prototype.isReady = function () {
  60353. if (!this.emitter || !this._imageProcessingConfiguration.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  60354. return false;
  60355. }
  60356. if (this.blendMode !== ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60357. if (!this._getEffect(this.blendMode).isReady()) {
  60358. return false;
  60359. }
  60360. }
  60361. else {
  60362. if (!this._getEffect(ParticleSystem.BLENDMODE_MULTIPLY).isReady()) {
  60363. return false;
  60364. }
  60365. if (!this._getEffect(ParticleSystem.BLENDMODE_ADD).isReady()) {
  60366. return false;
  60367. }
  60368. }
  60369. return true;
  60370. };
  60371. ParticleSystem.prototype._render = function (blendMode) {
  60372. var effect = this._getEffect(blendMode);
  60373. var engine = this._scene.getEngine();
  60374. // Render
  60375. engine.enableEffect(effect);
  60376. var viewMatrix = this._scene.getViewMatrix();
  60377. effect.setTexture("diffuseSampler", this.particleTexture);
  60378. effect.setMatrix("view", viewMatrix);
  60379. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  60380. if (this._isAnimationSheetEnabled && this.particleTexture) {
  60381. var baseSize = this.particleTexture.getBaseSize();
  60382. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  60383. }
  60384. effect.setVector2("translationPivot", this.translationPivot);
  60385. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  60386. if (this._isBillboardBased) {
  60387. var camera = this._scene.activeCamera;
  60388. effect.setVector3("eyePosition", camera.globalPosition);
  60389. }
  60390. if (this._rampGradientsTexture) {
  60391. effect.setTexture("rampSampler", this._rampGradientsTexture);
  60392. }
  60393. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  60394. var invView = viewMatrix.clone();
  60395. invView.invert();
  60396. effect.setMatrix("invView", invView);
  60397. BABYLON.MaterialHelper.BindClipPlane(effect, this._scene);
  60398. }
  60399. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  60400. // image processing
  60401. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  60402. this._imageProcessingConfiguration.bind(effect);
  60403. }
  60404. // Draw order
  60405. switch (blendMode) {
  60406. case ParticleSystem.BLENDMODE_ADD:
  60407. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  60408. break;
  60409. case ParticleSystem.BLENDMODE_ONEONE:
  60410. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  60411. break;
  60412. case ParticleSystem.BLENDMODE_STANDARD:
  60413. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  60414. break;
  60415. case ParticleSystem.BLENDMODE_MULTIPLY:
  60416. engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  60417. break;
  60418. }
  60419. if (this._useInstancing) {
  60420. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  60421. }
  60422. else {
  60423. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  60424. }
  60425. return this._particles.length;
  60426. };
  60427. /**
  60428. * Renders the particle system in its current state.
  60429. * @returns the current number of particles
  60430. */
  60431. ParticleSystem.prototype.render = function () {
  60432. // Check
  60433. if (!this.isReady() || !this._particles.length) {
  60434. return 0;
  60435. }
  60436. var engine = this._scene.getEngine();
  60437. engine.setState(false);
  60438. if (this.forceDepthWrite) {
  60439. engine.setDepthWrite(true);
  60440. }
  60441. var outparticles = 0;
  60442. if (this.blendMode === ParticleSystem.BLENDMODE_MULTIPLYADD) {
  60443. outparticles = this._render(ParticleSystem.BLENDMODE_MULTIPLY) + this._render(ParticleSystem.BLENDMODE_ADD);
  60444. }
  60445. outparticles = this._render(this.blendMode);
  60446. engine.unbindInstanceAttributes();
  60447. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  60448. return outparticles;
  60449. };
  60450. /**
  60451. * Disposes the particle system and free the associated resources
  60452. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  60453. */
  60454. ParticleSystem.prototype.dispose = function (disposeTexture) {
  60455. if (disposeTexture === void 0) { disposeTexture = true; }
  60456. if (this._vertexBuffer) {
  60457. this._vertexBuffer.dispose();
  60458. this._vertexBuffer = null;
  60459. }
  60460. if (this._spriteBuffer) {
  60461. this._spriteBuffer.dispose();
  60462. this._spriteBuffer = null;
  60463. }
  60464. if (this._indexBuffer) {
  60465. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  60466. this._indexBuffer = null;
  60467. }
  60468. if (disposeTexture && this.particleTexture) {
  60469. this.particleTexture.dispose();
  60470. this.particleTexture = null;
  60471. }
  60472. if (disposeTexture && this.noiseTexture) {
  60473. this.noiseTexture.dispose();
  60474. this.noiseTexture = null;
  60475. }
  60476. if (this._rampGradientsTexture) {
  60477. this._rampGradientsTexture.dispose();
  60478. this._rampGradientsTexture = null;
  60479. }
  60480. this._removeFromRoot();
  60481. if (this._subEmitters && this._subEmitters.length) {
  60482. for (var index = 0; index < this._subEmitters.length; index++) {
  60483. for (var _i = 0, _a = this._subEmitters[index]; _i < _a.length; _i++) {
  60484. var subEmitter = _a[_i];
  60485. subEmitter.dispose();
  60486. }
  60487. }
  60488. this._subEmitters = [];
  60489. this.subEmitters = [];
  60490. }
  60491. if (this._disposeEmitterOnDispose && this.emitter && this.emitter.dispose) {
  60492. this.emitter.dispose(true);
  60493. }
  60494. // Remove from scene
  60495. var index = this._scene.particleSystems.indexOf(this);
  60496. if (index > -1) {
  60497. this._scene.particleSystems.splice(index, 1);
  60498. }
  60499. this._scene._activeParticleSystems.dispose();
  60500. // Callback
  60501. this.onDisposeObservable.notifyObservers(this);
  60502. this.onDisposeObservable.clear();
  60503. this.reset();
  60504. };
  60505. // Clone
  60506. /**
  60507. * Clones the particle system.
  60508. * @param name The name of the cloned object
  60509. * @param newEmitter The new emitter to use
  60510. * @returns the cloned particle system
  60511. */
  60512. ParticleSystem.prototype.clone = function (name, newEmitter) {
  60513. var custom = null;
  60514. var program = null;
  60515. if (this.customShader != null) {
  60516. program = this.customShader;
  60517. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  60518. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  60519. }
  60520. else if (this._customEffect) {
  60521. custom = this._customEffect;
  60522. }
  60523. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  60524. result.customShader = program;
  60525. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader", "noiseTexture"]);
  60526. if (newEmitter === undefined) {
  60527. newEmitter = this.emitter;
  60528. }
  60529. result.noiseTexture = this.noiseTexture;
  60530. result.emitter = newEmitter;
  60531. if (this.particleTexture) {
  60532. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  60533. }
  60534. // Clone gradients
  60535. if (this._colorGradients) {
  60536. this._colorGradients.forEach(function (v) {
  60537. result.addColorGradient(v.gradient, v.color1, v.color2);
  60538. });
  60539. }
  60540. if (this._dragGradients) {
  60541. this._dragGradients.forEach(function (v) {
  60542. result.addDragGradient(v.gradient, v.factor1, v.factor2);
  60543. });
  60544. }
  60545. if (this._angularSpeedGradients) {
  60546. this._angularSpeedGradients.forEach(function (v) {
  60547. result.addAngularSpeedGradient(v.gradient, v.factor1, v.factor2);
  60548. });
  60549. }
  60550. if (this._emitRateGradients) {
  60551. this._emitRateGradients.forEach(function (v) {
  60552. result.addEmitRateGradient(v.gradient, v.factor1, v.factor2);
  60553. });
  60554. }
  60555. if (this._lifeTimeGradients) {
  60556. this._lifeTimeGradients.forEach(function (v) {
  60557. result.addLifeTimeGradient(v.gradient, v.factor1, v.factor2);
  60558. });
  60559. }
  60560. if (this._limitVelocityGradients) {
  60561. this._limitVelocityGradients.forEach(function (v) {
  60562. result.addLimitVelocityGradient(v.gradient, v.factor1, v.factor2);
  60563. });
  60564. }
  60565. if (this._sizeGradients) {
  60566. this._sizeGradients.forEach(function (v) {
  60567. result.addSizeGradient(v.gradient, v.factor1, v.factor2);
  60568. });
  60569. }
  60570. if (this._startSizeGradients) {
  60571. this._startSizeGradients.forEach(function (v) {
  60572. result.addStartSizeGradient(v.gradient, v.factor1, v.factor2);
  60573. });
  60574. }
  60575. if (this._velocityGradients) {
  60576. this._velocityGradients.forEach(function (v) {
  60577. result.addVelocityGradient(v.gradient, v.factor1, v.factor2);
  60578. });
  60579. }
  60580. if (this._rampGradients) {
  60581. this._rampGradients.forEach(function (v) {
  60582. result.addRampGradient(v.gradient, v.color);
  60583. });
  60584. }
  60585. if (this._colorRemapGradients) {
  60586. this._colorRemapGradients.forEach(function (v) {
  60587. result.addColorRemapGradient(v.gradient, v.factor1, v.factor2);
  60588. });
  60589. }
  60590. if (this._alphaRemapGradients) {
  60591. this._alphaRemapGradients.forEach(function (v) {
  60592. result.addAlphaRemapGradient(v.gradient, v.factor1, v.factor2);
  60593. });
  60594. }
  60595. if (!this.preventAutoStart) {
  60596. result.start();
  60597. }
  60598. return result;
  60599. };
  60600. /**
  60601. * Serializes the particle system to a JSON object.
  60602. * @returns the JSON object
  60603. */
  60604. ParticleSystem.prototype.serialize = function () {
  60605. var serializationObject = {};
  60606. ParticleSystem._Serialize(serializationObject, this);
  60607. serializationObject.textureMask = this.textureMask.asArray();
  60608. serializationObject.customShader = this.customShader;
  60609. serializationObject.preventAutoStart = this.preventAutoStart;
  60610. // SubEmitters
  60611. if (this.subEmitters) {
  60612. serializationObject.subEmitters = [];
  60613. if (!this._subEmitters) {
  60614. this._prepareSubEmitterInternalArray();
  60615. }
  60616. for (var _i = 0, _a = this._subEmitters; _i < _a.length; _i++) {
  60617. var subs = _a[_i];
  60618. var cell = [];
  60619. for (var _b = 0, subs_1 = subs; _b < subs_1.length; _b++) {
  60620. var sub = subs_1[_b];
  60621. cell.push(sub.serialize());
  60622. }
  60623. serializationObject.subEmitters.push(cell);
  60624. }
  60625. }
  60626. return serializationObject;
  60627. };
  60628. /** @hidden */
  60629. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  60630. serializationObject.name = particleSystem.name;
  60631. serializationObject.id = particleSystem.id;
  60632. serializationObject.capacity = particleSystem.getCapacity();
  60633. // Emitter
  60634. if (particleSystem.emitter.position) {
  60635. var emitterMesh = particleSystem.emitter;
  60636. serializationObject.emitterId = emitterMesh.id;
  60637. }
  60638. else {
  60639. var emitterPosition = particleSystem.emitter;
  60640. serializationObject.emitter = emitterPosition.asArray();
  60641. }
  60642. // Emitter
  60643. if (particleSystem.particleEmitterType) {
  60644. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  60645. }
  60646. if (particleSystem.particleTexture) {
  60647. serializationObject.textureName = particleSystem.particleTexture.name;
  60648. serializationObject.invertY = particleSystem.particleTexture._invertY;
  60649. }
  60650. // Animations
  60651. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  60652. serializationObject.beginAnimationOnStart = particleSystem.beginAnimationOnStart;
  60653. serializationObject.beginAnimationFrom = particleSystem.beginAnimationFrom;
  60654. serializationObject.beginAnimationTo = particleSystem.beginAnimationTo;
  60655. serializationObject.beginAnimationLoop = particleSystem.beginAnimationLoop;
  60656. // Particle system
  60657. serializationObject.startDelay = particleSystem.startDelay;
  60658. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  60659. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  60660. serializationObject.billboardMode = particleSystem.billboardMode;
  60661. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  60662. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  60663. serializationObject.minSize = particleSystem.minSize;
  60664. serializationObject.maxSize = particleSystem.maxSize;
  60665. serializationObject.minScaleX = particleSystem.minScaleX;
  60666. serializationObject.maxScaleX = particleSystem.maxScaleX;
  60667. serializationObject.minScaleY = particleSystem.minScaleY;
  60668. serializationObject.maxScaleY = particleSystem.maxScaleY;
  60669. serializationObject.minEmitPower = particleSystem.minEmitPower;
  60670. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  60671. serializationObject.minLifeTime = particleSystem.minLifeTime;
  60672. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  60673. serializationObject.emitRate = particleSystem.emitRate;
  60674. serializationObject.gravity = particleSystem.gravity.asArray();
  60675. serializationObject.noiseStrength = particleSystem.noiseStrength.asArray();
  60676. serializationObject.color1 = particleSystem.color1.asArray();
  60677. serializationObject.color2 = particleSystem.color2.asArray();
  60678. serializationObject.colorDead = particleSystem.colorDead.asArray();
  60679. serializationObject.updateSpeed = particleSystem.updateSpeed;
  60680. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  60681. serializationObject.blendMode = particleSystem.blendMode;
  60682. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  60683. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  60684. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  60685. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  60686. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  60687. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  60688. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  60689. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  60690. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  60691. serializationObject.spriteRandomStartCell = particleSystem.spriteRandomStartCell;
  60692. serializationObject.isAnimationSheetEnabled = particleSystem.isAnimationSheetEnabled;
  60693. var colorGradients = particleSystem.getColorGradients();
  60694. if (colorGradients) {
  60695. serializationObject.colorGradients = [];
  60696. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  60697. var colorGradient = colorGradients_1[_i];
  60698. var serializedGradient = {
  60699. gradient: colorGradient.gradient,
  60700. color1: colorGradient.color1.asArray()
  60701. };
  60702. if (colorGradient.color2) {
  60703. serializedGradient.color2 = colorGradient.color2.asArray();
  60704. }
  60705. serializationObject.colorGradients.push(serializedGradient);
  60706. }
  60707. }
  60708. var rampGradients = particleSystem.getRampGradients();
  60709. if (rampGradients) {
  60710. serializationObject.rampGradients = [];
  60711. for (var _a = 0, rampGradients_1 = rampGradients; _a < rampGradients_1.length; _a++) {
  60712. var rampGradient = rampGradients_1[_a];
  60713. var serializedGradient = {
  60714. gradient: rampGradient.gradient,
  60715. color: rampGradient.color.asArray()
  60716. };
  60717. serializationObject.rampGradients.push(serializedGradient);
  60718. }
  60719. serializationObject.useRampGradients = particleSystem.useRampGradients;
  60720. }
  60721. var colorRemapGradients = particleSystem.getColorRemapGradients();
  60722. if (colorRemapGradients) {
  60723. serializationObject.colorRemapGradients = [];
  60724. for (var _b = 0, colorRemapGradients_1 = colorRemapGradients; _b < colorRemapGradients_1.length; _b++) {
  60725. var colorRemapGradient = colorRemapGradients_1[_b];
  60726. var serializedGradient = {
  60727. gradient: colorRemapGradient.gradient,
  60728. factor1: colorRemapGradient.factor1
  60729. };
  60730. if (colorRemapGradient.factor2 !== undefined) {
  60731. serializedGradient.factor2 = colorRemapGradient.factor2;
  60732. }
  60733. serializationObject.colorRemapGradients.push(serializedGradient);
  60734. }
  60735. }
  60736. var alphaRemapGradients = particleSystem.getAlphaRemapGradients();
  60737. if (alphaRemapGradients) {
  60738. serializationObject.alphaRemapGradients = [];
  60739. for (var _c = 0, alphaRemapGradients_1 = alphaRemapGradients; _c < alphaRemapGradients_1.length; _c++) {
  60740. var alphaRemapGradient = alphaRemapGradients_1[_c];
  60741. var serializedGradient = {
  60742. gradient: alphaRemapGradient.gradient,
  60743. factor1: alphaRemapGradient.factor1
  60744. };
  60745. if (alphaRemapGradient.factor2 !== undefined) {
  60746. serializedGradient.factor2 = alphaRemapGradient.factor2;
  60747. }
  60748. serializationObject.alphaRemapGradients.push(serializedGradient);
  60749. }
  60750. }
  60751. var sizeGradients = particleSystem.getSizeGradients();
  60752. if (sizeGradients) {
  60753. serializationObject.sizeGradients = [];
  60754. for (var _d = 0, sizeGradients_1 = sizeGradients; _d < sizeGradients_1.length; _d++) {
  60755. var sizeGradient = sizeGradients_1[_d];
  60756. var serializedGradient = {
  60757. gradient: sizeGradient.gradient,
  60758. factor1: sizeGradient.factor1
  60759. };
  60760. if (sizeGradient.factor2 !== undefined) {
  60761. serializedGradient.factor2 = sizeGradient.factor2;
  60762. }
  60763. serializationObject.sizeGradients.push(serializedGradient);
  60764. }
  60765. }
  60766. var angularSpeedGradients = particleSystem.getAngularSpeedGradients();
  60767. if (angularSpeedGradients) {
  60768. serializationObject.angularSpeedGradients = [];
  60769. for (var _e = 0, angularSpeedGradients_1 = angularSpeedGradients; _e < angularSpeedGradients_1.length; _e++) {
  60770. var angularSpeedGradient = angularSpeedGradients_1[_e];
  60771. var serializedGradient = {
  60772. gradient: angularSpeedGradient.gradient,
  60773. factor1: angularSpeedGradient.factor1
  60774. };
  60775. if (angularSpeedGradient.factor2 !== undefined) {
  60776. serializedGradient.factor2 = angularSpeedGradient.factor2;
  60777. }
  60778. serializationObject.angularSpeedGradients.push(serializedGradient);
  60779. }
  60780. }
  60781. var velocityGradients = particleSystem.getVelocityGradients();
  60782. if (velocityGradients) {
  60783. serializationObject.velocityGradients = [];
  60784. for (var _f = 0, velocityGradients_1 = velocityGradients; _f < velocityGradients_1.length; _f++) {
  60785. var velocityGradient = velocityGradients_1[_f];
  60786. var serializedGradient = {
  60787. gradient: velocityGradient.gradient,
  60788. factor1: velocityGradient.factor1
  60789. };
  60790. if (velocityGradient.factor2 !== undefined) {
  60791. serializedGradient.factor2 = velocityGradient.factor2;
  60792. }
  60793. serializationObject.velocityGradients.push(serializedGradient);
  60794. }
  60795. }
  60796. var dragGradients = particleSystem.getDragGradients();
  60797. if (dragGradients) {
  60798. serializationObject.dragyGradients = [];
  60799. for (var _g = 0, dragGradients_1 = dragGradients; _g < dragGradients_1.length; _g++) {
  60800. var dragGradient = dragGradients_1[_g];
  60801. var serializedGradient = {
  60802. gradient: dragGradient.gradient,
  60803. factor1: dragGradient.factor1
  60804. };
  60805. if (dragGradient.factor2 !== undefined) {
  60806. serializedGradient.factor2 = dragGradient.factor2;
  60807. }
  60808. serializationObject.dragGradients.push(serializedGradient);
  60809. }
  60810. }
  60811. var emitRateGradients = particleSystem.getEmitRateGradients();
  60812. if (emitRateGradients) {
  60813. serializationObject.emitRateGradients = [];
  60814. for (var _h = 0, emitRateGradients_1 = emitRateGradients; _h < emitRateGradients_1.length; _h++) {
  60815. var emitRateGradient = emitRateGradients_1[_h];
  60816. var serializedGradient = {
  60817. gradient: emitRateGradient.gradient,
  60818. factor1: emitRateGradient.factor1
  60819. };
  60820. if (emitRateGradient.factor2 !== undefined) {
  60821. serializedGradient.factor2 = emitRateGradient.factor2;
  60822. }
  60823. serializationObject.emitRateGradients.push(serializedGradient);
  60824. }
  60825. }
  60826. var startSizeGradients = particleSystem.getStartSizeGradients();
  60827. if (startSizeGradients) {
  60828. serializationObject.startSizeGradients = [];
  60829. for (var _j = 0, startSizeGradients_1 = startSizeGradients; _j < startSizeGradients_1.length; _j++) {
  60830. var startSizeGradient = startSizeGradients_1[_j];
  60831. var serializedGradient = {
  60832. gradient: startSizeGradient.gradient,
  60833. factor1: startSizeGradient.factor1
  60834. };
  60835. if (startSizeGradient.factor2 !== undefined) {
  60836. serializedGradient.factor2 = startSizeGradient.factor2;
  60837. }
  60838. serializationObject.startSizeGradients.push(serializedGradient);
  60839. }
  60840. }
  60841. var lifeTimeGradients = particleSystem.getLifeTimeGradients();
  60842. if (lifeTimeGradients) {
  60843. serializationObject.lifeTimeGradients = [];
  60844. for (var _k = 0, lifeTimeGradients_1 = lifeTimeGradients; _k < lifeTimeGradients_1.length; _k++) {
  60845. var lifeTimeGradient = lifeTimeGradients_1[_k];
  60846. var serializedGradient = {
  60847. gradient: lifeTimeGradient.gradient,
  60848. factor1: lifeTimeGradient.factor1
  60849. };
  60850. if (lifeTimeGradient.factor2 !== undefined) {
  60851. serializedGradient.factor2 = lifeTimeGradient.factor2;
  60852. }
  60853. serializationObject.lifeTimeGradients.push(serializedGradient);
  60854. }
  60855. }
  60856. var limitVelocityGradients = particleSystem.getLimitVelocityGradients();
  60857. if (limitVelocityGradients) {
  60858. serializationObject.limitVelocityGradients = [];
  60859. for (var _l = 0, limitVelocityGradients_1 = limitVelocityGradients; _l < limitVelocityGradients_1.length; _l++) {
  60860. var limitVelocityGradient = limitVelocityGradients_1[_l];
  60861. var serializedGradient = {
  60862. gradient: limitVelocityGradient.gradient,
  60863. factor1: limitVelocityGradient.factor1
  60864. };
  60865. if (limitVelocityGradient.factor2 !== undefined) {
  60866. serializedGradient.factor2 = limitVelocityGradient.factor2;
  60867. }
  60868. serializationObject.limitVelocityGradients.push(serializedGradient);
  60869. }
  60870. serializationObject.limitVelocityDamping = particleSystem.limitVelocityDamping;
  60871. }
  60872. if (particleSystem.noiseTexture) {
  60873. serializationObject.noiseTexture = particleSystem.noiseTexture.serialize();
  60874. }
  60875. };
  60876. /** @hidden */
  60877. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  60878. // Texture
  60879. if (parsedParticleSystem.textureName) {
  60880. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene, false, parsedParticleSystem.invertY !== undefined ? parsedParticleSystem.invertY : true);
  60881. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  60882. }
  60883. // Emitter
  60884. if (!parsedParticleSystem.emitterId && parsedParticleSystem.emitterId !== 0 && parsedParticleSystem.emitter === undefined) {
  60885. particleSystem.emitter = BABYLON.Vector3.Zero();
  60886. }
  60887. else if (parsedParticleSystem.emitterId) {
  60888. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  60889. }
  60890. else {
  60891. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  60892. }
  60893. // Misc.
  60894. if (parsedParticleSystem.renderingGroupId !== undefined) {
  60895. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  60896. }
  60897. if (parsedParticleSystem.isBillboardBased !== undefined) {
  60898. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  60899. }
  60900. if (parsedParticleSystem.billboardMode !== undefined) {
  60901. particleSystem.billboardMode = parsedParticleSystem.billboardMode;
  60902. }
  60903. // Animations
  60904. if (parsedParticleSystem.animations) {
  60905. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  60906. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  60907. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  60908. }
  60909. particleSystem.beginAnimationOnStart = parsedParticleSystem.beginAnimationOnStart;
  60910. particleSystem.beginAnimationFrom = parsedParticleSystem.beginAnimationFrom;
  60911. particleSystem.beginAnimationTo = parsedParticleSystem.beginAnimationTo;
  60912. particleSystem.beginAnimationLoop = parsedParticleSystem.beginAnimationLoop;
  60913. }
  60914. if (parsedParticleSystem.autoAnimate) {
  60915. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  60916. }
  60917. // Particle system
  60918. particleSystem.startDelay = parsedParticleSystem.startDelay | 0;
  60919. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  60920. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  60921. particleSystem.minSize = parsedParticleSystem.minSize;
  60922. particleSystem.maxSize = parsedParticleSystem.maxSize;
  60923. if (parsedParticleSystem.minScaleX) {
  60924. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  60925. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  60926. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  60927. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  60928. }
  60929. if (parsedParticleSystem.preWarmCycles !== undefined) {
  60930. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  60931. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  60932. }
  60933. if (parsedParticleSystem.minInitialRotation !== undefined) {
  60934. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  60935. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  60936. }
  60937. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  60938. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  60939. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  60940. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  60941. particleSystem.emitRate = parsedParticleSystem.emitRate;
  60942. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  60943. if (parsedParticleSystem.noiseStrength) {
  60944. particleSystem.noiseStrength = BABYLON.Vector3.FromArray(parsedParticleSystem.noiseStrength);
  60945. }
  60946. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  60947. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  60948. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  60949. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  60950. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  60951. particleSystem.blendMode = parsedParticleSystem.blendMode;
  60952. if (parsedParticleSystem.colorGradients) {
  60953. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  60954. var colorGradient = _a[_i];
  60955. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  60956. }
  60957. }
  60958. if (parsedParticleSystem.rampGradients) {
  60959. for (var _b = 0, _c = parsedParticleSystem.rampGradients; _b < _c.length; _b++) {
  60960. var rampGradient = _c[_b];
  60961. particleSystem.addRampGradient(rampGradient.gradient, BABYLON.Color3.FromArray(rampGradient.color));
  60962. }
  60963. particleSystem.useRampGradients = parsedParticleSystem.useRampGradients;
  60964. }
  60965. if (parsedParticleSystem.colorRemapGradients) {
  60966. for (var _d = 0, _e = parsedParticleSystem.colorRemapGradients; _d < _e.length; _d++) {
  60967. var colorRemapGradient = _e[_d];
  60968. particleSystem.addColorRemapGradient(colorRemapGradient.gradient, colorRemapGradient.factor1 !== undefined ? colorRemapGradient.factor1 : colorRemapGradient.factor, colorRemapGradient.factor2);
  60969. }
  60970. }
  60971. if (parsedParticleSystem.alphaRemapGradients) {
  60972. for (var _f = 0, _g = parsedParticleSystem.alphaRemapGradients; _f < _g.length; _f++) {
  60973. var alphaRemapGradient = _g[_f];
  60974. particleSystem.addAlphaRemapGradient(alphaRemapGradient.gradient, alphaRemapGradient.factor1 !== undefined ? alphaRemapGradient.factor1 : alphaRemapGradient.factor, alphaRemapGradient.factor2);
  60975. }
  60976. }
  60977. if (parsedParticleSystem.sizeGradients) {
  60978. for (var _h = 0, _j = parsedParticleSystem.sizeGradients; _h < _j.length; _h++) {
  60979. var sizeGradient = _j[_h];
  60980. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60981. }
  60982. }
  60983. if (parsedParticleSystem.sizeGradients) {
  60984. for (var _k = 0, _l = parsedParticleSystem.sizeGradients; _k < _l.length; _k++) {
  60985. var sizeGradient = _l[_k];
  60986. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  60987. }
  60988. }
  60989. if (parsedParticleSystem.angularSpeedGradients) {
  60990. for (var _m = 0, _o = parsedParticleSystem.angularSpeedGradients; _m < _o.length; _m++) {
  60991. var angularSpeedGradient = _o[_m];
  60992. particleSystem.addAngularSpeedGradient(angularSpeedGradient.gradient, angularSpeedGradient.factor1 !== undefined ? angularSpeedGradient.factor1 : angularSpeedGradient.factor, angularSpeedGradient.factor2);
  60993. }
  60994. }
  60995. if (parsedParticleSystem.velocityGradients) {
  60996. for (var _p = 0, _q = parsedParticleSystem.velocityGradients; _p < _q.length; _p++) {
  60997. var velocityGradient = _q[_p];
  60998. particleSystem.addVelocityGradient(velocityGradient.gradient, velocityGradient.factor1 !== undefined ? velocityGradient.factor1 : velocityGradient.factor, velocityGradient.factor2);
  60999. }
  61000. }
  61001. if (parsedParticleSystem.dragGradients) {
  61002. for (var _r = 0, _s = parsedParticleSystem.dragGradients; _r < _s.length; _r++) {
  61003. var dragGradient = _s[_r];
  61004. particleSystem.addDragGradient(dragGradient.gradient, dragGradient.factor1 !== undefined ? dragGradient.factor1 : dragGradient.factor, dragGradient.factor2);
  61005. }
  61006. }
  61007. if (parsedParticleSystem.emitRateGradients) {
  61008. for (var _t = 0, _u = parsedParticleSystem.emitRateGradients; _t < _u.length; _t++) {
  61009. var emitRateGradient = _u[_t];
  61010. particleSystem.addEmitRateGradient(emitRateGradient.gradient, emitRateGradient.factor1 !== undefined ? emitRateGradient.factor1 : emitRateGradient.factor, emitRateGradient.factor2);
  61011. }
  61012. }
  61013. if (parsedParticleSystem.startSizeGradients) {
  61014. for (var _v = 0, _w = parsedParticleSystem.startSizeGradients; _v < _w.length; _v++) {
  61015. var startSizeGradient = _w[_v];
  61016. particleSystem.addStartSizeGradient(startSizeGradient.gradient, startSizeGradient.factor1 !== undefined ? startSizeGradient.factor1 : startSizeGradient.factor, startSizeGradient.factor2);
  61017. }
  61018. }
  61019. if (parsedParticleSystem.lifeTimeGradients) {
  61020. for (var _x = 0, _y = parsedParticleSystem.lifeTimeGradients; _x < _y.length; _x++) {
  61021. var lifeTimeGradient = _y[_x];
  61022. particleSystem.addLifeTimeGradient(lifeTimeGradient.gradient, lifeTimeGradient.factor1 !== undefined ? lifeTimeGradient.factor1 : lifeTimeGradient.factor, lifeTimeGradient.factor2);
  61023. }
  61024. }
  61025. if (parsedParticleSystem.limitVelocityGradients) {
  61026. for (var _z = 0, _0 = parsedParticleSystem.limitVelocityGradients; _z < _0.length; _z++) {
  61027. var limitVelocityGradient = _0[_z];
  61028. particleSystem.addLimitVelocityGradient(limitVelocityGradient.gradient, limitVelocityGradient.factor1 !== undefined ? limitVelocityGradient.factor1 : limitVelocityGradient.factor, limitVelocityGradient.factor2);
  61029. }
  61030. particleSystem.limitVelocityDamping = parsedParticleSystem.limitVelocityDamping;
  61031. }
  61032. if (parsedParticleSystem.noiseTexture) {
  61033. particleSystem.noiseTexture = BABYLON.ProceduralTexture.Parse(parsedParticleSystem.noiseTexture, scene, rootUrl);
  61034. }
  61035. // Emitter
  61036. var emitterType;
  61037. if (parsedParticleSystem.particleEmitterType) {
  61038. switch (parsedParticleSystem.particleEmitterType.type) {
  61039. case "SphereParticleEmitter":
  61040. emitterType = new BABYLON.SphereParticleEmitter();
  61041. break;
  61042. case "SphereDirectedParticleEmitter":
  61043. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  61044. break;
  61045. case "ConeEmitter":
  61046. case "ConeParticleEmitter":
  61047. emitterType = new BABYLON.ConeParticleEmitter();
  61048. break;
  61049. case "CylinderParticleEmitter":
  61050. emitterType = new BABYLON.CylinderParticleEmitter();
  61051. break;
  61052. case "HemisphericParticleEmitter":
  61053. emitterType = new BABYLON.HemisphericParticleEmitter();
  61054. break;
  61055. case "BoxEmitter":
  61056. case "BoxParticleEmitter":
  61057. default:
  61058. emitterType = new BABYLON.BoxParticleEmitter();
  61059. break;
  61060. }
  61061. emitterType.parse(parsedParticleSystem.particleEmitterType);
  61062. }
  61063. else {
  61064. emitterType = new BABYLON.BoxParticleEmitter();
  61065. emitterType.parse(parsedParticleSystem);
  61066. }
  61067. particleSystem.particleEmitterType = emitterType;
  61068. // Animation sheet
  61069. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  61070. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  61071. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  61072. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  61073. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  61074. particleSystem.spriteRandomStartCell = parsedParticleSystem.spriteRandomStartCell;
  61075. };
  61076. /**
  61077. * Parses a JSON object to create a particle system.
  61078. * @param parsedParticleSystem The JSON object to parse
  61079. * @param scene The scene to create the particle system in
  61080. * @param rootUrl The root url to use to load external dependencies like texture
  61081. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  61082. * @returns the Parsed particle system
  61083. */
  61084. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  61085. if (doNotStart === void 0) { doNotStart = false; }
  61086. var name = parsedParticleSystem.name;
  61087. var custom = null;
  61088. var program = null;
  61089. if (parsedParticleSystem.customShader) {
  61090. program = parsedParticleSystem.customShader;
  61091. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  61092. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  61093. }
  61094. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  61095. particleSystem.customShader = program;
  61096. if (parsedParticleSystem.id) {
  61097. particleSystem.id = parsedParticleSystem.id;
  61098. }
  61099. // SubEmitters
  61100. if (parsedParticleSystem.subEmitters) {
  61101. particleSystem.subEmitters = [];
  61102. for (var _i = 0, _a = parsedParticleSystem.subEmitters; _i < _a.length; _i++) {
  61103. var cell = _a[_i];
  61104. var cellArray = [];
  61105. for (var _b = 0, cell_1 = cell; _b < cell_1.length; _b++) {
  61106. var sub = cell_1[_b];
  61107. cellArray.push(BABYLON.SubEmitter.Parse(sub, scene, rootUrl));
  61108. }
  61109. particleSystem.subEmitters.push(cellArray);
  61110. }
  61111. }
  61112. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  61113. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  61114. // Auto start
  61115. if (parsedParticleSystem.preventAutoStart) {
  61116. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  61117. }
  61118. if (!doNotStart && !particleSystem.preventAutoStart) {
  61119. particleSystem.start();
  61120. }
  61121. return particleSystem;
  61122. };
  61123. /**
  61124. * Billboard mode will only apply to Y axis
  61125. */
  61126. ParticleSystem.BILLBOARDMODE_Y = 2;
  61127. /**
  61128. * Billboard mode will apply to all axes
  61129. */
  61130. ParticleSystem.BILLBOARDMODE_ALL = 7;
  61131. /**
  61132. * Special billboard mode where the particle will be biilboard to the camera but rotated to align with direction
  61133. */
  61134. ParticleSystem.BILLBOARDMODE_STRETCHED = 8;
  61135. return ParticleSystem;
  61136. }(BABYLON.BaseParticleSystem));
  61137. BABYLON.ParticleSystem = ParticleSystem;
  61138. })(BABYLON || (BABYLON = {}));
  61139. //# sourceMappingURL=babylon.particleSystem.js.map
  61140. var BABYLON;
  61141. (function (BABYLON) {
  61142. /**
  61143. * Particle emitter emitting particles from the inside of a box.
  61144. * It emits the particles randomly between 2 given directions.
  61145. */
  61146. var BoxParticleEmitter = /** @class */ (function () {
  61147. /**
  61148. * Creates a new instance BoxParticleEmitter
  61149. */
  61150. function BoxParticleEmitter() {
  61151. /**
  61152. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61153. */
  61154. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  61155. /**
  61156. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  61157. */
  61158. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  61159. /**
  61160. * 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.
  61161. */
  61162. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  61163. /**
  61164. * 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.
  61165. */
  61166. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  61167. }
  61168. /**
  61169. * Called by the particle System when the direction is computed for the created particle.
  61170. * @param worldMatrix is the world matrix of the particle system
  61171. * @param directionToUpdate is the direction vector to update with the result
  61172. * @param particle is the particle we are computed the direction for
  61173. */
  61174. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61175. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61176. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61177. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61178. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61179. };
  61180. /**
  61181. * Called by the particle System when the position is computed for the created particle.
  61182. * @param worldMatrix is the world matrix of the particle system
  61183. * @param positionToUpdate is the position vector to update with the result
  61184. * @param particle is the particle we are computed the position for
  61185. */
  61186. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61187. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  61188. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  61189. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  61190. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61191. };
  61192. /**
  61193. * Clones the current emitter and returns a copy of it
  61194. * @returns the new emitter
  61195. */
  61196. BoxParticleEmitter.prototype.clone = function () {
  61197. var newOne = new BoxParticleEmitter();
  61198. BABYLON.Tools.DeepCopy(this, newOne);
  61199. return newOne;
  61200. };
  61201. /**
  61202. * Called by the GPUParticleSystem to setup the update shader
  61203. * @param effect defines the update shader
  61204. */
  61205. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  61206. effect.setVector3("direction1", this.direction1);
  61207. effect.setVector3("direction2", this.direction2);
  61208. effect.setVector3("minEmitBox", this.minEmitBox);
  61209. effect.setVector3("maxEmitBox", this.maxEmitBox);
  61210. };
  61211. /**
  61212. * Returns a string to use to update the GPU particles update shader
  61213. * @returns a string containng the defines string
  61214. */
  61215. BoxParticleEmitter.prototype.getEffectDefines = function () {
  61216. return "#define BOXEMITTER";
  61217. };
  61218. /**
  61219. * Returns the string "BoxParticleEmitter"
  61220. * @returns a string containing the class name
  61221. */
  61222. BoxParticleEmitter.prototype.getClassName = function () {
  61223. return "BoxParticleEmitter";
  61224. };
  61225. /**
  61226. * Serializes the particle system to a JSON object.
  61227. * @returns the JSON object
  61228. */
  61229. BoxParticleEmitter.prototype.serialize = function () {
  61230. var serializationObject = {};
  61231. serializationObject.type = this.getClassName();
  61232. serializationObject.direction1 = this.direction1.asArray();
  61233. serializationObject.direction2 = this.direction2.asArray();
  61234. serializationObject.minEmitBox = this.minEmitBox.asArray();
  61235. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  61236. return serializationObject;
  61237. };
  61238. /**
  61239. * Parse properties from a JSON object
  61240. * @param serializationObject defines the JSON object
  61241. */
  61242. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  61243. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  61244. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  61245. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  61246. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  61247. };
  61248. return BoxParticleEmitter;
  61249. }());
  61250. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  61251. })(BABYLON || (BABYLON = {}));
  61252. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  61253. var BABYLON;
  61254. (function (BABYLON) {
  61255. /**
  61256. * Particle emitter emitting particles from the inside of a cylinder.
  61257. * It emits the particles alongside the cylinder radius. The emission direction might be randomized.
  61258. */
  61259. var CylinderParticleEmitter = /** @class */ (function () {
  61260. /**
  61261. * Creates a new instance CylinderParticleEmitter
  61262. * @param radius the radius of the emission cylinder (1 by default)
  61263. * @param height the height of the emission cylinder (1 by default)
  61264. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61265. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61266. */
  61267. function CylinderParticleEmitter(
  61268. /**
  61269. * The radius of the emission cylinder.
  61270. */
  61271. radius,
  61272. /**
  61273. * The height of the emission cylinder.
  61274. */
  61275. height,
  61276. /**
  61277. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61278. */
  61279. radiusRange,
  61280. /**
  61281. * How much to randomize the particle direction [0-1].
  61282. */
  61283. directionRandomizer) {
  61284. if (radius === void 0) { radius = 1; }
  61285. if (height === void 0) { height = 1; }
  61286. if (radiusRange === void 0) { radiusRange = 1; }
  61287. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61288. this.radius = radius;
  61289. this.height = height;
  61290. this.radiusRange = radiusRange;
  61291. this.directionRandomizer = directionRandomizer;
  61292. }
  61293. /**
  61294. * Called by the particle System when the direction is computed for the created particle.
  61295. * @param worldMatrix is the world matrix of the particle system
  61296. * @param directionToUpdate is the direction vector to update with the result
  61297. * @param particle is the particle we are computed the direction for
  61298. */
  61299. CylinderParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61300. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61301. var randY = BABYLON.Scalar.RandomRange(-this.directionRandomizer / 2, this.directionRandomizer / 2);
  61302. var angle = Math.atan2(direction.x, direction.z);
  61303. angle += BABYLON.Scalar.RandomRange(-Math.PI / 2, Math.PI / 2) * this.directionRandomizer;
  61304. direction.y = randY; // set direction y to rand y to mirror normal of cylinder surface
  61305. direction.x = Math.sin(angle);
  61306. direction.z = Math.cos(angle);
  61307. direction.normalize();
  61308. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61309. };
  61310. /**
  61311. * Called by the particle System when the position is computed for the created particle.
  61312. * @param worldMatrix is the world matrix of the particle system
  61313. * @param positionToUpdate is the position vector to update with the result
  61314. * @param particle is the particle we are computed the position for
  61315. */
  61316. CylinderParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61317. var yPos = BABYLON.Scalar.RandomRange(-this.height / 2, this.height / 2);
  61318. var angle = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61319. // Pick a properly distributed point within the circle https://programming.guide/random-point-within-circle.html
  61320. var radiusDistribution = BABYLON.Scalar.RandomRange((1 - this.radiusRange) * (1 - this.radiusRange), 1);
  61321. var positionRadius = Math.sqrt(radiusDistribution) * this.radius;
  61322. var xPos = positionRadius * Math.cos(angle);
  61323. var zPos = positionRadius * Math.sin(angle);
  61324. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(xPos, yPos, zPos, worldMatrix, positionToUpdate);
  61325. };
  61326. /**
  61327. * Clones the current emitter and returns a copy of it
  61328. * @returns the new emitter
  61329. */
  61330. CylinderParticleEmitter.prototype.clone = function () {
  61331. var newOne = new CylinderParticleEmitter(this.radius, this.directionRandomizer);
  61332. BABYLON.Tools.DeepCopy(this, newOne);
  61333. return newOne;
  61334. };
  61335. /**
  61336. * Called by the GPUParticleSystem to setup the update shader
  61337. * @param effect defines the update shader
  61338. */
  61339. CylinderParticleEmitter.prototype.applyToShader = function (effect) {
  61340. effect.setFloat("radius", this.radius);
  61341. effect.setFloat("height", this.height);
  61342. effect.setFloat("radiusRange", this.radiusRange);
  61343. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61344. };
  61345. /**
  61346. * Returns a string to use to update the GPU particles update shader
  61347. * @returns a string containng the defines string
  61348. */
  61349. CylinderParticleEmitter.prototype.getEffectDefines = function () {
  61350. return "#define CYLINDEREMITTER";
  61351. };
  61352. /**
  61353. * Returns the string "CylinderParticleEmitter"
  61354. * @returns a string containing the class name
  61355. */
  61356. CylinderParticleEmitter.prototype.getClassName = function () {
  61357. return "CylinderParticleEmitter";
  61358. };
  61359. /**
  61360. * Serializes the particle system to a JSON object.
  61361. * @returns the JSON object
  61362. */
  61363. CylinderParticleEmitter.prototype.serialize = function () {
  61364. var serializationObject = {};
  61365. serializationObject.type = this.getClassName();
  61366. serializationObject.radius = this.radius;
  61367. serializationObject.height = this.height;
  61368. serializationObject.radiusRange = this.radiusRange;
  61369. serializationObject.directionRandomizer = this.directionRandomizer;
  61370. return serializationObject;
  61371. };
  61372. /**
  61373. * Parse properties from a JSON object
  61374. * @param serializationObject defines the JSON object
  61375. */
  61376. CylinderParticleEmitter.prototype.parse = function (serializationObject) {
  61377. this.radius = serializationObject.radius;
  61378. this.height = serializationObject.height;
  61379. this.radiusRange = serializationObject.radiusRange;
  61380. this.directionRandomizer = serializationObject.directionRandomizer;
  61381. };
  61382. return CylinderParticleEmitter;
  61383. }());
  61384. BABYLON.CylinderParticleEmitter = CylinderParticleEmitter;
  61385. /**
  61386. * Particle emitter emitting particles from the inside of a cylinder.
  61387. * It emits the particles randomly between two vectors.
  61388. */
  61389. var CylinderDirectedParticleEmitter = /** @class */ (function (_super) {
  61390. __extends(CylinderDirectedParticleEmitter, _super);
  61391. /**
  61392. * Creates a new instance CylinderDirectedParticleEmitter
  61393. * @param radius the radius of the emission cylinder (1 by default)
  61394. * @param height the height of the emission cylinder (1 by default)
  61395. * @param radiusRange the range of the emission cylinder [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61396. * @param direction1 the min limit of the emission direction (up vector by default)
  61397. * @param direction2 the max limit of the emission direction (up vector by default)
  61398. */
  61399. function CylinderDirectedParticleEmitter(radius, height, radiusRange,
  61400. /**
  61401. * The min limit of the emission direction.
  61402. */
  61403. direction1,
  61404. /**
  61405. * The max limit of the emission direction.
  61406. */
  61407. direction2) {
  61408. if (radius === void 0) { radius = 1; }
  61409. if (height === void 0) { height = 1; }
  61410. if (radiusRange === void 0) { radiusRange = 1; }
  61411. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61412. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61413. var _this = _super.call(this, radius, height, radiusRange) || this;
  61414. _this.direction1 = direction1;
  61415. _this.direction2 = direction2;
  61416. return _this;
  61417. }
  61418. /**
  61419. * Called by the particle System when the direction is computed for the created particle.
  61420. * @param worldMatrix is the world matrix of the particle system
  61421. * @param directionToUpdate is the direction vector to update with the result
  61422. * @param particle is the particle we are computed the direction for
  61423. */
  61424. CylinderDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61425. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61426. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61427. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61428. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61429. };
  61430. /**
  61431. * Clones the current emitter and returns a copy of it
  61432. * @returns the new emitter
  61433. */
  61434. CylinderDirectedParticleEmitter.prototype.clone = function () {
  61435. var newOne = new CylinderDirectedParticleEmitter(this.radius, this.height, this.radiusRange, this.direction1, this.direction2);
  61436. BABYLON.Tools.DeepCopy(this, newOne);
  61437. return newOne;
  61438. };
  61439. /**
  61440. * Called by the GPUParticleSystem to setup the update shader
  61441. * @param effect defines the update shader
  61442. */
  61443. CylinderDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61444. effect.setFloat("radius", this.radius);
  61445. effect.setFloat("height", this.height);
  61446. effect.setFloat("radiusRange", this.radiusRange);
  61447. effect.setVector3("direction1", this.direction1);
  61448. effect.setVector3("direction2", this.direction2);
  61449. };
  61450. /**
  61451. * Returns a string to use to update the GPU particles update shader
  61452. * @returns a string containng the defines string
  61453. */
  61454. CylinderDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61455. return "#define CYLINDEREMITTER\n#define DIRECTEDCYLINDEREMITTER";
  61456. };
  61457. /**
  61458. * Returns the string "CylinderDirectedParticleEmitter"
  61459. * @returns a string containing the class name
  61460. */
  61461. CylinderDirectedParticleEmitter.prototype.getClassName = function () {
  61462. return "CylinderDirectedParticleEmitter";
  61463. };
  61464. /**
  61465. * Serializes the particle system to a JSON object.
  61466. * @returns the JSON object
  61467. */
  61468. CylinderDirectedParticleEmitter.prototype.serialize = function () {
  61469. var serializationObject = _super.prototype.serialize.call(this);
  61470. serializationObject.direction1 = this.direction1.asArray();
  61471. serializationObject.direction2 = this.direction2.asArray();
  61472. return serializationObject;
  61473. };
  61474. /**
  61475. * Parse properties from a JSON object
  61476. * @param serializationObject defines the JSON object
  61477. */
  61478. CylinderDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61479. _super.prototype.parse.call(this, serializationObject);
  61480. this.direction1.copyFrom(serializationObject.direction1);
  61481. this.direction2.copyFrom(serializationObject.direction2);
  61482. };
  61483. return CylinderDirectedParticleEmitter;
  61484. }(CylinderParticleEmitter));
  61485. BABYLON.CylinderDirectedParticleEmitter = CylinderDirectedParticleEmitter;
  61486. })(BABYLON || (BABYLON = {}));
  61487. //# sourceMappingURL=babylon.cylinderParticleEmitter.js.map
  61488. var BABYLON;
  61489. (function (BABYLON) {
  61490. /**
  61491. * Particle emitter emitting particles from the inside of a cone.
  61492. * It emits the particles alongside the cone volume from the base to the particle.
  61493. * The emission direction might be randomized.
  61494. */
  61495. var ConeParticleEmitter = /** @class */ (function () {
  61496. /**
  61497. * Creates a new instance ConeParticleEmitter
  61498. * @param radius the radius of the emission cone (1 by default)
  61499. * @param angles the cone base angle (PI by default)
  61500. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  61501. */
  61502. function ConeParticleEmitter(radius, angle,
  61503. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  61504. directionRandomizer) {
  61505. if (radius === void 0) { radius = 1; }
  61506. if (angle === void 0) { angle = Math.PI; }
  61507. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61508. this.directionRandomizer = directionRandomizer;
  61509. /**
  61510. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  61511. */
  61512. this.radiusRange = 1;
  61513. /**
  61514. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  61515. */
  61516. this.heightRange = 1;
  61517. /**
  61518. * Gets or sets a value indicating if all the particles should be emitted from the spawn point only (the base of the cone)
  61519. */
  61520. this.emitFromSpawnPointOnly = false;
  61521. this.angle = angle;
  61522. this.radius = radius;
  61523. }
  61524. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  61525. /**
  61526. * Gets or sets the radius of the emission cone
  61527. */
  61528. get: function () {
  61529. return this._radius;
  61530. },
  61531. set: function (value) {
  61532. this._radius = value;
  61533. this._buildHeight();
  61534. },
  61535. enumerable: true,
  61536. configurable: true
  61537. });
  61538. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  61539. /**
  61540. * Gets or sets the angle of the emission cone
  61541. */
  61542. get: function () {
  61543. return this._angle;
  61544. },
  61545. set: function (value) {
  61546. this._angle = value;
  61547. this._buildHeight();
  61548. },
  61549. enumerable: true,
  61550. configurable: true
  61551. });
  61552. ConeParticleEmitter.prototype._buildHeight = function () {
  61553. if (this._angle !== 0) {
  61554. this._height = this._radius / Math.tan(this._angle / 2);
  61555. }
  61556. else {
  61557. this._height = 1;
  61558. }
  61559. };
  61560. /**
  61561. * Called by the particle System when the direction is computed for the created particle.
  61562. * @param worldMatrix is the world matrix of the particle system
  61563. * @param directionToUpdate is the direction vector to update with the result
  61564. * @param particle is the particle we are computed the direction for
  61565. */
  61566. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61567. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  61568. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  61569. }
  61570. else {
  61571. // measure the direction Vector from the emitter to the particle.
  61572. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61573. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61574. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61575. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61576. direction.x += randX;
  61577. direction.y += randY;
  61578. direction.z += randZ;
  61579. direction.normalize();
  61580. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61581. }
  61582. };
  61583. /**
  61584. * Called by the particle System when the position is computed for the created particle.
  61585. * @param worldMatrix is the world matrix of the particle system
  61586. * @param positionToUpdate is the position vector to update with the result
  61587. * @param particle is the particle we are computed the position for
  61588. */
  61589. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61590. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  61591. var h;
  61592. if (!this.emitFromSpawnPointOnly) {
  61593. h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  61594. // Better distribution in a cone at normal angles.
  61595. h = 1 - h * h;
  61596. }
  61597. else {
  61598. h = 0.0001;
  61599. }
  61600. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  61601. radius = radius * h;
  61602. var randX = radius * Math.sin(s);
  61603. var randZ = radius * Math.cos(s);
  61604. var randY = h * this._height;
  61605. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61606. };
  61607. /**
  61608. * Clones the current emitter and returns a copy of it
  61609. * @returns the new emitter
  61610. */
  61611. ConeParticleEmitter.prototype.clone = function () {
  61612. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  61613. BABYLON.Tools.DeepCopy(this, newOne);
  61614. return newOne;
  61615. };
  61616. /**
  61617. * Called by the GPUParticleSystem to setup the update shader
  61618. * @param effect defines the update shader
  61619. */
  61620. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  61621. effect.setFloat2("radius", this._radius, this.radiusRange);
  61622. effect.setFloat("coneAngle", this._angle);
  61623. effect.setFloat2("height", this._height, this.heightRange);
  61624. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61625. };
  61626. /**
  61627. * Returns a string to use to update the GPU particles update shader
  61628. * @returns a string containng the defines string
  61629. */
  61630. ConeParticleEmitter.prototype.getEffectDefines = function () {
  61631. var defines = "#define CONEEMITTER";
  61632. if (this.emitFromSpawnPointOnly) {
  61633. defines += "\n#define CONEEMITTERSPAWNPOINT";
  61634. }
  61635. return defines;
  61636. };
  61637. /**
  61638. * Returns the string "ConeParticleEmitter"
  61639. * @returns a string containing the class name
  61640. */
  61641. ConeParticleEmitter.prototype.getClassName = function () {
  61642. return "ConeParticleEmitter";
  61643. };
  61644. /**
  61645. * Serializes the particle system to a JSON object.
  61646. * @returns the JSON object
  61647. */
  61648. ConeParticleEmitter.prototype.serialize = function () {
  61649. var serializationObject = {};
  61650. serializationObject.type = this.getClassName();
  61651. serializationObject.radius = this._radius;
  61652. serializationObject.angle = this._angle;
  61653. serializationObject.directionRandomizer = this.directionRandomizer;
  61654. return serializationObject;
  61655. };
  61656. /**
  61657. * Parse properties from a JSON object
  61658. * @param serializationObject defines the JSON object
  61659. */
  61660. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  61661. this.radius = serializationObject.radius;
  61662. this.angle = serializationObject.angle;
  61663. this.directionRandomizer = serializationObject.directionRandomizer;
  61664. };
  61665. return ConeParticleEmitter;
  61666. }());
  61667. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  61668. })(BABYLON || (BABYLON = {}));
  61669. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  61670. var BABYLON;
  61671. (function (BABYLON) {
  61672. /**
  61673. * Particle emitter emitting particles from the inside of a sphere.
  61674. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  61675. */
  61676. var SphereParticleEmitter = /** @class */ (function () {
  61677. /**
  61678. * Creates a new instance SphereParticleEmitter
  61679. * @param radius the radius of the emission sphere (1 by default)
  61680. * @param radiusRange the range of the emission sphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61681. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61682. */
  61683. function SphereParticleEmitter(
  61684. /**
  61685. * The radius of the emission sphere.
  61686. */
  61687. radius,
  61688. /**
  61689. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61690. */
  61691. radiusRange,
  61692. /**
  61693. * How much to randomize the particle direction [0-1].
  61694. */
  61695. directionRandomizer) {
  61696. if (radius === void 0) { radius = 1; }
  61697. if (radiusRange === void 0) { radiusRange = 1; }
  61698. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61699. this.radius = radius;
  61700. this.radiusRange = radiusRange;
  61701. this.directionRandomizer = directionRandomizer;
  61702. }
  61703. /**
  61704. * Called by the particle System when the direction is computed for the created particle.
  61705. * @param worldMatrix is the world matrix of the particle system
  61706. * @param directionToUpdate is the direction vector to update with the result
  61707. * @param particle is the particle we are computed the direction for
  61708. */
  61709. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61710. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61711. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61712. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61713. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61714. direction.x += randX;
  61715. direction.y += randY;
  61716. direction.z += randZ;
  61717. direction.normalize();
  61718. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61719. };
  61720. /**
  61721. * Called by the particle System when the position is computed for the created particle.
  61722. * @param worldMatrix is the world matrix of the particle system
  61723. * @param positionToUpdate is the position vector to update with the result
  61724. * @param particle is the particle we are computed the position for
  61725. */
  61726. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61727. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61728. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61729. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61730. var theta = Math.acos(2 * v - 1);
  61731. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61732. var randY = randRadius * Math.cos(theta);
  61733. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61734. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  61735. };
  61736. /**
  61737. * Clones the current emitter and returns a copy of it
  61738. * @returns the new emitter
  61739. */
  61740. SphereParticleEmitter.prototype.clone = function () {
  61741. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  61742. BABYLON.Tools.DeepCopy(this, newOne);
  61743. return newOne;
  61744. };
  61745. /**
  61746. * Called by the GPUParticleSystem to setup the update shader
  61747. * @param effect defines the update shader
  61748. */
  61749. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  61750. effect.setFloat("radius", this.radius);
  61751. effect.setFloat("radiusRange", this.radiusRange);
  61752. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61753. };
  61754. /**
  61755. * Returns a string to use to update the GPU particles update shader
  61756. * @returns a string containng the defines string
  61757. */
  61758. SphereParticleEmitter.prototype.getEffectDefines = function () {
  61759. return "#define SPHEREEMITTER";
  61760. };
  61761. /**
  61762. * Returns the string "SphereParticleEmitter"
  61763. * @returns a string containing the class name
  61764. */
  61765. SphereParticleEmitter.prototype.getClassName = function () {
  61766. return "SphereParticleEmitter";
  61767. };
  61768. /**
  61769. * Serializes the particle system to a JSON object.
  61770. * @returns the JSON object
  61771. */
  61772. SphereParticleEmitter.prototype.serialize = function () {
  61773. var serializationObject = {};
  61774. serializationObject.type = this.getClassName();
  61775. serializationObject.radius = this.radius;
  61776. serializationObject.radiusRange = this.radiusRange;
  61777. serializationObject.directionRandomizer = this.directionRandomizer;
  61778. return serializationObject;
  61779. };
  61780. /**
  61781. * Parse properties from a JSON object
  61782. * @param serializationObject defines the JSON object
  61783. */
  61784. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  61785. this.radius = serializationObject.radius;
  61786. this.radiusRange = serializationObject.radiusRange;
  61787. this.directionRandomizer = serializationObject.directionRandomizer;
  61788. };
  61789. return SphereParticleEmitter;
  61790. }());
  61791. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  61792. /**
  61793. * Particle emitter emitting particles from the inside of a sphere.
  61794. * It emits the particles randomly between two vectors.
  61795. */
  61796. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  61797. __extends(SphereDirectedParticleEmitter, _super);
  61798. /**
  61799. * Creates a new instance SphereDirectedParticleEmitter
  61800. * @param radius the radius of the emission sphere (1 by default)
  61801. * @param direction1 the min limit of the emission direction (up vector by default)
  61802. * @param direction2 the max limit of the emission direction (up vector by default)
  61803. */
  61804. function SphereDirectedParticleEmitter(radius,
  61805. /**
  61806. * The min limit of the emission direction.
  61807. */
  61808. direction1,
  61809. /**
  61810. * The max limit of the emission direction.
  61811. */
  61812. direction2) {
  61813. if (radius === void 0) { radius = 1; }
  61814. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  61815. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  61816. var _this = _super.call(this, radius) || this;
  61817. _this.direction1 = direction1;
  61818. _this.direction2 = direction2;
  61819. return _this;
  61820. }
  61821. /**
  61822. * Called by the particle System when the direction is computed for the created particle.
  61823. * @param worldMatrix is the world matrix of the particle system
  61824. * @param directionToUpdate is the direction vector to update with the result
  61825. * @param particle is the particle we are computed the direction for
  61826. */
  61827. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61828. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  61829. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  61830. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  61831. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  61832. };
  61833. /**
  61834. * Clones the current emitter and returns a copy of it
  61835. * @returns the new emitter
  61836. */
  61837. SphereDirectedParticleEmitter.prototype.clone = function () {
  61838. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  61839. BABYLON.Tools.DeepCopy(this, newOne);
  61840. return newOne;
  61841. };
  61842. /**
  61843. * Called by the GPUParticleSystem to setup the update shader
  61844. * @param effect defines the update shader
  61845. */
  61846. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  61847. effect.setFloat("radius", this.radius);
  61848. effect.setFloat("radiusRange", this.radiusRange);
  61849. effect.setVector3("direction1", this.direction1);
  61850. effect.setVector3("direction2", this.direction2);
  61851. };
  61852. /**
  61853. * Returns a string to use to update the GPU particles update shader
  61854. * @returns a string containng the defines string
  61855. */
  61856. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  61857. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  61858. };
  61859. /**
  61860. * Returns the string "SphereDirectedParticleEmitter"
  61861. * @returns a string containing the class name
  61862. */
  61863. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  61864. return "SphereDirectedParticleEmitter";
  61865. };
  61866. /**
  61867. * Serializes the particle system to a JSON object.
  61868. * @returns the JSON object
  61869. */
  61870. SphereDirectedParticleEmitter.prototype.serialize = function () {
  61871. var serializationObject = _super.prototype.serialize.call(this);
  61872. serializationObject.direction1 = this.direction1.asArray();
  61873. serializationObject.direction2 = this.direction2.asArray();
  61874. return serializationObject;
  61875. };
  61876. /**
  61877. * Parse properties from a JSON object
  61878. * @param serializationObject defines the JSON object
  61879. */
  61880. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  61881. _super.prototype.parse.call(this, serializationObject);
  61882. this.direction1.copyFrom(serializationObject.direction1);
  61883. this.direction2.copyFrom(serializationObject.direction2);
  61884. };
  61885. return SphereDirectedParticleEmitter;
  61886. }(SphereParticleEmitter));
  61887. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  61888. })(BABYLON || (BABYLON = {}));
  61889. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  61890. var BABYLON;
  61891. (function (BABYLON) {
  61892. /**
  61893. * Particle emitter emitting particles from the inside of a hemisphere.
  61894. * It emits the particles alongside the hemisphere radius. The emission direction might be randomized.
  61895. */
  61896. var HemisphericParticleEmitter = /** @class */ (function () {
  61897. /**
  61898. * Creates a new instance HemisphericParticleEmitter
  61899. * @param radius the radius of the emission hemisphere (1 by default)
  61900. * @param radiusRange the range of the emission hemisphere [0-1] 0 Surface only, 1 Entire Radius (1 by default)
  61901. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  61902. */
  61903. function HemisphericParticleEmitter(
  61904. /**
  61905. * The radius of the emission hemisphere.
  61906. */
  61907. radius,
  61908. /**
  61909. * The range of emission [0-1] 0 Surface only, 1 Entire Radius.
  61910. */
  61911. radiusRange,
  61912. /**
  61913. * How much to randomize the particle direction [0-1].
  61914. */
  61915. directionRandomizer) {
  61916. if (radius === void 0) { radius = 1; }
  61917. if (radiusRange === void 0) { radiusRange = 1; }
  61918. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  61919. this.radius = radius;
  61920. this.radiusRange = radiusRange;
  61921. this.directionRandomizer = directionRandomizer;
  61922. }
  61923. /**
  61924. * Called by the particle System when the direction is computed for the created particle.
  61925. * @param worldMatrix is the world matrix of the particle system
  61926. * @param directionToUpdate is the direction vector to update with the result
  61927. * @param particle is the particle we are computed the direction for
  61928. */
  61929. HemisphericParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  61930. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  61931. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61932. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61933. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  61934. direction.x += randX;
  61935. direction.y += randY;
  61936. direction.z += randZ;
  61937. direction.normalize();
  61938. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  61939. };
  61940. /**
  61941. * Called by the particle System when the position is computed for the created particle.
  61942. * @param worldMatrix is the world matrix of the particle system
  61943. * @param positionToUpdate is the position vector to update with the result
  61944. * @param particle is the particle we are computed the position for
  61945. */
  61946. HemisphericParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  61947. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  61948. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  61949. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  61950. var theta = Math.acos(2 * v - 1);
  61951. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  61952. var randY = randRadius * Math.cos(theta);
  61953. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  61954. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, Math.abs(randY), randZ, worldMatrix, positionToUpdate);
  61955. };
  61956. /**
  61957. * Clones the current emitter and returns a copy of it
  61958. * @returns the new emitter
  61959. */
  61960. HemisphericParticleEmitter.prototype.clone = function () {
  61961. var newOne = new HemisphericParticleEmitter(this.radius, this.directionRandomizer);
  61962. BABYLON.Tools.DeepCopy(this, newOne);
  61963. return newOne;
  61964. };
  61965. /**
  61966. * Called by the GPUParticleSystem to setup the update shader
  61967. * @param effect defines the update shader
  61968. */
  61969. HemisphericParticleEmitter.prototype.applyToShader = function (effect) {
  61970. effect.setFloat("radius", this.radius);
  61971. effect.setFloat("radiusRange", this.radiusRange);
  61972. effect.setFloat("directionRandomizer", this.directionRandomizer);
  61973. };
  61974. /**
  61975. * Returns a string to use to update the GPU particles update shader
  61976. * @returns a string containng the defines string
  61977. */
  61978. HemisphericParticleEmitter.prototype.getEffectDefines = function () {
  61979. return "#define HEMISPHERICEMITTER";
  61980. };
  61981. /**
  61982. * Returns the string "HemisphericParticleEmitter"
  61983. * @returns a string containing the class name
  61984. */
  61985. HemisphericParticleEmitter.prototype.getClassName = function () {
  61986. return "HemisphericParticleEmitter";
  61987. };
  61988. /**
  61989. * Serializes the particle system to a JSON object.
  61990. * @returns the JSON object
  61991. */
  61992. HemisphericParticleEmitter.prototype.serialize = function () {
  61993. var serializationObject = {};
  61994. serializationObject.type = this.getClassName();
  61995. serializationObject.radius = this.radius;
  61996. serializationObject.radiusRange = this.radiusRange;
  61997. serializationObject.directionRandomizer = this.directionRandomizer;
  61998. return serializationObject;
  61999. };
  62000. /**
  62001. * Parse properties from a JSON object
  62002. * @param serializationObject defines the JSON object
  62003. */
  62004. HemisphericParticleEmitter.prototype.parse = function (serializationObject) {
  62005. this.radius = serializationObject.radius;
  62006. this.radiusRange = serializationObject.radiusRange;
  62007. this.directionRandomizer = serializationObject.directionRandomizer;
  62008. };
  62009. return HemisphericParticleEmitter;
  62010. }());
  62011. BABYLON.HemisphericParticleEmitter = HemisphericParticleEmitter;
  62012. })(BABYLON || (BABYLON = {}));
  62013. //# sourceMappingURL=babylon.hemisphericParticleEmitter.js.map
  62014. var BABYLON;
  62015. (function (BABYLON) {
  62016. /**
  62017. * Particle emitter emitting particles from a point.
  62018. * It emits the particles randomly between 2 given directions.
  62019. */
  62020. var PointParticleEmitter = /** @class */ (function () {
  62021. /**
  62022. * Creates a new instance PointParticleEmitter
  62023. */
  62024. function PointParticleEmitter() {
  62025. /**
  62026. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62027. */
  62028. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  62029. /**
  62030. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  62031. */
  62032. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  62033. }
  62034. /**
  62035. * Called by the particle System when the direction is computed for the created particle.
  62036. * @param worldMatrix is the world matrix of the particle system
  62037. * @param directionToUpdate is the direction vector to update with the result
  62038. * @param particle is the particle we are computed the direction for
  62039. */
  62040. PointParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  62041. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  62042. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  62043. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  62044. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  62045. };
  62046. /**
  62047. * Called by the particle System when the position is computed for the created particle.
  62048. * @param worldMatrix is the world matrix of the particle system
  62049. * @param positionToUpdate is the position vector to update with the result
  62050. * @param particle is the particle we are computed the position for
  62051. */
  62052. PointParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  62053. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0, 0, 0, worldMatrix, positionToUpdate);
  62054. };
  62055. /**
  62056. * Clones the current emitter and returns a copy of it
  62057. * @returns the new emitter
  62058. */
  62059. PointParticleEmitter.prototype.clone = function () {
  62060. var newOne = new PointParticleEmitter();
  62061. BABYLON.Tools.DeepCopy(this, newOne);
  62062. return newOne;
  62063. };
  62064. /**
  62065. * Called by the GPUParticleSystem to setup the update shader
  62066. * @param effect defines the update shader
  62067. */
  62068. PointParticleEmitter.prototype.applyToShader = function (effect) {
  62069. effect.setVector3("direction1", this.direction1);
  62070. effect.setVector3("direction2", this.direction2);
  62071. };
  62072. /**
  62073. * Returns a string to use to update the GPU particles update shader
  62074. * @returns a string containng the defines string
  62075. */
  62076. PointParticleEmitter.prototype.getEffectDefines = function () {
  62077. return "#define POINTEMITTER";
  62078. };
  62079. /**
  62080. * Returns the string "PointParticleEmitter"
  62081. * @returns a string containing the class name
  62082. */
  62083. PointParticleEmitter.prototype.getClassName = function () {
  62084. return "PointParticleEmitter";
  62085. };
  62086. /**
  62087. * Serializes the particle system to a JSON object.
  62088. * @returns the JSON object
  62089. */
  62090. PointParticleEmitter.prototype.serialize = function () {
  62091. var serializationObject = {};
  62092. serializationObject.type = this.getClassName();
  62093. serializationObject.direction1 = this.direction1.asArray();
  62094. serializationObject.direction2 = this.direction2.asArray();
  62095. return serializationObject;
  62096. };
  62097. /**
  62098. * Parse properties from a JSON object
  62099. * @param serializationObject defines the JSON object
  62100. */
  62101. PointParticleEmitter.prototype.parse = function (serializationObject) {
  62102. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  62103. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  62104. };
  62105. return PointParticleEmitter;
  62106. }());
  62107. BABYLON.PointParticleEmitter = PointParticleEmitter;
  62108. })(BABYLON || (BABYLON = {}));
  62109. //# sourceMappingURL=babylon.pointParticleEmitter.js.map
  62110. var BABYLON;
  62111. (function (BABYLON) {
  62112. // Adds the parsers to the scene parsers.
  62113. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedData, scene, container, rootUrl) {
  62114. var individualParser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  62115. if (!individualParser) {
  62116. return;
  62117. }
  62118. // Particles Systems
  62119. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  62120. for (var index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  62121. var parsedParticleSystem = parsedData.particleSystems[index];
  62122. container.particleSystems.push(individualParser(parsedParticleSystem, scene, rootUrl));
  62123. }
  62124. }
  62125. });
  62126. BABYLON.AbstractScene.AddIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM, function (parsedParticleSystem, scene, rootUrl) {
  62127. if (parsedParticleSystem.activeParticleCount) {
  62128. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62129. return ps;
  62130. }
  62131. else {
  62132. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  62133. return ps;
  62134. }
  62135. });
  62136. BABYLON.Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  62137. if (uniformsNames === void 0) { uniformsNames = []; }
  62138. if (samplers === void 0) { samplers = []; }
  62139. if (defines === void 0) { defines = ""; }
  62140. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  62141. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  62142. if (defines.indexOf(" BILLBOARD") === -1) {
  62143. defines += "\n#define BILLBOARD\n";
  62144. }
  62145. if (samplers.indexOf("diffuseSampler") === -1) {
  62146. samplers.push("diffuseSampler");
  62147. }
  62148. return this.createEffect({
  62149. vertex: "particles",
  62150. fragmentElement: fragmentName
  62151. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  62152. };
  62153. BABYLON.Mesh.prototype.getEmittedParticleSystems = function () {
  62154. var results = new Array();
  62155. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62156. var particleSystem = this.getScene().particleSystems[index];
  62157. if (particleSystem.emitter === this) {
  62158. results.push(particleSystem);
  62159. }
  62160. }
  62161. return results;
  62162. };
  62163. BABYLON.Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  62164. var results = new Array();
  62165. var descendants = this.getDescendants();
  62166. descendants.push(this);
  62167. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  62168. var particleSystem = this.getScene().particleSystems[index];
  62169. var emitter = particleSystem.emitter;
  62170. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  62171. results.push(particleSystem);
  62172. }
  62173. }
  62174. return results;
  62175. };
  62176. })(BABYLON || (BABYLON = {}));
  62177. //# sourceMappingURL=babylon.particleSystemComponent.js.map
  62178. var BABYLON;
  62179. (function (BABYLON) {
  62180. /**
  62181. * Type of sub emitter
  62182. */
  62183. var SubEmitterType;
  62184. (function (SubEmitterType) {
  62185. /**
  62186. * Attached to the particle over it's lifetime
  62187. */
  62188. SubEmitterType[SubEmitterType["ATTACHED"] = 0] = "ATTACHED";
  62189. /**
  62190. * Created when the particle dies
  62191. */
  62192. SubEmitterType[SubEmitterType["END"] = 1] = "END";
  62193. })(SubEmitterType = BABYLON.SubEmitterType || (BABYLON.SubEmitterType = {}));
  62194. /**
  62195. * Sub emitter class used to emit particles from an existing particle
  62196. */
  62197. var SubEmitter = /** @class */ (function () {
  62198. /**
  62199. * Creates a sub emitter
  62200. * @param particleSystem the particle system to be used by the sub emitter
  62201. */
  62202. function SubEmitter(
  62203. /**
  62204. * the particle system to be used by the sub emitter
  62205. */
  62206. particleSystem) {
  62207. this.particleSystem = particleSystem;
  62208. /**
  62209. * Type of the submitter (Default: END)
  62210. */
  62211. this.type = SubEmitterType.END;
  62212. /**
  62213. * 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)
  62214. * Note: This only is supported when using an emitter of type Mesh
  62215. */
  62216. this.inheritDirection = false;
  62217. /**
  62218. * How much of the attached particles speed should be added to the sub emitted particle (default: 0)
  62219. */
  62220. this.inheritedVelocityAmount = 0;
  62221. // Create mesh as emitter to support rotation
  62222. if (!particleSystem.emitter || !particleSystem.emitter.dispose) {
  62223. particleSystem.emitter = new BABYLON.AbstractMesh("SubemitterSystemEmitter", particleSystem.getScene());
  62224. }
  62225. // Automatically dispose of subemitter when system is disposed
  62226. particleSystem.onDisposeObservable.add(function () {
  62227. if (particleSystem.emitter && particleSystem.emitter.dispose) {
  62228. particleSystem.emitter.dispose();
  62229. }
  62230. });
  62231. }
  62232. /**
  62233. * Clones the sub emitter
  62234. * @returns the cloned sub emitter
  62235. */
  62236. SubEmitter.prototype.clone = function () {
  62237. // Clone particle system
  62238. var emitter = this.particleSystem.emitter;
  62239. if (!emitter) {
  62240. emitter = new BABYLON.Vector3();
  62241. }
  62242. else if (emitter instanceof BABYLON.Vector3) {
  62243. emitter = emitter.clone();
  62244. }
  62245. else if (emitter instanceof BABYLON.AbstractMesh) {
  62246. emitter = new BABYLON.Mesh("", emitter.getScene());
  62247. emitter.isVisible = false;
  62248. }
  62249. var clone = new SubEmitter(this.particleSystem.clone("", emitter));
  62250. // Clone properties
  62251. clone.type = this.type;
  62252. clone.inheritDirection = this.inheritDirection;
  62253. clone.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62254. clone.particleSystem._disposeEmitterOnDispose = true;
  62255. clone.particleSystem.disposeOnStop = true;
  62256. return clone;
  62257. };
  62258. /**
  62259. * Serialize current object to a JSON object
  62260. * @returns the serialized object
  62261. */
  62262. SubEmitter.prototype.serialize = function () {
  62263. var serializationObject = {};
  62264. serializationObject.type = this.type;
  62265. serializationObject.inheritDirection = this.inheritDirection;
  62266. serializationObject.inheritedVelocityAmount = this.inheritedVelocityAmount;
  62267. serializationObject.particleSystem = this.particleSystem.serialize();
  62268. return serializationObject;
  62269. };
  62270. /**
  62271. * Creates a new SubEmitter from a serialized JSON version
  62272. * @param serializationObject defines the JSON object to read from
  62273. * @param scene defines the hosting scene
  62274. * @param rootUrl defines the rootUrl for data loading
  62275. * @returns a new SubEmitter
  62276. */
  62277. SubEmitter.Parse = function (serializationObject, scene, rootUrl) {
  62278. var system = serializationObject.particleSystem;
  62279. var subEmitter = new SubEmitter(BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  62280. subEmitter.type = serializationObject.type;
  62281. subEmitter.inheritDirection = serializationObject.inheritDirection;
  62282. subEmitter.inheritedVelocityAmount = serializationObject.inheritedVelocityAmount;
  62283. subEmitter.particleSystem._isSubEmitter = true;
  62284. return subEmitter;
  62285. };
  62286. /** Release associated resources */
  62287. SubEmitter.prototype.dispose = function () {
  62288. this.particleSystem.dispose();
  62289. };
  62290. return SubEmitter;
  62291. }());
  62292. BABYLON.SubEmitter = SubEmitter;
  62293. })(BABYLON || (BABYLON = {}));
  62294. //# sourceMappingURL=babylon.subEmitter.js.map
  62295. var BABYLON;
  62296. (function (BABYLON) {
  62297. /**
  62298. * 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.
  62299. *
  62300. * This returned material effects how the mesh will look based on the code in the shaders.
  62301. *
  62302. * @see http://doc.babylonjs.com/how_to/shader_material
  62303. */
  62304. var ShaderMaterial = /** @class */ (function (_super) {
  62305. __extends(ShaderMaterial, _super);
  62306. /**
  62307. * Instantiate a new shader material.
  62308. * 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.
  62309. * This returned material effects how the mesh will look based on the code in the shaders.
  62310. * @see http://doc.babylonjs.com/how_to/shader_material
  62311. * @param name Define the name of the material in the scene
  62312. * @param scene Define the scene the material belongs to
  62313. * @param shaderPath Defines the route to the shader code in one of three ways:
  62314. * - object - { vertex: "custom", fragment: "custom" }, used with BABYLON.Effect.ShadersStore["customVertexShader"] and BABYLON.Effect.ShadersStore["customFragmentShader"]
  62315. * - object - { vertexElement: "vertexShaderCode", fragmentElement: "fragmentShaderCode" }, used with shader code in <script> tags
  62316. * - string - "./COMMON_NAME", used with external files COMMON_NAME.vertex.fx and COMMON_NAME.fragment.fx in index.html folder.
  62317. * @param options Define the options used to create the shader
  62318. */
  62319. function ShaderMaterial(name, scene, shaderPath, options) {
  62320. if (options === void 0) { options = {}; }
  62321. var _this = _super.call(this, name, scene) || this;
  62322. _this._textures = {};
  62323. _this._textureArrays = {};
  62324. _this._floats = {};
  62325. _this._ints = {};
  62326. _this._floatsArrays = {};
  62327. _this._colors3 = {};
  62328. _this._colors3Arrays = {};
  62329. _this._colors4 = {};
  62330. _this._vectors2 = {};
  62331. _this._vectors3 = {};
  62332. _this._vectors4 = {};
  62333. _this._matrices = {};
  62334. _this._matrices3x3 = {};
  62335. _this._matrices2x2 = {};
  62336. _this._vectors2Arrays = {};
  62337. _this._vectors3Arrays = {};
  62338. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  62339. _this._shaderPath = shaderPath;
  62340. _this._options = __assign({ needAlphaBlending: false, needAlphaTesting: false, attributes: ["position", "normal", "uv"], uniforms: ["worldViewProjection"], uniformBuffers: [], samplers: [], defines: [] }, options);
  62341. return _this;
  62342. }
  62343. /**
  62344. * Gets the current class name of the material e.g. "ShaderMaterial"
  62345. * Mainly use in serialization.
  62346. * @returns the class name
  62347. */
  62348. ShaderMaterial.prototype.getClassName = function () {
  62349. return "ShaderMaterial";
  62350. };
  62351. /**
  62352. * Specifies if the material will require alpha blending
  62353. * @returns a boolean specifying if alpha blending is needed
  62354. */
  62355. ShaderMaterial.prototype.needAlphaBlending = function () {
  62356. return (this.alpha < 1.0) || this._options.needAlphaBlending;
  62357. };
  62358. /**
  62359. * Specifies if this material should be rendered in alpha test mode
  62360. * @returns a boolean specifying if an alpha test is needed.
  62361. */
  62362. ShaderMaterial.prototype.needAlphaTesting = function () {
  62363. return this._options.needAlphaTesting;
  62364. };
  62365. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  62366. if (this._options.uniforms.indexOf(uniformName) === -1) {
  62367. this._options.uniforms.push(uniformName);
  62368. }
  62369. };
  62370. /**
  62371. * Set a texture in the shader.
  62372. * @param name Define the name of the uniform samplers as defined in the shader
  62373. * @param texture Define the texture to bind to this sampler
  62374. * @return the material itself allowing "fluent" like uniform updates
  62375. */
  62376. ShaderMaterial.prototype.setTexture = function (name, texture) {
  62377. if (this._options.samplers.indexOf(name) === -1) {
  62378. this._options.samplers.push(name);
  62379. }
  62380. this._textures[name] = texture;
  62381. return this;
  62382. };
  62383. /**
  62384. * Set a texture array in the shader.
  62385. * @param name Define the name of the uniform sampler array as defined in the shader
  62386. * @param textures Define the list of textures to bind to this sampler
  62387. * @return the material itself allowing "fluent" like uniform updates
  62388. */
  62389. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  62390. if (this._options.samplers.indexOf(name) === -1) {
  62391. this._options.samplers.push(name);
  62392. }
  62393. this._checkUniform(name);
  62394. this._textureArrays[name] = textures;
  62395. return this;
  62396. };
  62397. /**
  62398. * Set a float in the shader.
  62399. * @param name Define the name of the uniform as defined in the shader
  62400. * @param value Define the value to give to the uniform
  62401. * @return the material itself allowing "fluent" like uniform updates
  62402. */
  62403. ShaderMaterial.prototype.setFloat = function (name, value) {
  62404. this._checkUniform(name);
  62405. this._floats[name] = value;
  62406. return this;
  62407. };
  62408. /**
  62409. * Set a int in the shader.
  62410. * @param name Define the name of the uniform as defined in the shader
  62411. * @param value Define the value to give to the uniform
  62412. * @return the material itself allowing "fluent" like uniform updates
  62413. */
  62414. ShaderMaterial.prototype.setInt = function (name, value) {
  62415. this._checkUniform(name);
  62416. this._ints[name] = value;
  62417. return this;
  62418. };
  62419. /**
  62420. * Set an array of floats in the shader.
  62421. * @param name Define the name of the uniform as defined in the shader
  62422. * @param value Define the value to give to the uniform
  62423. * @return the material itself allowing "fluent" like uniform updates
  62424. */
  62425. ShaderMaterial.prototype.setFloats = function (name, value) {
  62426. this._checkUniform(name);
  62427. this._floatsArrays[name] = value;
  62428. return this;
  62429. };
  62430. /**
  62431. * Set a vec3 in the shader from a Color3.
  62432. * @param name Define the name of the uniform as defined in the shader
  62433. * @param value Define the value to give to the uniform
  62434. * @return the material itself allowing "fluent" like uniform updates
  62435. */
  62436. ShaderMaterial.prototype.setColor3 = function (name, value) {
  62437. this._checkUniform(name);
  62438. this._colors3[name] = value;
  62439. return this;
  62440. };
  62441. /**
  62442. * Set a vec3 array in the shader from a Color3 array.
  62443. * @param name Define the name of the uniform as defined in the shader
  62444. * @param value Define the value to give to the uniform
  62445. * @return the material itself allowing "fluent" like uniform updates
  62446. */
  62447. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  62448. this._checkUniform(name);
  62449. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  62450. color.toArray(arr, arr.length);
  62451. return arr;
  62452. }, []);
  62453. return this;
  62454. };
  62455. /**
  62456. * Set a vec4 in the shader from a Color4.
  62457. * @param name Define the name of the uniform as defined in the shader
  62458. * @param value Define the value to give to the uniform
  62459. * @return the material itself allowing "fluent" like uniform updates
  62460. */
  62461. ShaderMaterial.prototype.setColor4 = function (name, value) {
  62462. this._checkUniform(name);
  62463. this._colors4[name] = value;
  62464. return this;
  62465. };
  62466. /**
  62467. * Set a vec2 in the shader from a Vector2.
  62468. * @param name Define the name of the uniform as defined in the shader
  62469. * @param value Define the value to give to the uniform
  62470. * @return the material itself allowing "fluent" like uniform updates
  62471. */
  62472. ShaderMaterial.prototype.setVector2 = function (name, value) {
  62473. this._checkUniform(name);
  62474. this._vectors2[name] = value;
  62475. return this;
  62476. };
  62477. /**
  62478. * Set a vec3 in the shader from a Vector3.
  62479. * @param name Define the name of the uniform as defined in the shader
  62480. * @param value Define the value to give to the uniform
  62481. * @return the material itself allowing "fluent" like uniform updates
  62482. */
  62483. ShaderMaterial.prototype.setVector3 = function (name, value) {
  62484. this._checkUniform(name);
  62485. this._vectors3[name] = value;
  62486. return this;
  62487. };
  62488. /**
  62489. * Set a vec4 in the shader from a Vector4.
  62490. * @param name Define the name of the uniform as defined in the shader
  62491. * @param value Define the value to give to the uniform
  62492. * @return the material itself allowing "fluent" like uniform updates
  62493. */
  62494. ShaderMaterial.prototype.setVector4 = function (name, value) {
  62495. this._checkUniform(name);
  62496. this._vectors4[name] = value;
  62497. return this;
  62498. };
  62499. /**
  62500. * Set a mat4 in the shader from a Matrix.
  62501. * @param name Define the name of the uniform as defined in the shader
  62502. * @param value Define the value to give to the uniform
  62503. * @return the material itself allowing "fluent" like uniform updates
  62504. */
  62505. ShaderMaterial.prototype.setMatrix = function (name, value) {
  62506. this._checkUniform(name);
  62507. this._matrices[name] = value;
  62508. return this;
  62509. };
  62510. /**
  62511. * Set a mat3 in the shader from a Float32Array.
  62512. * @param name Define the name of the uniform as defined in the shader
  62513. * @param value Define the value to give to the uniform
  62514. * @return the material itself allowing "fluent" like uniform updates
  62515. */
  62516. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  62517. this._checkUniform(name);
  62518. this._matrices3x3[name] = value;
  62519. return this;
  62520. };
  62521. /**
  62522. * Set a mat2 in the shader from a Float32Array.
  62523. * @param name Define the name of the uniform as defined in the shader
  62524. * @param value Define the value to give to the uniform
  62525. * @return the material itself allowing "fluent" like uniform updates
  62526. */
  62527. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  62528. this._checkUniform(name);
  62529. this._matrices2x2[name] = value;
  62530. return this;
  62531. };
  62532. /**
  62533. * Set a vec2 array in the shader from a number array.
  62534. * @param name Define the name of the uniform as defined in the shader
  62535. * @param value Define the value to give to the uniform
  62536. * @return the material itself allowing "fluent" like uniform updates
  62537. */
  62538. ShaderMaterial.prototype.setArray2 = function (name, value) {
  62539. this._checkUniform(name);
  62540. this._vectors2Arrays[name] = value;
  62541. return this;
  62542. };
  62543. /**
  62544. * Set a vec3 array in the shader from a number array.
  62545. * @param name Define the name of the uniform as defined in the shader
  62546. * @param value Define the value to give to the uniform
  62547. * @return the material itself allowing "fluent" like uniform updates
  62548. */
  62549. ShaderMaterial.prototype.setArray3 = function (name, value) {
  62550. this._checkUniform(name);
  62551. this._vectors3Arrays[name] = value;
  62552. return this;
  62553. };
  62554. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  62555. if (!mesh) {
  62556. return true;
  62557. }
  62558. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  62559. return false;
  62560. }
  62561. return false;
  62562. };
  62563. /**
  62564. * Checks if the material is ready to render the requested mesh
  62565. * @param mesh Define the mesh to render
  62566. * @param useInstances Define whether or not the material is used with instances
  62567. * @returns true if ready, otherwise false
  62568. */
  62569. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  62570. var scene = this.getScene();
  62571. var engine = scene.getEngine();
  62572. if (!this.checkReadyOnEveryCall) {
  62573. if (this._renderId === scene.getRenderId()) {
  62574. if (this._checkCache(scene, mesh, useInstances)) {
  62575. return true;
  62576. }
  62577. }
  62578. }
  62579. // Instances
  62580. var defines = [];
  62581. var attribs = [];
  62582. var fallbacks = new BABYLON.EffectFallbacks();
  62583. for (var index = 0; index < this._options.defines.length; index++) {
  62584. defines.push(this._options.defines[index]);
  62585. }
  62586. for (var index = 0; index < this._options.attributes.length; index++) {
  62587. attribs.push(this._options.attributes[index]);
  62588. }
  62589. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  62590. attribs.push(BABYLON.VertexBuffer.ColorKind);
  62591. defines.push("#define VERTEXCOLOR");
  62592. }
  62593. if (useInstances) {
  62594. defines.push("#define INSTANCES");
  62595. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  62596. }
  62597. // Bones
  62598. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  62599. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  62600. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  62601. if (mesh.numBoneInfluencers > 4) {
  62602. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  62603. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  62604. }
  62605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  62606. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  62607. fallbacks.addCPUSkinningFallback(0, mesh);
  62608. if (this._options.uniforms.indexOf("mBones") === -1) {
  62609. this._options.uniforms.push("mBones");
  62610. }
  62611. }
  62612. else {
  62613. defines.push("#define NUM_BONE_INFLUENCERS 0");
  62614. }
  62615. // Textures
  62616. for (var name in this._textures) {
  62617. if (!this._textures[name].isReady()) {
  62618. return false;
  62619. }
  62620. }
  62621. // Alpha test
  62622. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  62623. defines.push("#define ALPHATEST");
  62624. }
  62625. var previousEffect = this._effect;
  62626. var join = defines.join("\n");
  62627. this._effect = engine.createEffect(this._shaderPath, {
  62628. attributes: attribs,
  62629. uniformsNames: this._options.uniforms,
  62630. uniformBuffersNames: this._options.uniformBuffers,
  62631. samplers: this._options.samplers,
  62632. defines: join,
  62633. fallbacks: fallbacks,
  62634. onCompiled: this.onCompiled,
  62635. onError: this.onError
  62636. }, engine);
  62637. if (!this._effect.isReady()) {
  62638. return false;
  62639. }
  62640. if (previousEffect !== this._effect) {
  62641. scene.resetCachedMaterial();
  62642. }
  62643. this._renderId = scene.getRenderId();
  62644. return true;
  62645. };
  62646. /**
  62647. * Binds the world matrix to the material
  62648. * @param world defines the world transformation matrix
  62649. */
  62650. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  62651. var scene = this.getScene();
  62652. if (!this._effect) {
  62653. return;
  62654. }
  62655. if (this._options.uniforms.indexOf("world") !== -1) {
  62656. this._effect.setMatrix("world", world);
  62657. }
  62658. if (this._options.uniforms.indexOf("worldView") !== -1) {
  62659. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  62660. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  62661. }
  62662. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  62663. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  62664. }
  62665. };
  62666. /**
  62667. * Binds the material to the mesh
  62668. * @param world defines the world transformation matrix
  62669. * @param mesh defines the mesh to bind the material to
  62670. */
  62671. ShaderMaterial.prototype.bind = function (world, mesh) {
  62672. // Std values
  62673. this.bindOnlyWorldMatrix(world);
  62674. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  62675. if (this._options.uniforms.indexOf("view") !== -1) {
  62676. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  62677. }
  62678. if (this._options.uniforms.indexOf("projection") !== -1) {
  62679. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  62680. }
  62681. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  62682. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  62683. }
  62684. // Bones
  62685. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  62686. var name;
  62687. // Texture
  62688. for (name in this._textures) {
  62689. this._effect.setTexture(name, this._textures[name]);
  62690. }
  62691. // Texture arrays
  62692. for (name in this._textureArrays) {
  62693. this._effect.setTextureArray(name, this._textureArrays[name]);
  62694. }
  62695. // Int
  62696. for (name in this._ints) {
  62697. this._effect.setInt(name, this._ints[name]);
  62698. }
  62699. // Float
  62700. for (name in this._floats) {
  62701. this._effect.setFloat(name, this._floats[name]);
  62702. }
  62703. // Floats
  62704. for (name in this._floatsArrays) {
  62705. this._effect.setArray(name, this._floatsArrays[name]);
  62706. }
  62707. // Color3
  62708. for (name in this._colors3) {
  62709. this._effect.setColor3(name, this._colors3[name]);
  62710. }
  62711. for (name in this._colors3Arrays) {
  62712. this._effect.setArray3(name, this._colors3Arrays[name]);
  62713. }
  62714. // Color4
  62715. for (name in this._colors4) {
  62716. var color = this._colors4[name];
  62717. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  62718. }
  62719. // Vector2
  62720. for (name in this._vectors2) {
  62721. this._effect.setVector2(name, this._vectors2[name]);
  62722. }
  62723. // Vector3
  62724. for (name in this._vectors3) {
  62725. this._effect.setVector3(name, this._vectors3[name]);
  62726. }
  62727. // Vector4
  62728. for (name in this._vectors4) {
  62729. this._effect.setVector4(name, this._vectors4[name]);
  62730. }
  62731. // Matrix
  62732. for (name in this._matrices) {
  62733. this._effect.setMatrix(name, this._matrices[name]);
  62734. }
  62735. // Matrix 3x3
  62736. for (name in this._matrices3x3) {
  62737. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  62738. }
  62739. // Matrix 2x2
  62740. for (name in this._matrices2x2) {
  62741. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  62742. }
  62743. // Vector2Array
  62744. for (name in this._vectors2Arrays) {
  62745. this._effect.setArray2(name, this._vectors2Arrays[name]);
  62746. }
  62747. // Vector3Array
  62748. for (name in this._vectors3Arrays) {
  62749. this._effect.setArray3(name, this._vectors3Arrays[name]);
  62750. }
  62751. }
  62752. this._afterBind(mesh);
  62753. };
  62754. /**
  62755. * Gets the active textures from the material
  62756. * @returns an array of textures
  62757. */
  62758. ShaderMaterial.prototype.getActiveTextures = function () {
  62759. var activeTextures = _super.prototype.getActiveTextures.call(this);
  62760. for (var name in this._textures) {
  62761. activeTextures.push(this._textures[name]);
  62762. }
  62763. for (var name in this._textureArrays) {
  62764. var array = this._textureArrays[name];
  62765. for (var index = 0; index < array.length; index++) {
  62766. activeTextures.push(array[index]);
  62767. }
  62768. }
  62769. return activeTextures;
  62770. };
  62771. /**
  62772. * Specifies if the material uses a texture
  62773. * @param texture defines the texture to check against the material
  62774. * @returns a boolean specifying if the material uses the texture
  62775. */
  62776. ShaderMaterial.prototype.hasTexture = function (texture) {
  62777. if (_super.prototype.hasTexture.call(this, texture)) {
  62778. return true;
  62779. }
  62780. for (var name in this._textures) {
  62781. if (this._textures[name] === texture) {
  62782. return true;
  62783. }
  62784. }
  62785. for (var name in this._textureArrays) {
  62786. var array = this._textureArrays[name];
  62787. for (var index = 0; index < array.length; index++) {
  62788. if (array[index] === texture) {
  62789. return true;
  62790. }
  62791. }
  62792. }
  62793. return false;
  62794. };
  62795. /**
  62796. * Makes a duplicate of the material, and gives it a new name
  62797. * @param name defines the new name for the duplicated material
  62798. * @returns the cloned material
  62799. */
  62800. ShaderMaterial.prototype.clone = function (name) {
  62801. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  62802. return newShaderMaterial;
  62803. };
  62804. /**
  62805. * Disposes the material
  62806. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  62807. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  62808. */
  62809. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  62810. if (forceDisposeTextures) {
  62811. var name;
  62812. for (name in this._textures) {
  62813. this._textures[name].dispose();
  62814. }
  62815. for (name in this._textureArrays) {
  62816. var array = this._textureArrays[name];
  62817. for (var index = 0; index < array.length; index++) {
  62818. array[index].dispose();
  62819. }
  62820. }
  62821. }
  62822. this._textures = {};
  62823. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  62824. };
  62825. /**
  62826. * Serializes this material in a JSON representation
  62827. * @returns the serialized material object
  62828. */
  62829. ShaderMaterial.prototype.serialize = function () {
  62830. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  62831. serializationObject.customType = "BABYLON.ShaderMaterial";
  62832. serializationObject.options = this._options;
  62833. serializationObject.shaderPath = this._shaderPath;
  62834. var name;
  62835. // Texture
  62836. serializationObject.textures = {};
  62837. for (name in this._textures) {
  62838. serializationObject.textures[name] = this._textures[name].serialize();
  62839. }
  62840. // Texture arrays
  62841. serializationObject.textureArrays = {};
  62842. for (name in this._textureArrays) {
  62843. serializationObject.textureArrays[name] = [];
  62844. var array = this._textureArrays[name];
  62845. for (var index = 0; index < array.length; index++) {
  62846. serializationObject.textureArrays[name].push(array[index].serialize());
  62847. }
  62848. }
  62849. // Float
  62850. serializationObject.floats = {};
  62851. for (name in this._floats) {
  62852. serializationObject.floats[name] = this._floats[name];
  62853. }
  62854. // Float s
  62855. serializationObject.FloatArrays = {};
  62856. for (name in this._floatsArrays) {
  62857. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  62858. }
  62859. // Color3
  62860. serializationObject.colors3 = {};
  62861. for (name in this._colors3) {
  62862. serializationObject.colors3[name] = this._colors3[name].asArray();
  62863. }
  62864. // Color3 array
  62865. serializationObject.colors3Arrays = {};
  62866. for (name in this._colors3Arrays) {
  62867. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  62868. }
  62869. // Color4
  62870. serializationObject.colors4 = {};
  62871. for (name in this._colors4) {
  62872. serializationObject.colors4[name] = this._colors4[name].asArray();
  62873. }
  62874. // Vector2
  62875. serializationObject.vectors2 = {};
  62876. for (name in this._vectors2) {
  62877. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  62878. }
  62879. // Vector3
  62880. serializationObject.vectors3 = {};
  62881. for (name in this._vectors3) {
  62882. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  62883. }
  62884. // Vector4
  62885. serializationObject.vectors4 = {};
  62886. for (name in this._vectors4) {
  62887. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  62888. }
  62889. // Matrix
  62890. serializationObject.matrices = {};
  62891. for (name in this._matrices) {
  62892. serializationObject.matrices[name] = this._matrices[name].asArray();
  62893. }
  62894. // Matrix 3x3
  62895. serializationObject.matrices3x3 = {};
  62896. for (name in this._matrices3x3) {
  62897. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  62898. }
  62899. // Matrix 2x2
  62900. serializationObject.matrices2x2 = {};
  62901. for (name in this._matrices2x2) {
  62902. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  62903. }
  62904. // Vector2Array
  62905. serializationObject.vectors2Arrays = {};
  62906. for (name in this._vectors2Arrays) {
  62907. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  62908. }
  62909. // Vector3Array
  62910. serializationObject.vectors3Arrays = {};
  62911. for (name in this._vectors3Arrays) {
  62912. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  62913. }
  62914. return serializationObject;
  62915. };
  62916. /**
  62917. * Creates a shader material from parsed shader material data
  62918. * @param source defines the JSON represnetation of the material
  62919. * @param scene defines the hosting scene
  62920. * @param rootUrl defines the root URL to use to load textures and relative dependencies
  62921. * @returns a new material
  62922. */
  62923. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  62924. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  62925. var name;
  62926. // Texture
  62927. for (name in source.textures) {
  62928. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  62929. }
  62930. // Texture arrays
  62931. for (name in source.textureArrays) {
  62932. var array = source.textureArrays[name];
  62933. var textureArray = new Array();
  62934. for (var index = 0; index < array.length; index++) {
  62935. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  62936. }
  62937. material.setTextureArray(name, textureArray);
  62938. }
  62939. // Float
  62940. for (name in source.floats) {
  62941. material.setFloat(name, source.floats[name]);
  62942. }
  62943. // Float s
  62944. for (name in source.floatsArrays) {
  62945. material.setFloats(name, source.floatsArrays[name]);
  62946. }
  62947. // Color3
  62948. for (name in source.colors3) {
  62949. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  62950. }
  62951. // Color3 arrays
  62952. for (name in source.colors3Arrays) {
  62953. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  62954. if (i % 3 === 0) {
  62955. arr.push([num]);
  62956. }
  62957. else {
  62958. arr[arr.length - 1].push(num);
  62959. }
  62960. return arr;
  62961. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  62962. material.setColor3Array(name, colors);
  62963. }
  62964. // Color4
  62965. for (name in source.colors4) {
  62966. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  62967. }
  62968. // Vector2
  62969. for (name in source.vectors2) {
  62970. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  62971. }
  62972. // Vector3
  62973. for (name in source.vectors3) {
  62974. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  62975. }
  62976. // Vector4
  62977. for (name in source.vectors4) {
  62978. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  62979. }
  62980. // Matrix
  62981. for (name in source.matrices) {
  62982. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  62983. }
  62984. // Matrix 3x3
  62985. for (name in source.matrices3x3) {
  62986. material.setMatrix3x3(name, source.matrices3x3[name]);
  62987. }
  62988. // Matrix 2x2
  62989. for (name in source.matrices2x2) {
  62990. material.setMatrix2x2(name, source.matrices2x2[name]);
  62991. }
  62992. // Vector2Array
  62993. for (name in source.vectors2Arrays) {
  62994. material.setArray2(name, source.vectors2Arrays[name]);
  62995. }
  62996. // Vector3Array
  62997. for (name in source.vectors3Arrays) {
  62998. material.setArray3(name, source.vectors3Arrays[name]);
  62999. }
  63000. return material;
  63001. };
  63002. return ShaderMaterial;
  63003. }(BABYLON.Material));
  63004. BABYLON.ShaderMaterial = ShaderMaterial;
  63005. })(BABYLON || (BABYLON = {}));
  63006. //# sourceMappingURL=babylon.shaderMaterial.js.map
  63007. var BABYLON;
  63008. (function (BABYLON) {
  63009. /**
  63010. * Mesh representing the gorund
  63011. */
  63012. var GroundMesh = /** @class */ (function (_super) {
  63013. __extends(GroundMesh, _super);
  63014. function GroundMesh(name, scene) {
  63015. var _this = _super.call(this, name, scene) || this;
  63016. /** If octree should be generated */
  63017. _this.generateOctree = false;
  63018. return _this;
  63019. }
  63020. /**
  63021. * "GroundMesh"
  63022. * @returns "GroundMesh"
  63023. */
  63024. GroundMesh.prototype.getClassName = function () {
  63025. return "GroundMesh";
  63026. };
  63027. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  63028. /**
  63029. * The minimum of x and y subdivisions
  63030. */
  63031. get: function () {
  63032. return Math.min(this._subdivisionsX, this._subdivisionsY);
  63033. },
  63034. enumerable: true,
  63035. configurable: true
  63036. });
  63037. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  63038. /**
  63039. * X subdivisions
  63040. */
  63041. get: function () {
  63042. return this._subdivisionsX;
  63043. },
  63044. enumerable: true,
  63045. configurable: true
  63046. });
  63047. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  63048. /**
  63049. * Y subdivisions
  63050. */
  63051. get: function () {
  63052. return this._subdivisionsY;
  63053. },
  63054. enumerable: true,
  63055. configurable: true
  63056. });
  63057. /**
  63058. * This function will update an octree to help to select the right submeshes for rendering, picking and collision computations.
  63059. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  63060. * @param chunksCount the number of subdivisions for x and y
  63061. * @param octreeBlocksSize (Default: 32)
  63062. */
  63063. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  63064. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  63065. this._subdivisionsX = chunksCount;
  63066. this._subdivisionsY = chunksCount;
  63067. this.subdivide(chunksCount);
  63068. // Call the octree system optimization if it is defined.
  63069. var thisAsAny = this;
  63070. if (thisAsAny.createOrUpdateSubmeshesOctree) {
  63071. thisAsAny.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  63072. }
  63073. };
  63074. /**
  63075. * Returns a height (y) value in the Worl system :
  63076. * the ground altitude at the coordinates (x, z) expressed in the World system.
  63077. * @param x x coordinate
  63078. * @param z z coordinate
  63079. * @returns the ground y position if (x, z) are outside the ground surface.
  63080. */
  63081. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  63082. var world = this.getWorldMatrix();
  63083. var invMat = BABYLON.Tmp.Matrix[5];
  63084. world.invertToRef(invMat);
  63085. var tmpVect = BABYLON.Tmp.Vector3[8];
  63086. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  63087. x = tmpVect.x;
  63088. z = tmpVect.z;
  63089. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63090. return this.position.y;
  63091. }
  63092. if (!this._heightQuads || this._heightQuads.length == 0) {
  63093. this._initHeightQuads();
  63094. this._computeHeightQuads();
  63095. }
  63096. var facet = this._getFacetAt(x, z);
  63097. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  63098. // return y in the World system
  63099. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  63100. return tmpVect.y;
  63101. };
  63102. /**
  63103. * Returns a normalized vector (Vector3) orthogonal to the ground
  63104. * at the ground coordinates (x, z) expressed in the World system.
  63105. * @param x x coordinate
  63106. * @param z z coordinate
  63107. * @returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  63108. */
  63109. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  63110. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  63111. this.getNormalAtCoordinatesToRef(x, z, normal);
  63112. return normal;
  63113. };
  63114. /**
  63115. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  63116. * at the ground coordinates (x, z) expressed in the World system.
  63117. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  63118. * @param x x coordinate
  63119. * @param z z coordinate
  63120. * @param ref vector to store the result
  63121. * @returns the GroundMesh.
  63122. */
  63123. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  63124. var world = this.getWorldMatrix();
  63125. var tmpMat = BABYLON.Tmp.Matrix[5];
  63126. world.invertToRef(tmpMat);
  63127. var tmpVect = BABYLON.Tmp.Vector3[8];
  63128. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  63129. x = tmpVect.x;
  63130. z = tmpVect.z;
  63131. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  63132. return this;
  63133. }
  63134. if (!this._heightQuads || this._heightQuads.length == 0) {
  63135. this._initHeightQuads();
  63136. this._computeHeightQuads();
  63137. }
  63138. var facet = this._getFacetAt(x, z);
  63139. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  63140. return this;
  63141. };
  63142. /**
  63143. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  63144. * if the ground has been updated.
  63145. * This can be used in the render loop.
  63146. * @returns the GroundMesh.
  63147. */
  63148. GroundMesh.prototype.updateCoordinateHeights = function () {
  63149. if (!this._heightQuads || this._heightQuads.length == 0) {
  63150. this._initHeightQuads();
  63151. }
  63152. this._computeHeightQuads();
  63153. return this;
  63154. };
  63155. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  63156. GroundMesh.prototype._getFacetAt = function (x, z) {
  63157. // retrieve col and row from x, z coordinates in the ground local system
  63158. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  63159. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  63160. var quad = this._heightQuads[row * this._subdivisionsX + col];
  63161. var facet;
  63162. if (z < quad.slope.x * x + quad.slope.y) {
  63163. facet = quad.facet1;
  63164. }
  63165. else {
  63166. facet = quad.facet2;
  63167. }
  63168. return facet;
  63169. };
  63170. // Creates and populates the heightMap array with "facet" elements :
  63171. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  63172. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63173. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63174. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63175. // Returns the GroundMesh.
  63176. GroundMesh.prototype._initHeightQuads = function () {
  63177. var subdivisionsX = this._subdivisionsX;
  63178. var subdivisionsY = this._subdivisionsY;
  63179. this._heightQuads = new Array();
  63180. for (var row = 0; row < subdivisionsY; row++) {
  63181. for (var col = 0; col < subdivisionsX; col++) {
  63182. 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) };
  63183. this._heightQuads[row * subdivisionsX + col] = quad;
  63184. }
  63185. }
  63186. return this;
  63187. };
  63188. // Compute each quad element values and update the the heightMap array :
  63189. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  63190. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  63191. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  63192. // Returns the GroundMesh.
  63193. GroundMesh.prototype._computeHeightQuads = function () {
  63194. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  63195. if (!positions) {
  63196. return this;
  63197. }
  63198. var v1 = BABYLON.Tmp.Vector3[3];
  63199. var v2 = BABYLON.Tmp.Vector3[2];
  63200. var v3 = BABYLON.Tmp.Vector3[1];
  63201. var v4 = BABYLON.Tmp.Vector3[0];
  63202. var v1v2 = BABYLON.Tmp.Vector3[4];
  63203. var v1v3 = BABYLON.Tmp.Vector3[5];
  63204. var v1v4 = BABYLON.Tmp.Vector3[6];
  63205. var norm1 = BABYLON.Tmp.Vector3[7];
  63206. var norm2 = BABYLON.Tmp.Vector3[8];
  63207. var i = 0;
  63208. var j = 0;
  63209. var k = 0;
  63210. var cd = 0; // 2D slope coefficient : z = cd * x + h
  63211. var h = 0;
  63212. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  63213. var d2 = 0;
  63214. var subdivisionsX = this._subdivisionsX;
  63215. var subdivisionsY = this._subdivisionsY;
  63216. for (var row = 0; row < subdivisionsY; row++) {
  63217. for (var col = 0; col < subdivisionsX; col++) {
  63218. i = col * 3;
  63219. j = row * (subdivisionsX + 1) * 3;
  63220. k = (row + 1) * (subdivisionsX + 1) * 3;
  63221. v1.x = positions[j + i];
  63222. v1.y = positions[j + i + 1];
  63223. v1.z = positions[j + i + 2];
  63224. v2.x = positions[j + i + 3];
  63225. v2.y = positions[j + i + 4];
  63226. v2.z = positions[j + i + 5];
  63227. v3.x = positions[k + i];
  63228. v3.y = positions[k + i + 1];
  63229. v3.z = positions[k + i + 2];
  63230. v4.x = positions[k + i + 3];
  63231. v4.y = positions[k + i + 4];
  63232. v4.z = positions[k + i + 5];
  63233. // 2D slope V1V4
  63234. cd = (v4.z - v1.z) / (v4.x - v1.x);
  63235. h = v1.z - cd * v1.x; // v1 belongs to the slope
  63236. // facet equations :
  63237. // we compute each facet normal vector
  63238. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  63239. // we compute the value d by applying the equation to v1 which belongs to the plane
  63240. // then we store the facet equation in a Vector4
  63241. v2.subtractToRef(v1, v1v2);
  63242. v3.subtractToRef(v1, v1v3);
  63243. v4.subtractToRef(v1, v1v4);
  63244. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  63245. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  63246. norm1.normalize();
  63247. norm2.normalize();
  63248. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  63249. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  63250. var quad = this._heightQuads[row * subdivisionsX + col];
  63251. quad.slope.copyFromFloats(cd, h);
  63252. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  63253. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  63254. }
  63255. }
  63256. return this;
  63257. };
  63258. /**
  63259. * Serializes this ground mesh
  63260. * @param serializationObject object to write serialization to
  63261. */
  63262. GroundMesh.prototype.serialize = function (serializationObject) {
  63263. _super.prototype.serialize.call(this, serializationObject);
  63264. serializationObject.subdivisionsX = this._subdivisionsX;
  63265. serializationObject.subdivisionsY = this._subdivisionsY;
  63266. serializationObject.minX = this._minX;
  63267. serializationObject.maxX = this._maxX;
  63268. serializationObject.minZ = this._minZ;
  63269. serializationObject.maxZ = this._maxZ;
  63270. serializationObject.width = this._width;
  63271. serializationObject.height = this._height;
  63272. };
  63273. /**
  63274. * Parses a serialized ground mesh
  63275. * @param parsedMesh the serialized mesh
  63276. * @param scene the scene to create the ground mesh in
  63277. * @returns the created ground mesh
  63278. */
  63279. GroundMesh.Parse = function (parsedMesh, scene) {
  63280. var result = new GroundMesh(parsedMesh.name, scene);
  63281. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  63282. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  63283. result._minX = parsedMesh.minX;
  63284. result._maxX = parsedMesh.maxX;
  63285. result._minZ = parsedMesh.minZ;
  63286. result._maxZ = parsedMesh.maxZ;
  63287. result._width = parsedMesh.width;
  63288. result._height = parsedMesh.height;
  63289. return result;
  63290. };
  63291. return GroundMesh;
  63292. }(BABYLON.Mesh));
  63293. BABYLON.GroundMesh = GroundMesh;
  63294. })(BABYLON || (BABYLON = {}));
  63295. //# sourceMappingURL=babylon.groundMesh.js.map
  63296. var BABYLON;
  63297. (function (BABYLON) {
  63298. /**
  63299. * Creates an instance based on a source mesh.
  63300. */
  63301. var InstancedMesh = /** @class */ (function (_super) {
  63302. __extends(InstancedMesh, _super);
  63303. function InstancedMesh(name, source) {
  63304. var _this = _super.call(this, name, source.getScene()) || this;
  63305. source.instances.push(_this);
  63306. _this._sourceMesh = source;
  63307. _this.position.copyFrom(source.position);
  63308. _this.rotation.copyFrom(source.rotation);
  63309. _this.scaling.copyFrom(source.scaling);
  63310. if (source.rotationQuaternion) {
  63311. _this.rotationQuaternion = source.rotationQuaternion.clone();
  63312. }
  63313. _this.infiniteDistance = source.infiniteDistance;
  63314. _this.setPivotMatrix(source.getPivotMatrix());
  63315. _this.refreshBoundingInfo();
  63316. _this._syncSubMeshes();
  63317. return _this;
  63318. }
  63319. /**
  63320. * Returns the string "InstancedMesh".
  63321. */
  63322. InstancedMesh.prototype.getClassName = function () {
  63323. return "InstancedMesh";
  63324. };
  63325. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  63326. // Methods
  63327. /**
  63328. * If the source mesh receives shadows
  63329. */
  63330. get: function () {
  63331. return this._sourceMesh.receiveShadows;
  63332. },
  63333. enumerable: true,
  63334. configurable: true
  63335. });
  63336. Object.defineProperty(InstancedMesh.prototype, "material", {
  63337. /**
  63338. * The material of the source mesh
  63339. */
  63340. get: function () {
  63341. return this._sourceMesh.material;
  63342. },
  63343. enumerable: true,
  63344. configurable: true
  63345. });
  63346. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  63347. /**
  63348. * Visibility of the source mesh
  63349. */
  63350. get: function () {
  63351. return this._sourceMesh.visibility;
  63352. },
  63353. enumerable: true,
  63354. configurable: true
  63355. });
  63356. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  63357. /**
  63358. * Skeleton of the source mesh
  63359. */
  63360. get: function () {
  63361. return this._sourceMesh.skeleton;
  63362. },
  63363. enumerable: true,
  63364. configurable: true
  63365. });
  63366. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  63367. /**
  63368. * Rendering ground id of the source mesh
  63369. */
  63370. get: function () {
  63371. return this._sourceMesh.renderingGroupId;
  63372. },
  63373. set: function (value) {
  63374. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  63375. return;
  63376. }
  63377. //no-op with warning
  63378. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  63379. },
  63380. enumerable: true,
  63381. configurable: true
  63382. });
  63383. /**
  63384. * Returns the total number of vertices (integer).
  63385. */
  63386. InstancedMesh.prototype.getTotalVertices = function () {
  63387. return this._sourceMesh.getTotalVertices();
  63388. };
  63389. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  63390. /**
  63391. * The source mesh of the instance
  63392. */
  63393. get: function () {
  63394. return this._sourceMesh;
  63395. },
  63396. enumerable: true,
  63397. configurable: true
  63398. });
  63399. /**
  63400. * Is this node ready to be used/rendered
  63401. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  63402. * @return {boolean} is it ready
  63403. */
  63404. InstancedMesh.prototype.isReady = function (completeCheck) {
  63405. if (completeCheck === void 0) { completeCheck = false; }
  63406. return this._sourceMesh.isReady(completeCheck, true);
  63407. };
  63408. /**
  63409. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  63410. * @param kind kind of verticies to retreive (eg. positons, normals, uvs, etc.)
  63411. * @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.
  63412. * @returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  63413. */
  63414. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  63415. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  63416. };
  63417. /**
  63418. * Sets the vertex data of the mesh geometry for the requested `kind`.
  63419. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  63420. * The `data` are either a numeric array either a Float32Array.
  63421. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  63422. * 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).
  63423. * Note that a new underlying VertexBuffer object is created each call.
  63424. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  63425. *
  63426. * Possible `kind` values :
  63427. * - BABYLON.VertexBuffer.PositionKind
  63428. * - BABYLON.VertexBuffer.UVKind
  63429. * - BABYLON.VertexBuffer.UV2Kind
  63430. * - BABYLON.VertexBuffer.UV3Kind
  63431. * - BABYLON.VertexBuffer.UV4Kind
  63432. * - BABYLON.VertexBuffer.UV5Kind
  63433. * - BABYLON.VertexBuffer.UV6Kind
  63434. * - BABYLON.VertexBuffer.ColorKind
  63435. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63436. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63437. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63438. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63439. *
  63440. * Returns the Mesh.
  63441. */
  63442. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  63443. if (this.sourceMesh) {
  63444. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  63445. }
  63446. return this.sourceMesh;
  63447. };
  63448. /**
  63449. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  63450. * If the mesh has no geometry, it is simply returned as it is.
  63451. * The `data` are either a numeric array either a Float32Array.
  63452. * No new underlying VertexBuffer object is created.
  63453. * 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.
  63454. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  63455. *
  63456. * Possible `kind` values :
  63457. * - BABYLON.VertexBuffer.PositionKind
  63458. * - BABYLON.VertexBuffer.UVKind
  63459. * - BABYLON.VertexBuffer.UV2Kind
  63460. * - BABYLON.VertexBuffer.UV3Kind
  63461. * - BABYLON.VertexBuffer.UV4Kind
  63462. * - BABYLON.VertexBuffer.UV5Kind
  63463. * - BABYLON.VertexBuffer.UV6Kind
  63464. * - BABYLON.VertexBuffer.ColorKind
  63465. * - BABYLON.VertexBuffer.MatricesIndicesKind
  63466. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  63467. * - BABYLON.VertexBuffer.MatricesWeightsKind
  63468. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  63469. *
  63470. * Returns the Mesh.
  63471. */
  63472. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  63473. if (this.sourceMesh) {
  63474. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  63475. }
  63476. return this.sourceMesh;
  63477. };
  63478. /**
  63479. * Sets the mesh indices.
  63480. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  63481. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  63482. * This method creates a new index buffer each call.
  63483. * Returns the Mesh.
  63484. */
  63485. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  63486. if (totalVertices === void 0) { totalVertices = null; }
  63487. if (this.sourceMesh) {
  63488. this.sourceMesh.setIndices(indices, totalVertices);
  63489. }
  63490. return this.sourceMesh;
  63491. };
  63492. /**
  63493. * Boolean : True if the mesh owns the requested kind of data.
  63494. */
  63495. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  63496. return this._sourceMesh.isVerticesDataPresent(kind);
  63497. };
  63498. /**
  63499. * Returns an array of indices (IndicesArray).
  63500. */
  63501. InstancedMesh.prototype.getIndices = function () {
  63502. return this._sourceMesh.getIndices();
  63503. };
  63504. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  63505. get: function () {
  63506. return this._sourceMesh._positions;
  63507. },
  63508. enumerable: true,
  63509. configurable: true
  63510. });
  63511. /**
  63512. * Sets a new updated BoundingInfo to the mesh.
  63513. * @returns the mesh.
  63514. */
  63515. InstancedMesh.prototype.refreshBoundingInfo = function () {
  63516. var meshBB = this._sourceMesh.getBoundingInfo();
  63517. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  63518. this._updateBoundingInfo();
  63519. return this;
  63520. };
  63521. /** @hidden */
  63522. InstancedMesh.prototype._preActivate = function () {
  63523. if (this._currentLOD) {
  63524. this._currentLOD._preActivate();
  63525. }
  63526. return this;
  63527. };
  63528. /** @hidden */
  63529. InstancedMesh.prototype._activate = function (renderId) {
  63530. if (this._currentLOD) {
  63531. this._currentLOD._registerInstanceForRenderId(this, renderId);
  63532. }
  63533. return this;
  63534. };
  63535. /**
  63536. * Returns the current associated LOD AbstractMesh.
  63537. */
  63538. InstancedMesh.prototype.getLOD = function (camera) {
  63539. if (!camera) {
  63540. return this;
  63541. }
  63542. var boundingInfo = this.getBoundingInfo();
  63543. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  63544. if (this._currentLOD === this.sourceMesh) {
  63545. return this;
  63546. }
  63547. return this._currentLOD;
  63548. };
  63549. /** @hidden */
  63550. InstancedMesh.prototype._syncSubMeshes = function () {
  63551. this.releaseSubMeshes();
  63552. if (this._sourceMesh.subMeshes) {
  63553. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  63554. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  63555. }
  63556. }
  63557. return this;
  63558. };
  63559. /** @hidden */
  63560. InstancedMesh.prototype._generatePointsArray = function () {
  63561. return this._sourceMesh._generatePointsArray();
  63562. };
  63563. /**
  63564. * Creates a new InstancedMesh from the current mesh.
  63565. * - name (string) : the cloned mesh name
  63566. * - newParent (optional Node) : the optional Node to parent the clone to.
  63567. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  63568. *
  63569. * Returns the clone.
  63570. */
  63571. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63572. var result = this._sourceMesh.createInstance(name);
  63573. // Deep copy
  63574. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  63575. // Bounding info
  63576. this.refreshBoundingInfo();
  63577. // Parent
  63578. if (newParent) {
  63579. result.parent = newParent;
  63580. }
  63581. if (!doNotCloneChildren) {
  63582. // Children
  63583. for (var index = 0; index < this.getScene().meshes.length; index++) {
  63584. var mesh = this.getScene().meshes[index];
  63585. if (mesh.parent === this) {
  63586. mesh.clone(mesh.name, result);
  63587. }
  63588. }
  63589. }
  63590. result.computeWorldMatrix(true);
  63591. return result;
  63592. };
  63593. /**
  63594. * Disposes the InstancedMesh.
  63595. * Returns nothing.
  63596. */
  63597. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  63598. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  63599. // Remove from mesh
  63600. var index = this._sourceMesh.instances.indexOf(this);
  63601. this._sourceMesh.instances.splice(index, 1);
  63602. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  63603. };
  63604. return InstancedMesh;
  63605. }(BABYLON.AbstractMesh));
  63606. BABYLON.InstancedMesh = InstancedMesh;
  63607. })(BABYLON || (BABYLON = {}));
  63608. //# sourceMappingURL=babylon.instancedMesh.js.map
  63609. var BABYLON;
  63610. (function (BABYLON) {
  63611. /**
  63612. * Line mesh
  63613. * @see https://doc.babylonjs.com/babylon101/parametric_shapes
  63614. */
  63615. var LinesMesh = /** @class */ (function (_super) {
  63616. __extends(LinesMesh, _super);
  63617. function LinesMesh(name, scene, parent, source, doNotCloneChildren,
  63618. /**
  63619. * If vertex color should be applied to the mesh
  63620. */
  63621. useVertexColor,
  63622. /**
  63623. * If vertex alpha should be applied to the mesh
  63624. */
  63625. useVertexAlpha) {
  63626. if (scene === void 0) { scene = null; }
  63627. if (parent === void 0) { parent = null; }
  63628. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  63629. _this.useVertexColor = useVertexColor;
  63630. _this.useVertexAlpha = useVertexAlpha;
  63631. /**
  63632. * Color of the line (Default: White)
  63633. */
  63634. _this.color = new BABYLON.Color3(1, 1, 1);
  63635. /**
  63636. * Alpha of the line (Default: 1)
  63637. */
  63638. _this.alpha = 1;
  63639. if (source) {
  63640. _this.color = source.color.clone();
  63641. _this.alpha = source.alpha;
  63642. _this.useVertexColor = source.useVertexColor;
  63643. _this.useVertexAlpha = source.useVertexAlpha;
  63644. }
  63645. _this._intersectionThreshold = 0.1;
  63646. var defines = [];
  63647. var options = {
  63648. attributes: [BABYLON.VertexBuffer.PositionKind, "world0", "world1", "world2", "world3"],
  63649. uniforms: ["world", "viewProjection"],
  63650. needAlphaBlending: true,
  63651. defines: defines
  63652. };
  63653. if (useVertexAlpha === false) {
  63654. options.needAlphaBlending = false;
  63655. }
  63656. if (!useVertexColor) {
  63657. options.uniforms.push("color");
  63658. }
  63659. else {
  63660. options.defines.push("#define VERTEXCOLOR");
  63661. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  63662. }
  63663. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  63664. return _this;
  63665. }
  63666. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  63667. /**
  63668. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63669. * This margin is expressed in world space coordinates, so its value may vary.
  63670. * Default value is 0.1
  63671. * @returns the intersection Threshold value.
  63672. */
  63673. get: function () {
  63674. return this._intersectionThreshold;
  63675. },
  63676. /**
  63677. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  63678. * This margin is expressed in world space coordinates, so its value may vary.
  63679. */
  63680. set: function (value) {
  63681. if (this._intersectionThreshold === value) {
  63682. return;
  63683. }
  63684. this._intersectionThreshold = value;
  63685. if (this.geometry) {
  63686. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  63687. }
  63688. },
  63689. enumerable: true,
  63690. configurable: true
  63691. });
  63692. /**
  63693. * Returns the string "LineMesh"
  63694. */
  63695. LinesMesh.prototype.getClassName = function () {
  63696. return "LinesMesh";
  63697. };
  63698. Object.defineProperty(LinesMesh.prototype, "material", {
  63699. /**
  63700. * @hidden
  63701. */
  63702. get: function () {
  63703. return this._colorShader;
  63704. },
  63705. /**
  63706. * @hidden
  63707. */
  63708. set: function (value) {
  63709. // Do nothing
  63710. },
  63711. enumerable: true,
  63712. configurable: true
  63713. });
  63714. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  63715. /**
  63716. * @hidden
  63717. */
  63718. get: function () {
  63719. return false;
  63720. },
  63721. enumerable: true,
  63722. configurable: true
  63723. });
  63724. /** @hidden */
  63725. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  63726. if (!this._geometry) {
  63727. return this;
  63728. }
  63729. // VBOs
  63730. this._geometry._bind(this._colorShader.getEffect());
  63731. // Color
  63732. if (!this.useVertexColor) {
  63733. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  63734. }
  63735. return this;
  63736. };
  63737. /** @hidden */
  63738. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  63739. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  63740. return this;
  63741. }
  63742. var engine = this.getScene().getEngine();
  63743. // Draw order
  63744. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  63745. return this;
  63746. };
  63747. /**
  63748. * Disposes of the line mesh
  63749. * @param doNotRecurse If children should be disposed
  63750. */
  63751. LinesMesh.prototype.dispose = function (doNotRecurse) {
  63752. this._colorShader.dispose();
  63753. _super.prototype.dispose.call(this, doNotRecurse);
  63754. };
  63755. /**
  63756. * Returns a new LineMesh object cloned from the current one.
  63757. */
  63758. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  63759. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  63760. };
  63761. return LinesMesh;
  63762. }(BABYLON.Mesh));
  63763. BABYLON.LinesMesh = LinesMesh;
  63764. })(BABYLON || (BABYLON = {}));
  63765. //# sourceMappingURL=babylon.linesMesh.js.map
  63766. var BABYLON;
  63767. (function (BABYLON) {
  63768. /**
  63769. * This class implement a typical dictionary using a string as key and the generic type T as value.
  63770. * The underlying implementation relies on an associative array to ensure the best performances.
  63771. * The value can be anything including 'null' but except 'undefined'
  63772. */
  63773. var StringDictionary = /** @class */ (function () {
  63774. function StringDictionary() {
  63775. this._count = 0;
  63776. this._data = {};
  63777. }
  63778. /**
  63779. * This will clear this dictionary and copy the content from the 'source' one.
  63780. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  63781. * @param source the dictionary to take the content from and copy to this dictionary
  63782. */
  63783. StringDictionary.prototype.copyFrom = function (source) {
  63784. var _this = this;
  63785. this.clear();
  63786. source.forEach(function (t, v) { return _this.add(t, v); });
  63787. };
  63788. /**
  63789. * Get a value based from its key
  63790. * @param key the given key to get the matching value from
  63791. * @return the value if found, otherwise undefined is returned
  63792. */
  63793. StringDictionary.prototype.get = function (key) {
  63794. var val = this._data[key];
  63795. if (val !== undefined) {
  63796. return val;
  63797. }
  63798. return undefined;
  63799. };
  63800. /**
  63801. * Get a value from its key or add it if it doesn't exist.
  63802. * This method will ensure you that a given key/data will be present in the dictionary.
  63803. * @param key the given key to get the matching value from
  63804. * @param factory the factory that will create the value if the key is not present in the dictionary.
  63805. * The factory will only be invoked if there's no data for the given key.
  63806. * @return the value corresponding to the key.
  63807. */
  63808. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  63809. var val = this.get(key);
  63810. if (val !== undefined) {
  63811. return val;
  63812. }
  63813. val = factory(key);
  63814. if (val) {
  63815. this.add(key, val);
  63816. }
  63817. return val;
  63818. };
  63819. /**
  63820. * Get a value from its key if present in the dictionary otherwise add it
  63821. * @param key the key to get the value from
  63822. * @param val if there's no such key/value pair in the dictionary add it with this value
  63823. * @return the value corresponding to the key
  63824. */
  63825. StringDictionary.prototype.getOrAdd = function (key, val) {
  63826. var curVal = this.get(key);
  63827. if (curVal !== undefined) {
  63828. return curVal;
  63829. }
  63830. this.add(key, val);
  63831. return val;
  63832. };
  63833. /**
  63834. * Check if there's a given key in the dictionary
  63835. * @param key the key to check for
  63836. * @return true if the key is present, false otherwise
  63837. */
  63838. StringDictionary.prototype.contains = function (key) {
  63839. return this._data[key] !== undefined;
  63840. };
  63841. /**
  63842. * Add a new key and its corresponding value
  63843. * @param key the key to add
  63844. * @param value the value corresponding to the key
  63845. * @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
  63846. */
  63847. StringDictionary.prototype.add = function (key, value) {
  63848. if (this._data[key] !== undefined) {
  63849. return false;
  63850. }
  63851. this._data[key] = value;
  63852. ++this._count;
  63853. return true;
  63854. };
  63855. /**
  63856. * Update a specific value associated to a key
  63857. * @param key defines the key to use
  63858. * @param value defines the value to store
  63859. * @returns true if the value was updated (or false if the key was not found)
  63860. */
  63861. StringDictionary.prototype.set = function (key, value) {
  63862. if (this._data[key] === undefined) {
  63863. return false;
  63864. }
  63865. this._data[key] = value;
  63866. return true;
  63867. };
  63868. /**
  63869. * Get the element of the given key and remove it from the dictionary
  63870. * @param key defines the key to search
  63871. * @returns the value associated with the key or null if not found
  63872. */
  63873. StringDictionary.prototype.getAndRemove = function (key) {
  63874. var val = this.get(key);
  63875. if (val !== undefined) {
  63876. delete this._data[key];
  63877. --this._count;
  63878. return val;
  63879. }
  63880. return null;
  63881. };
  63882. /**
  63883. * Remove a key/value from the dictionary.
  63884. * @param key the key to remove
  63885. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  63886. */
  63887. StringDictionary.prototype.remove = function (key) {
  63888. if (this.contains(key)) {
  63889. delete this._data[key];
  63890. --this._count;
  63891. return true;
  63892. }
  63893. return false;
  63894. };
  63895. /**
  63896. * Clear the whole content of the dictionary
  63897. */
  63898. StringDictionary.prototype.clear = function () {
  63899. this._data = {};
  63900. this._count = 0;
  63901. };
  63902. Object.defineProperty(StringDictionary.prototype, "count", {
  63903. /**
  63904. * Gets the current count
  63905. */
  63906. get: function () {
  63907. return this._count;
  63908. },
  63909. enumerable: true,
  63910. configurable: true
  63911. });
  63912. /**
  63913. * Execute a callback on each key/val of the dictionary.
  63914. * Note that you can remove any element in this dictionary in the callback implementation
  63915. * @param callback the callback to execute on a given key/value pair
  63916. */
  63917. StringDictionary.prototype.forEach = function (callback) {
  63918. for (var cur in this._data) {
  63919. var val = this._data[cur];
  63920. callback(cur, val);
  63921. }
  63922. };
  63923. /**
  63924. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  63925. * If the callback returns null or undefined the method will iterate to the next key/value pair
  63926. * Note that you can remove any element in this dictionary in the callback implementation
  63927. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  63928. * @returns the first item
  63929. */
  63930. StringDictionary.prototype.first = function (callback) {
  63931. for (var cur in this._data) {
  63932. var val = this._data[cur];
  63933. var res = callback(cur, val);
  63934. if (res) {
  63935. return res;
  63936. }
  63937. }
  63938. return null;
  63939. };
  63940. return StringDictionary;
  63941. }());
  63942. BABYLON.StringDictionary = StringDictionary;
  63943. })(BABYLON || (BABYLON = {}));
  63944. //# sourceMappingURL=babylon.stringDictionary.js.map
  63945. var BABYLON;
  63946. (function (BABYLON) {
  63947. var Debug;
  63948. (function (Debug) {
  63949. /**
  63950. * Class used to render a debug view of a given skeleton
  63951. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  63952. */
  63953. var SkeletonViewer = /** @class */ (function () {
  63954. /**
  63955. * Creates a new SkeletonViewer
  63956. * @param skeleton defines the skeleton to render
  63957. * @param mesh defines the mesh attached to the skeleton
  63958. * @param scene defines the hosting scene
  63959. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  63960. * @param renderingGroupId defines the rendering group id to use with the viewer
  63961. */
  63962. function SkeletonViewer(
  63963. /** defines the skeleton to render */
  63964. skeleton,
  63965. /** defines the mesh attached to the skeleton */
  63966. mesh, scene,
  63967. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  63968. autoUpdateBonesMatrices,
  63969. /** defines the rendering group id to use with the viewer */
  63970. renderingGroupId) {
  63971. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  63972. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  63973. this.skeleton = skeleton;
  63974. this.mesh = mesh;
  63975. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  63976. this.renderingGroupId = renderingGroupId;
  63977. /** Gets or sets the color used to render the skeleton */
  63978. this.color = BABYLON.Color3.White();
  63979. this._debugLines = new Array();
  63980. this._isEnabled = false;
  63981. this._scene = scene;
  63982. this.update();
  63983. this._renderFunction = this.update.bind(this);
  63984. }
  63985. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  63986. get: function () {
  63987. return this._isEnabled;
  63988. },
  63989. /** Gets or sets a boolean indicating if the viewer is enabled */
  63990. set: function (value) {
  63991. if (this._isEnabled === value) {
  63992. return;
  63993. }
  63994. this._isEnabled = value;
  63995. if (value) {
  63996. this._scene.registerBeforeRender(this._renderFunction);
  63997. }
  63998. else {
  63999. this._scene.unregisterBeforeRender(this._renderFunction);
  64000. }
  64001. },
  64002. enumerable: true,
  64003. configurable: true
  64004. });
  64005. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  64006. if (x === void 0) { x = 0; }
  64007. if (y === void 0) { y = 0; }
  64008. if (z === void 0) { z = 0; }
  64009. var tmat = BABYLON.Tmp.Matrix[0];
  64010. var parentBone = bone.getParent();
  64011. tmat.copyFrom(bone.getLocalMatrix());
  64012. if (x !== 0 || y !== 0 || z !== 0) {
  64013. var tmat2 = BABYLON.Tmp.Matrix[1];
  64014. BABYLON.Matrix.IdentityToRef(tmat2);
  64015. tmat2.m[12] = x;
  64016. tmat2.m[13] = y;
  64017. tmat2.m[14] = z;
  64018. tmat2.multiplyToRef(tmat, tmat);
  64019. }
  64020. if (parentBone) {
  64021. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  64022. }
  64023. tmat.multiplyToRef(meshMat, tmat);
  64024. position.x = tmat.m[12];
  64025. position.y = tmat.m[13];
  64026. position.z = tmat.m[14];
  64027. };
  64028. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  64029. var len = bones.length;
  64030. var meshPos = this.mesh.position;
  64031. for (var i = 0; i < len; i++) {
  64032. var bone = bones[i];
  64033. var points = this._debugLines[i];
  64034. if (!points) {
  64035. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64036. this._debugLines[i] = points;
  64037. }
  64038. this._getBonePosition(points[0], bone, meshMat);
  64039. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  64040. points[0].subtractInPlace(meshPos);
  64041. points[1].subtractInPlace(meshPos);
  64042. }
  64043. };
  64044. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  64045. var len = bones.length;
  64046. var boneNum = 0;
  64047. var meshPos = this.mesh.position;
  64048. for (var i = len - 1; i >= 0; i--) {
  64049. var childBone = bones[i];
  64050. var parentBone = childBone.getParent();
  64051. if (!parentBone) {
  64052. continue;
  64053. }
  64054. var points = this._debugLines[boneNum];
  64055. if (!points) {
  64056. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64057. this._debugLines[boneNum] = points;
  64058. }
  64059. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  64060. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  64061. points[0].subtractInPlace(meshPos);
  64062. points[1].subtractInPlace(meshPos);
  64063. boneNum++;
  64064. }
  64065. };
  64066. /** Update the viewer to sync with current skeleton state */
  64067. SkeletonViewer.prototype.update = function () {
  64068. if (this.autoUpdateBonesMatrices) {
  64069. this.skeleton.computeAbsoluteTransforms();
  64070. }
  64071. if (this.skeleton.bones[0].length === undefined) {
  64072. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64073. }
  64074. else {
  64075. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  64076. }
  64077. if (!this._debugMesh) {
  64078. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  64079. this._debugMesh.renderingGroupId = this.renderingGroupId;
  64080. }
  64081. else {
  64082. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  64083. }
  64084. this._debugMesh.position.copyFrom(this.mesh.position);
  64085. this._debugMesh.color = this.color;
  64086. };
  64087. /** Release associated resources */
  64088. SkeletonViewer.prototype.dispose = function () {
  64089. if (this._debugMesh) {
  64090. this.isEnabled = false;
  64091. this._debugMesh.dispose();
  64092. this._debugMesh = null;
  64093. }
  64094. };
  64095. return SkeletonViewer;
  64096. }());
  64097. Debug.SkeletonViewer = SkeletonViewer;
  64098. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64099. })(BABYLON || (BABYLON = {}));
  64100. //# sourceMappingURL=babylon.skeletonViewer.js.map
  64101. /**
  64102. * Module Debug contains the (visual) components to debug a scene correctly
  64103. */
  64104. var BABYLON;
  64105. (function (BABYLON) {
  64106. var Debug;
  64107. (function (Debug) {
  64108. /**
  64109. * The Axes viewer will show 3 axes in a specific point in space
  64110. */
  64111. var AxesViewer = /** @class */ (function () {
  64112. /**
  64113. * Creates a new AxesViewer
  64114. * @param scene defines the hosting scene
  64115. * @param scaleLines defines a number used to scale line length (1 by default)
  64116. */
  64117. function AxesViewer(scene, scaleLines) {
  64118. if (scaleLines === void 0) { scaleLines = 1; }
  64119. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64120. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64121. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  64122. /**
  64123. * Gets or sets a number used to scale line length
  64124. */
  64125. this.scaleLines = 1;
  64126. this.scaleLines = scaleLines;
  64127. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  64128. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  64129. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  64130. this._xmesh.renderingGroupId = 2;
  64131. this._ymesh.renderingGroupId = 2;
  64132. this._zmesh.renderingGroupId = 2;
  64133. this._xmesh.material.checkReadyOnlyOnce = true;
  64134. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  64135. this._ymesh.material.checkReadyOnlyOnce = true;
  64136. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  64137. this._zmesh.material.checkReadyOnlyOnce = true;
  64138. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  64139. this.scene = scene;
  64140. }
  64141. /**
  64142. * Force the viewer to update
  64143. * @param position defines the position of the viewer
  64144. * @param xaxis defines the x axis of the viewer
  64145. * @param yaxis defines the y axis of the viewer
  64146. * @param zaxis defines the z axis of the viewer
  64147. */
  64148. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  64149. var scaleLines = this.scaleLines;
  64150. if (this._xmesh) {
  64151. this._xmesh.position.copyFrom(position);
  64152. }
  64153. if (this._ymesh) {
  64154. this._ymesh.position.copyFrom(position);
  64155. }
  64156. if (this._zmesh) {
  64157. this._zmesh.position.copyFrom(position);
  64158. }
  64159. var point2 = this._xline[1];
  64160. point2.x = xaxis.x * scaleLines;
  64161. point2.y = xaxis.y * scaleLines;
  64162. point2.z = xaxis.z * scaleLines;
  64163. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  64164. point2 = this._yline[1];
  64165. point2.x = yaxis.x * scaleLines;
  64166. point2.y = yaxis.y * scaleLines;
  64167. point2.z = yaxis.z * scaleLines;
  64168. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  64169. point2 = this._zline[1];
  64170. point2.x = zaxis.x * scaleLines;
  64171. point2.y = zaxis.y * scaleLines;
  64172. point2.z = zaxis.z * scaleLines;
  64173. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  64174. };
  64175. /** Releases resources */
  64176. AxesViewer.prototype.dispose = function () {
  64177. if (this._xmesh) {
  64178. this._xmesh.dispose();
  64179. }
  64180. if (this._ymesh) {
  64181. this._ymesh.dispose();
  64182. }
  64183. if (this._zmesh) {
  64184. this._zmesh.dispose();
  64185. }
  64186. this._xmesh = null;
  64187. this._ymesh = null;
  64188. this._zmesh = null;
  64189. this.scene = null;
  64190. };
  64191. return AxesViewer;
  64192. }());
  64193. Debug.AxesViewer = AxesViewer;
  64194. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64195. })(BABYLON || (BABYLON = {}));
  64196. //# sourceMappingURL=babylon.axesViewer.js.map
  64197. var BABYLON;
  64198. (function (BABYLON) {
  64199. var Debug;
  64200. (function (Debug) {
  64201. /**
  64202. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  64203. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  64204. */
  64205. var BoneAxesViewer = /** @class */ (function (_super) {
  64206. __extends(BoneAxesViewer, _super);
  64207. /**
  64208. * Creates a new BoneAxesViewer
  64209. * @param scene defines the hosting scene
  64210. * @param bone defines the target bone
  64211. * @param mesh defines the target mesh
  64212. * @param scaleLines defines a scaling factor for line length (1 by default)
  64213. */
  64214. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  64215. if (scaleLines === void 0) { scaleLines = 1; }
  64216. var _this = _super.call(this, scene, scaleLines) || this;
  64217. /** Gets current position */
  64218. _this.pos = BABYLON.Vector3.Zero();
  64219. /** Gets direction of X axis */
  64220. _this.xaxis = BABYLON.Vector3.Zero();
  64221. /** Gets direction of Y axis */
  64222. _this.yaxis = BABYLON.Vector3.Zero();
  64223. /** Gets direction of Z axis */
  64224. _this.zaxis = BABYLON.Vector3.Zero();
  64225. _this.mesh = mesh;
  64226. _this.bone = bone;
  64227. return _this;
  64228. }
  64229. /**
  64230. * Force the viewer to update
  64231. */
  64232. BoneAxesViewer.prototype.update = function () {
  64233. if (!this.mesh || !this.bone) {
  64234. return;
  64235. }
  64236. var bone = this.bone;
  64237. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  64238. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  64239. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  64240. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  64241. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  64242. };
  64243. /** Releases resources */
  64244. BoneAxesViewer.prototype.dispose = function () {
  64245. if (this.mesh) {
  64246. this.mesh = null;
  64247. this.bone = null;
  64248. _super.prototype.dispose.call(this);
  64249. }
  64250. };
  64251. return BoneAxesViewer;
  64252. }(Debug.AxesViewer));
  64253. Debug.BoneAxesViewer = BoneAxesViewer;
  64254. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64255. })(BABYLON || (BABYLON = {}));
  64256. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  64257. var BABYLON;
  64258. (function (BABYLON) {
  64259. /**
  64260. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64261. * in order to better appreciate the issue one might have.
  64262. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64263. */
  64264. var RayHelper = /** @class */ (function () {
  64265. /**
  64266. * Instantiate a new ray helper.
  64267. * As raycast might be hard to debug, the RayHelper can help rendering the different rays
  64268. * in order to better appreciate the issue one might have.
  64269. * @see http://doc.babylonjs.com/babylon101/raycasts#debugging
  64270. * @param ray Defines the ray we are currently tryin to visualize
  64271. */
  64272. function RayHelper(ray) {
  64273. this.ray = ray;
  64274. }
  64275. /**
  64276. * Helper function to create a colored helper in a scene in one line.
  64277. * @param ray Defines the ray we are currently tryin to visualize
  64278. * @param scene Defines the scene the ray is used in
  64279. * @param color Defines the color we want to see the ray in
  64280. * @returns The newly created ray helper.
  64281. */
  64282. RayHelper.CreateAndShow = function (ray, scene, color) {
  64283. var helper = new RayHelper(ray);
  64284. helper.show(scene, color);
  64285. return helper;
  64286. };
  64287. /**
  64288. * Shows the ray we are willing to debug.
  64289. * @param scene Defines the scene the ray needs to be rendered in
  64290. * @param color Defines the color the ray needs to be rendered in
  64291. */
  64292. RayHelper.prototype.show = function (scene, color) {
  64293. if (!this._renderFunction && this.ray) {
  64294. var ray = this.ray;
  64295. this._renderFunction = this._render.bind(this);
  64296. this._scene = scene;
  64297. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  64298. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  64299. if (this._renderFunction) {
  64300. this._scene.registerBeforeRender(this._renderFunction);
  64301. }
  64302. }
  64303. if (color && this._renderLine) {
  64304. this._renderLine.color.copyFrom(color);
  64305. }
  64306. };
  64307. /**
  64308. * Hides the ray we are debugging.
  64309. */
  64310. RayHelper.prototype.hide = function () {
  64311. if (this._renderFunction && this._scene) {
  64312. this._scene.unregisterBeforeRender(this._renderFunction);
  64313. this._scene = null;
  64314. this._renderFunction = null;
  64315. if (this._renderLine) {
  64316. this._renderLine.dispose();
  64317. this._renderLine = null;
  64318. }
  64319. this._renderPoints = [];
  64320. }
  64321. };
  64322. RayHelper.prototype._render = function () {
  64323. var ray = this.ray;
  64324. if (!ray) {
  64325. return;
  64326. }
  64327. var point = this._renderPoints[1];
  64328. var len = Math.min(ray.length, 1000000);
  64329. point.copyFrom(ray.direction);
  64330. point.scaleInPlace(len);
  64331. point.addInPlace(ray.origin);
  64332. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  64333. };
  64334. /**
  64335. * Attach a ray helper to a mesh so that we can easily see its orientation for instance or information like its normals.
  64336. * @param mesh Defines the mesh we want the helper attached to
  64337. * @param meshSpaceDirection Defines the direction of the Ray in mesh space (local space of the mesh node)
  64338. * @param meshSpaceOrigin Defines the origin of the Ray in mesh space (local space of the mesh node)
  64339. * @param length Defines the length of the ray
  64340. */
  64341. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  64342. this._attachedToMesh = mesh;
  64343. var ray = this.ray;
  64344. if (!ray) {
  64345. return;
  64346. }
  64347. if (!ray.direction) {
  64348. ray.direction = BABYLON.Vector3.Zero();
  64349. }
  64350. if (!ray.origin) {
  64351. ray.origin = BABYLON.Vector3.Zero();
  64352. }
  64353. if (length) {
  64354. ray.length = length;
  64355. }
  64356. if (!meshSpaceOrigin) {
  64357. meshSpaceOrigin = BABYLON.Vector3.Zero();
  64358. }
  64359. if (!meshSpaceDirection) {
  64360. // -1 so that this will work with Mesh.lookAt
  64361. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  64362. }
  64363. if (!this._meshSpaceDirection) {
  64364. this._meshSpaceDirection = meshSpaceDirection.clone();
  64365. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  64366. }
  64367. else {
  64368. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  64369. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  64370. }
  64371. if (!this._updateToMeshFunction) {
  64372. this._updateToMeshFunction = this._updateToMesh.bind(this);
  64373. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  64374. }
  64375. this._updateToMesh();
  64376. };
  64377. /**
  64378. * Detach the ray helper from the mesh it has previously been attached to.
  64379. */
  64380. RayHelper.prototype.detachFromMesh = function () {
  64381. if (this._attachedToMesh) {
  64382. if (this._updateToMeshFunction) {
  64383. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  64384. }
  64385. this._attachedToMesh = null;
  64386. this._updateToMeshFunction = null;
  64387. }
  64388. };
  64389. RayHelper.prototype._updateToMesh = function () {
  64390. var ray = this.ray;
  64391. if (!this._attachedToMesh || !ray) {
  64392. return;
  64393. }
  64394. if (this._attachedToMesh._isDisposed) {
  64395. this.detachFromMesh();
  64396. return;
  64397. }
  64398. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  64399. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  64400. };
  64401. /**
  64402. * Dispose the helper and release its associated resources.
  64403. */
  64404. RayHelper.prototype.dispose = function () {
  64405. this.hide();
  64406. this.detachFromMesh();
  64407. this.ray = null;
  64408. };
  64409. return RayHelper;
  64410. }());
  64411. BABYLON.RayHelper = RayHelper;
  64412. })(BABYLON || (BABYLON = {}));
  64413. //# sourceMappingURL=babylon.rayHelper.js.map
  64414. var BABYLON;
  64415. (function (BABYLON) {
  64416. Object.defineProperty(BABYLON.Scene.prototype, "debugLayer", {
  64417. get: function () {
  64418. if (!this._debugLayer) {
  64419. this._debugLayer = new DebugLayer(this);
  64420. }
  64421. return this._debugLayer;
  64422. },
  64423. enumerable: true,
  64424. configurable: true
  64425. });
  64426. /**
  64427. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64428. * what is happening in your scene
  64429. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64430. */
  64431. var DebugLayer = /** @class */ (function () {
  64432. /**
  64433. * Instantiates a new debug layer.
  64434. * The debug layer (aka Inspector) is the go to tool in order to better understand
  64435. * what is happening in your scene
  64436. * @see http://doc.babylonjs.com/features/playground_debuglayer
  64437. * @param scene Defines the scene to inspect
  64438. */
  64439. function DebugLayer(scene) {
  64440. var _this = this;
  64441. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64442. /**
  64443. * Observable triggered when a property is changed through the inspector.
  64444. */
  64445. this.onPropertyChangedObservable = new BABYLON.Observable();
  64446. this._scene = scene;
  64447. this._scene.onDisposeObservable.add(function () {
  64448. // Debug layer
  64449. if (_this._scene._debugLayer) {
  64450. _this._scene._debugLayer.hide();
  64451. }
  64452. });
  64453. }
  64454. /** Creates the inspector window. */
  64455. DebugLayer.prototype._createInspector = function (config) {
  64456. if (config === void 0) { config = {}; }
  64457. var popup = config.popup || false;
  64458. var initialTab = config.initialTab || 0;
  64459. var parentElement = config.parentElement || null;
  64460. if (!this._inspector) {
  64461. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  64462. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  64463. } // else nothing to do as instance is already created
  64464. };
  64465. /**
  64466. * Get if the inspector is visible or not.
  64467. * @returns true if visible otherwise, false
  64468. */
  64469. DebugLayer.prototype.isVisible = function () {
  64470. if (!this._inspector) {
  64471. return false;
  64472. }
  64473. return true;
  64474. };
  64475. /**
  64476. * Hide the inspector and close its window.
  64477. */
  64478. DebugLayer.prototype.hide = function () {
  64479. if (this._inspector) {
  64480. try {
  64481. this._inspector.dispose();
  64482. }
  64483. catch (e) {
  64484. // If the inspector has been removed directly from the inspector tool
  64485. }
  64486. this.onPropertyChangedObservable.clear();
  64487. this._inspector = null;
  64488. }
  64489. };
  64490. /**
  64491. *
  64492. * Launch the debugLayer.
  64493. *
  64494. * initialTab:
  64495. * | Value | Tab Name |
  64496. * | --- | --- |
  64497. * | 0 | Scene |
  64498. * | 1 | Console |
  64499. * | 2 | Stats |
  64500. * | 3 | Textures |
  64501. * | 4 | Mesh |
  64502. * | 5 | Light |
  64503. * | 6 | Material |
  64504. * | 7 | GLTF |
  64505. * | 8 | GUI |
  64506. * | 9 | Physics |
  64507. * | 10 | Camera |
  64508. * | 11 | Audio |
  64509. *
  64510. * @param config Define the configuration of the inspector
  64511. */
  64512. DebugLayer.prototype.show = function (config) {
  64513. if (config === void 0) { config = {}; }
  64514. if (typeof this.BJSINSPECTOR == 'undefined') {
  64515. // Load inspector and add it to the DOM
  64516. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  64517. }
  64518. else {
  64519. // Otherwise creates the inspector
  64520. this._createInspector(config);
  64521. }
  64522. };
  64523. /**
  64524. * Gets the active tab
  64525. * @return the index of the active tab or -1 if the inspector is hidden
  64526. */
  64527. DebugLayer.prototype.getActiveTab = function () {
  64528. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  64529. };
  64530. /**
  64531. * Define the url to get the inspector script from.
  64532. * By default it uses the babylonjs CDN.
  64533. * @ignoreNaming
  64534. */
  64535. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  64536. return DebugLayer;
  64537. }());
  64538. BABYLON.DebugLayer = DebugLayer;
  64539. })(BABYLON || (BABYLON = {}));
  64540. //# sourceMappingURL=babylon.debugLayer.js.map
  64541. var BABYLON;
  64542. (function (BABYLON) {
  64543. var Debug;
  64544. (function (Debug) {
  64545. /**
  64546. * Used to show the physics impostor around the specific mesh
  64547. */
  64548. var PhysicsViewer = /** @class */ (function () {
  64549. /**
  64550. * Creates a new PhysicsViewer
  64551. * @param scene defines the hosting scene
  64552. */
  64553. function PhysicsViewer(scene) {
  64554. /** @hidden */
  64555. this._impostors = [];
  64556. /** @hidden */
  64557. this._meshes = [];
  64558. /** @hidden */
  64559. this._numMeshes = 0;
  64560. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  64561. var physicEngine = this._scene.getPhysicsEngine();
  64562. if (physicEngine) {
  64563. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  64564. }
  64565. }
  64566. /** @hidden */
  64567. PhysicsViewer.prototype._updateDebugMeshes = function () {
  64568. var plugin = this._physicsEnginePlugin;
  64569. for (var i = 0; i < this._numMeshes; i++) {
  64570. var impostor = this._impostors[i];
  64571. if (!impostor) {
  64572. continue;
  64573. }
  64574. if (impostor.isDisposed) {
  64575. this.hideImpostor(this._impostors[i--]);
  64576. }
  64577. else {
  64578. var mesh = this._meshes[i];
  64579. if (mesh && plugin) {
  64580. plugin.syncMeshWithImpostor(mesh, impostor);
  64581. }
  64582. }
  64583. }
  64584. };
  64585. /**
  64586. * Renders a specified physic impostor
  64587. * @param impostor defines the impostor to render
  64588. */
  64589. PhysicsViewer.prototype.showImpostor = function (impostor) {
  64590. if (!this._scene) {
  64591. return;
  64592. }
  64593. for (var i = 0; i < this._numMeshes; i++) {
  64594. if (this._impostors[i] == impostor) {
  64595. return;
  64596. }
  64597. }
  64598. var debugMesh = this._getDebugMesh(impostor, this._scene);
  64599. if (debugMesh) {
  64600. this._impostors[this._numMeshes] = impostor;
  64601. this._meshes[this._numMeshes] = debugMesh;
  64602. if (this._numMeshes === 0) {
  64603. this._renderFunction = this._updateDebugMeshes.bind(this);
  64604. this._scene.registerBeforeRender(this._renderFunction);
  64605. }
  64606. this._numMeshes++;
  64607. }
  64608. };
  64609. /**
  64610. * Hides a specified physic impostor
  64611. * @param impostor defines the impostor to hide
  64612. */
  64613. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  64614. if (!impostor || !this._scene) {
  64615. return;
  64616. }
  64617. var removed = false;
  64618. for (var i = 0; i < this._numMeshes; i++) {
  64619. if (this._impostors[i] == impostor) {
  64620. var mesh = this._meshes[i];
  64621. if (!mesh) {
  64622. continue;
  64623. }
  64624. this._scene.removeMesh(mesh);
  64625. mesh.dispose();
  64626. this._numMeshes--;
  64627. if (this._numMeshes > 0) {
  64628. this._meshes[i] = this._meshes[this._numMeshes];
  64629. this._impostors[i] = this._impostors[this._numMeshes];
  64630. this._meshes[this._numMeshes] = null;
  64631. this._impostors[this._numMeshes] = null;
  64632. }
  64633. else {
  64634. this._meshes[0] = null;
  64635. this._impostors[0] = null;
  64636. }
  64637. removed = true;
  64638. break;
  64639. }
  64640. }
  64641. if (removed && this._numMeshes === 0) {
  64642. this._scene.unregisterBeforeRender(this._renderFunction);
  64643. }
  64644. };
  64645. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  64646. if (!this._debugMaterial) {
  64647. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  64648. this._debugMaterial.wireframe = true;
  64649. }
  64650. return this._debugMaterial;
  64651. };
  64652. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  64653. if (!this._debugBoxMesh) {
  64654. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  64655. this._debugBoxMesh.renderingGroupId = 1;
  64656. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64657. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  64658. scene.removeMesh(this._debugBoxMesh);
  64659. }
  64660. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  64661. };
  64662. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  64663. if (!this._debugSphereMesh) {
  64664. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  64665. this._debugSphereMesh.renderingGroupId = 1;
  64666. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  64667. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  64668. scene.removeMesh(this._debugSphereMesh);
  64669. }
  64670. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  64671. };
  64672. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  64673. var mesh = null;
  64674. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  64675. mesh = this._getDebugBoxMesh(scene);
  64676. impostor.getBoxSizeToRef(mesh.scaling);
  64677. }
  64678. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  64679. mesh = this._getDebugSphereMesh(scene);
  64680. var radius = impostor.getRadius();
  64681. mesh.scaling.x = radius * 2;
  64682. mesh.scaling.y = radius * 2;
  64683. mesh.scaling.z = radius * 2;
  64684. }
  64685. return mesh;
  64686. };
  64687. /** Releases all resources */
  64688. PhysicsViewer.prototype.dispose = function () {
  64689. for (var i = 0; i < this._numMeshes; i++) {
  64690. this.hideImpostor(this._impostors[i]);
  64691. }
  64692. if (this._debugBoxMesh) {
  64693. this._debugBoxMesh.dispose();
  64694. }
  64695. if (this._debugSphereMesh) {
  64696. this._debugSphereMesh.dispose();
  64697. }
  64698. if (this._debugMaterial) {
  64699. this._debugMaterial.dispose();
  64700. }
  64701. this._impostors.length = 0;
  64702. this._scene = null;
  64703. this._physicsEnginePlugin = null;
  64704. };
  64705. return PhysicsViewer;
  64706. }());
  64707. Debug.PhysicsViewer = PhysicsViewer;
  64708. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  64709. })(BABYLON || (BABYLON = {}));
  64710. //# sourceMappingURL=babylon.physicsViewer.js.map
  64711. var BABYLON;
  64712. (function (BABYLON) {
  64713. Object.defineProperty(BABYLON.Scene.prototype, "forceShowBoundingBoxes", {
  64714. get: function () {
  64715. return this._forceShowBoundingBoxes || false;
  64716. },
  64717. set: function (value) {
  64718. this._forceShowBoundingBoxes = value;
  64719. // Lazyly creates a BB renderer if needed.
  64720. if (value) {
  64721. this.getBoundingBoxRenderer();
  64722. }
  64723. },
  64724. enumerable: true,
  64725. configurable: true
  64726. });
  64727. BABYLON.Scene.prototype.getBoundingBoxRenderer = function () {
  64728. if (!this._boundingBoxRenderer) {
  64729. this._boundingBoxRenderer = new BoundingBoxRenderer(this);
  64730. }
  64731. return this._boundingBoxRenderer;
  64732. };
  64733. Object.defineProperty(BABYLON.AbstractMesh.prototype, "showBoundingBox", {
  64734. get: function () {
  64735. return this._showBoundingBox || false;
  64736. },
  64737. set: function (value) {
  64738. this._showBoundingBox = value;
  64739. // Lazyly creates a BB renderer if needed.
  64740. if (value) {
  64741. this.getScene().getBoundingBoxRenderer();
  64742. }
  64743. },
  64744. enumerable: true,
  64745. configurable: true
  64746. });
  64747. /**
  64748. * Component responsible of rendering the bounding box of the meshes in a scene.
  64749. * This is usually used through the mesh.showBoundingBox or the scene.forceShowBoundingBoxes properties
  64750. */
  64751. var BoundingBoxRenderer = /** @class */ (function () {
  64752. /**
  64753. * Instantiates a new bounding box renderer in a scene.
  64754. * @param scene the scene the renderer renders in
  64755. */
  64756. function BoundingBoxRenderer(scene) {
  64757. /**
  64758. * The component name helpfull to identify the component in the list of scene components.
  64759. */
  64760. this.name = BABYLON.SceneComponentConstants.NAME_BOUNDINGBOXRENDERER;
  64761. /**
  64762. * Color of the bounding box lines placed in front of an object
  64763. */
  64764. this.frontColor = new BABYLON.Color3(1, 1, 1);
  64765. /**
  64766. * Color of the bounding box lines placed behind an object
  64767. */
  64768. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  64769. /**
  64770. * Defines if the renderer should show the back lines or not
  64771. */
  64772. this.showBackLines = true;
  64773. /**
  64774. * @hidden
  64775. */
  64776. this.renderList = new BABYLON.SmartArray(32);
  64777. this._vertexBuffers = {};
  64778. this.scene = scene;
  64779. scene._addComponent(this);
  64780. }
  64781. /**
  64782. * Registers the component in a given scene
  64783. */
  64784. BoundingBoxRenderer.prototype.register = function () {
  64785. this.scene._beforeEvaluateActiveMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFOREEVALUATEACTIVEMESH_BOUNDINGBOXRENDERER, this, this.reset);
  64786. this.scene._activeMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ACTIVEMESH_BOUNDINGBOXRENDERER, this, this._activeMesh);
  64787. this.scene._evaluateSubMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_EVALUATESUBMESH_BOUNDINGBOXRENDERER, this, this._evaluateSubMesh);
  64788. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_BOUNDINGBOXRENDERER, this, this.render);
  64789. };
  64790. BoundingBoxRenderer.prototype._evaluateSubMesh = function (mesh, subMesh) {
  64791. if (mesh.showSubMeshesBoundingBox) {
  64792. var boundingInfo = subMesh.getBoundingInfo();
  64793. if (boundingInfo !== null && boundingInfo !== undefined) {
  64794. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64795. this.renderList.push(boundingInfo.boundingBox);
  64796. }
  64797. }
  64798. };
  64799. BoundingBoxRenderer.prototype._activeMesh = function (sourceMesh, mesh) {
  64800. if (sourceMesh.showBoundingBox || this.scene.forceShowBoundingBoxes) {
  64801. var boundingInfo = sourceMesh.getBoundingInfo();
  64802. boundingInfo.boundingBox._tag = mesh.renderingGroupId;
  64803. this.renderList.push(boundingInfo.boundingBox);
  64804. }
  64805. };
  64806. BoundingBoxRenderer.prototype._prepareRessources = function () {
  64807. if (this._colorShader) {
  64808. return;
  64809. }
  64810. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this.scene, "color", {
  64811. attributes: [BABYLON.VertexBuffer.PositionKind],
  64812. uniforms: ["world", "viewProjection", "color"]
  64813. });
  64814. var engine = this.scene.getEngine();
  64815. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  64816. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  64817. this._createIndexBuffer();
  64818. };
  64819. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  64820. var engine = this.scene.getEngine();
  64821. 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]);
  64822. };
  64823. /**
  64824. * Rebuilds the elements related to this component in case of
  64825. * context lost for instance.
  64826. */
  64827. BoundingBoxRenderer.prototype.rebuild = function () {
  64828. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64829. if (vb) {
  64830. vb._rebuild();
  64831. }
  64832. this._createIndexBuffer();
  64833. };
  64834. /**
  64835. * @hidden
  64836. */
  64837. BoundingBoxRenderer.prototype.reset = function () {
  64838. this.renderList.reset();
  64839. };
  64840. /**
  64841. * Render the bounding boxes of a specific rendering group
  64842. * @param renderingGroupId defines the rendering group to render
  64843. */
  64844. BoundingBoxRenderer.prototype.render = function (renderingGroupId) {
  64845. if (this.renderList.length === 0) {
  64846. return;
  64847. }
  64848. this._prepareRessources();
  64849. if (!this._colorShader.isReady()) {
  64850. return;
  64851. }
  64852. var engine = this.scene.getEngine();
  64853. engine.setDepthWrite(false);
  64854. this._colorShader._preBind();
  64855. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  64856. var boundingBox = this.renderList.data[boundingBoxIndex];
  64857. if (boundingBox._tag !== renderingGroupId) {
  64858. continue;
  64859. }
  64860. var min = boundingBox.minimum;
  64861. var max = boundingBox.maximum;
  64862. var diff = max.subtract(min);
  64863. var median = min.add(diff.scale(0.5));
  64864. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64865. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64866. .multiply(boundingBox.getWorldMatrix());
  64867. // VBOs
  64868. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64869. if (this.showBackLines) {
  64870. // Back
  64871. engine.setDepthFunctionToGreaterOrEqual();
  64872. this.scene.resetCachedMaterial();
  64873. this._colorShader.setColor4("color", this.backColor.toColor4());
  64874. this._colorShader.bind(worldMatrix);
  64875. // Draw order
  64876. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64877. }
  64878. // Front
  64879. engine.setDepthFunctionToLess();
  64880. this.scene.resetCachedMaterial();
  64881. this._colorShader.setColor4("color", this.frontColor.toColor4());
  64882. this._colorShader.bind(worldMatrix);
  64883. // Draw order
  64884. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64885. }
  64886. this._colorShader.unbind();
  64887. engine.setDepthFunctionToLessOrEqual();
  64888. engine.setDepthWrite(true);
  64889. };
  64890. /**
  64891. * In case of occlusion queries, we can render the occlusion bounding box through this method
  64892. * @param mesh Define the mesh to render the occlusion bounding box for
  64893. */
  64894. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  64895. this._prepareRessources();
  64896. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  64897. return;
  64898. }
  64899. var engine = this.scene.getEngine();
  64900. engine.setDepthWrite(false);
  64901. engine.setColorWrite(false);
  64902. this._colorShader._preBind();
  64903. var boundingBox = mesh._boundingInfo.boundingBox;
  64904. var min = boundingBox.minimum;
  64905. var max = boundingBox.maximum;
  64906. var diff = max.subtract(min);
  64907. var median = min.add(diff.scale(0.5));
  64908. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  64909. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  64910. .multiply(boundingBox.getWorldMatrix());
  64911. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  64912. engine.setDepthFunctionToLess();
  64913. this.scene.resetCachedMaterial();
  64914. this._colorShader.bind(worldMatrix);
  64915. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  64916. this._colorShader.unbind();
  64917. engine.setDepthFunctionToLessOrEqual();
  64918. engine.setDepthWrite(true);
  64919. engine.setColorWrite(true);
  64920. };
  64921. /**
  64922. * Dispose and release the resources attached to this renderer.
  64923. */
  64924. BoundingBoxRenderer.prototype.dispose = function () {
  64925. if (!this._colorShader) {
  64926. return;
  64927. }
  64928. this.renderList.dispose();
  64929. this._colorShader.dispose();
  64930. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  64931. if (buffer) {
  64932. buffer.dispose();
  64933. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  64934. }
  64935. this.scene.getEngine()._releaseBuffer(this._indexBuffer);
  64936. };
  64937. return BoundingBoxRenderer;
  64938. }());
  64939. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  64940. })(BABYLON || (BABYLON = {}));
  64941. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  64942. var BABYLON;
  64943. (function (BABYLON) {
  64944. BABYLON.Engine.prototype.createTransformFeedback = function () {
  64945. return this._gl.createTransformFeedback();
  64946. };
  64947. BABYLON.Engine.prototype.deleteTransformFeedback = function (value) {
  64948. this._gl.deleteTransformFeedback(value);
  64949. };
  64950. BABYLON.Engine.prototype.bindTransformFeedback = function (value) {
  64951. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  64952. };
  64953. BABYLON.Engine.prototype.beginTransformFeedback = function (usePoints) {
  64954. if (usePoints === void 0) { usePoints = true; }
  64955. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  64956. };
  64957. BABYLON.Engine.prototype.endTransformFeedback = function () {
  64958. this._gl.endTransformFeedback();
  64959. };
  64960. BABYLON.Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  64961. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  64962. };
  64963. BABYLON.Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  64964. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  64965. };
  64966. })(BABYLON || (BABYLON = {}));
  64967. //# sourceMappingURL=babylon.engine.transformFeedback.js.map
  64968. var BABYLON;
  64969. (function (BABYLON) {
  64970. /**
  64971. * This represents a GPU particle system in Babylon
  64972. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  64973. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  64974. */
  64975. var GPUParticleSystem = /** @class */ (function (_super) {
  64976. __extends(GPUParticleSystem, _super);
  64977. /**
  64978. * Instantiates a GPU particle system.
  64979. * 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.
  64980. * @param name The name of the particle system
  64981. * @param options The options used to create the system
  64982. * @param scene The scene the particle system belongs to
  64983. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  64984. */
  64985. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  64986. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  64987. var _this = _super.call(this, name) || this;
  64988. /**
  64989. * The layer mask we are rendering the particles through.
  64990. */
  64991. _this.layerMask = 0x0FFFFFFF;
  64992. _this._accumulatedCount = 0;
  64993. _this._targetIndex = 0;
  64994. _this._currentRenderId = -1;
  64995. _this._started = false;
  64996. _this._stopped = false;
  64997. _this._timeDelta = 0;
  64998. _this._attributesStrideSize = 21;
  64999. _this._actualFrame = 0;
  65000. _this._rawTextureWidth = 256;
  65001. /**
  65002. * An event triggered when the system is disposed.
  65003. */
  65004. _this.onDisposeObservable = new BABYLON.Observable();
  65005. /**
  65006. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  65007. * to override the particles.
  65008. */
  65009. _this.forceDepthWrite = false;
  65010. _this._preWarmDone = false;
  65011. _this._scene = scene || BABYLON.Engine.LastCreatedScene;
  65012. // Setup the default processing configuration to the scene.
  65013. _this._attachImageProcessingConfiguration(null);
  65014. _this._engine = _this._scene.getEngine();
  65015. if (!options.randomTextureSize) {
  65016. delete options.randomTextureSize;
  65017. }
  65018. var fullOptions = __assign({ capacity: 50000, randomTextureSize: _this._engine.getCaps().maxTextureSize }, options);
  65019. var optionsAsNumber = options;
  65020. if (isFinite(optionsAsNumber)) {
  65021. fullOptions.capacity = optionsAsNumber;
  65022. }
  65023. _this._capacity = fullOptions.capacity;
  65024. _this._activeCount = fullOptions.capacity;
  65025. _this._currentActiveCount = 0;
  65026. _this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  65027. _this._scene.particleSystems.push(_this);
  65028. _this._updateEffectOptions = {
  65029. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex", "cellStartOffset", "noiseCoordinates1", "noiseCoordinates2"],
  65030. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  65031. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  65032. "angleRange", "radiusRange", "cellInfos", "noiseStrength", "limitVelocityDamping"],
  65033. uniformBuffersNames: [],
  65034. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler", "angularSpeedGradientSampler", "velocityGradientSampler", "limitVelocityGradientSampler", "noiseSampler", "dragGradientSampler"],
  65035. defines: "",
  65036. fallbacks: null,
  65037. onCompiled: null,
  65038. onError: null,
  65039. indexParameters: null,
  65040. maxSimultaneousLights: 0,
  65041. transformFeedbackVaryings: []
  65042. };
  65043. _this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  65044. // Random data
  65045. var maxTextureSize = Math.min(_this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  65046. var d = [];
  65047. for (var i = 0; i < maxTextureSize; ++i) {
  65048. d.push(Math.random());
  65049. d.push(Math.random());
  65050. d.push(Math.random());
  65051. d.push(Math.random());
  65052. }
  65053. _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);
  65054. _this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65055. _this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65056. d = [];
  65057. for (var i = 0; i < maxTextureSize; ++i) {
  65058. d.push(Math.random());
  65059. d.push(Math.random());
  65060. d.push(Math.random());
  65061. d.push(Math.random());
  65062. }
  65063. _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);
  65064. _this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  65065. _this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  65066. _this._randomTextureSize = maxTextureSize;
  65067. return _this;
  65068. }
  65069. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  65070. /**
  65071. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  65072. */
  65073. get: function () {
  65074. if (!BABYLON.Engine.LastCreatedEngine) {
  65075. return false;
  65076. }
  65077. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  65078. },
  65079. enumerable: true,
  65080. configurable: true
  65081. });
  65082. /**
  65083. * Gets the maximum number of particles active at the same time.
  65084. * @returns The max number of active particles.
  65085. */
  65086. GPUParticleSystem.prototype.getCapacity = function () {
  65087. return this._capacity;
  65088. };
  65089. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  65090. /**
  65091. * Gets or set the number of active particles
  65092. */
  65093. get: function () {
  65094. return this._activeCount;
  65095. },
  65096. set: function (value) {
  65097. this._activeCount = Math.min(value, this._capacity);
  65098. },
  65099. enumerable: true,
  65100. configurable: true
  65101. });
  65102. /**
  65103. * Is this system ready to be used/rendered
  65104. * @return true if the system is ready
  65105. */
  65106. GPUParticleSystem.prototype.isReady = function () {
  65107. if (!this._updateEffect) {
  65108. this._recreateUpdateEffect();
  65109. this._recreateRenderEffect();
  65110. return false;
  65111. }
  65112. if (!this.emitter || !this._updateEffect.isReady() || !this._imageProcessingConfiguration.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  65113. return false;
  65114. }
  65115. return true;
  65116. };
  65117. /**
  65118. * Gets if the system has been started. (Note: this will still be true after stop is called)
  65119. * @returns True if it has been started, otherwise false.
  65120. */
  65121. GPUParticleSystem.prototype.isStarted = function () {
  65122. return this._started;
  65123. };
  65124. /**
  65125. * Starts the particle system and begins to emit
  65126. * @param delay defines the delay in milliseconds before starting the system (this.startDelay by default)
  65127. */
  65128. GPUParticleSystem.prototype.start = function (delay) {
  65129. var _this = this;
  65130. if (delay === void 0) { delay = this.startDelay; }
  65131. if (!this.targetStopDuration && this._hasTargetStopDurationDependantGradient()) {
  65132. throw "Particle system started with a targetStopDuration dependant gradient (eg. startSizeGradients) but no targetStopDuration set";
  65133. }
  65134. if (delay) {
  65135. setTimeout(function () {
  65136. _this.start(0);
  65137. }, delay);
  65138. return;
  65139. }
  65140. this._started = true;
  65141. this._stopped = false;
  65142. this._preWarmDone = false;
  65143. // Animations
  65144. if (this.beginAnimationOnStart && this.animations && this.animations.length > 0) {
  65145. this.getScene().beginAnimation(this, this.beginAnimationFrom, this.beginAnimationTo, this.beginAnimationLoop);
  65146. }
  65147. };
  65148. /**
  65149. * Stops the particle system.
  65150. */
  65151. GPUParticleSystem.prototype.stop = function () {
  65152. this._stopped = true;
  65153. };
  65154. /**
  65155. * Remove all active particles
  65156. */
  65157. GPUParticleSystem.prototype.reset = function () {
  65158. this._releaseBuffers();
  65159. this._releaseVAOs();
  65160. this._currentActiveCount = 0;
  65161. this._targetIndex = 0;
  65162. };
  65163. /**
  65164. * Returns the string "GPUParticleSystem"
  65165. * @returns a string containing the class name
  65166. */
  65167. GPUParticleSystem.prototype.getClassName = function () {
  65168. return "GPUParticleSystem";
  65169. };
  65170. GPUParticleSystem.prototype._removeGradientAndTexture = function (gradient, gradients, texture) {
  65171. _super.prototype._removeGradientAndTexture.call(this, gradient, gradients, texture);
  65172. this._releaseBuffers();
  65173. return this;
  65174. };
  65175. /**
  65176. * Adds a new color gradient
  65177. * @param gradient defines the gradient to use (between 0 and 1)
  65178. * @param color1 defines the color to affect to the specified gradient
  65179. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  65180. * @returns the current particle system
  65181. */
  65182. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  65183. if (!this._colorGradients) {
  65184. this._colorGradients = [];
  65185. }
  65186. var colorGradient = new BABYLON.ColorGradient();
  65187. colorGradient.gradient = gradient;
  65188. colorGradient.color1 = color1;
  65189. this._colorGradients.push(colorGradient);
  65190. this._colorGradients.sort(function (a, b) {
  65191. if (a.gradient < b.gradient) {
  65192. return -1;
  65193. }
  65194. else if (a.gradient > b.gradient) {
  65195. return 1;
  65196. }
  65197. return 0;
  65198. });
  65199. if (this._colorGradientsTexture) {
  65200. this._colorGradientsTexture.dispose();
  65201. this._colorGradientsTexture = null;
  65202. }
  65203. this._releaseBuffers();
  65204. return this;
  65205. };
  65206. /**
  65207. * Remove a specific color gradient
  65208. * @param gradient defines the gradient to remove
  65209. * @returns the current particle system
  65210. */
  65211. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  65212. this._removeGradientAndTexture(gradient, this._colorGradients, this._colorGradientsTexture);
  65213. this._colorGradientsTexture = null;
  65214. return this;
  65215. };
  65216. GPUParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor) {
  65217. var valueGradient = new BABYLON.FactorGradient();
  65218. valueGradient.gradient = gradient;
  65219. valueGradient.factor1 = factor;
  65220. factorGradients.push(valueGradient);
  65221. factorGradients.sort(function (a, b) {
  65222. if (a.gradient < b.gradient) {
  65223. return -1;
  65224. }
  65225. else if (a.gradient > b.gradient) {
  65226. return 1;
  65227. }
  65228. return 0;
  65229. });
  65230. this._releaseBuffers();
  65231. };
  65232. /**
  65233. * Adds a new size gradient
  65234. * @param gradient defines the gradient to use (between 0 and 1)
  65235. * @param factor defines the size factor to affect to the specified gradient
  65236. * @returns the current particle system
  65237. */
  65238. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  65239. if (!this._sizeGradients) {
  65240. this._sizeGradients = [];
  65241. }
  65242. this._addFactorGradient(this._sizeGradients, gradient, factor);
  65243. if (this._sizeGradientsTexture) {
  65244. this._sizeGradientsTexture.dispose();
  65245. this._sizeGradientsTexture = null;
  65246. }
  65247. this._releaseBuffers();
  65248. return this;
  65249. };
  65250. /**
  65251. * Remove a specific size gradient
  65252. * @param gradient defines the gradient to remove
  65253. * @returns the current particle system
  65254. */
  65255. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  65256. this._removeGradientAndTexture(gradient, this._sizeGradients, this._sizeGradientsTexture);
  65257. this._sizeGradientsTexture = null;
  65258. return this;
  65259. };
  65260. /**
  65261. * Adds a new angular speed gradient
  65262. * @param gradient defines the gradient to use (between 0 and 1)
  65263. * @param factor defines the angular speed to affect to the specified gradient
  65264. * @returns the current particle system
  65265. */
  65266. GPUParticleSystem.prototype.addAngularSpeedGradient = function (gradient, factor) {
  65267. if (!this._angularSpeedGradients) {
  65268. this._angularSpeedGradients = [];
  65269. }
  65270. this._addFactorGradient(this._angularSpeedGradients, gradient, factor);
  65271. if (this._angularSpeedGradientsTexture) {
  65272. this._angularSpeedGradientsTexture.dispose();
  65273. this._angularSpeedGradientsTexture = null;
  65274. }
  65275. this._releaseBuffers();
  65276. return this;
  65277. };
  65278. /**
  65279. * Remove a specific angular speed gradient
  65280. * @param gradient defines the gradient to remove
  65281. * @returns the current particle system
  65282. */
  65283. GPUParticleSystem.prototype.removeAngularSpeedGradient = function (gradient) {
  65284. this._removeGradientAndTexture(gradient, this._angularSpeedGradients, this._angularSpeedGradientsTexture);
  65285. this._angularSpeedGradientsTexture = null;
  65286. return this;
  65287. };
  65288. /**
  65289. * Adds a new velocity gradient
  65290. * @param gradient defines the gradient to use (between 0 and 1)
  65291. * @param factor defines the velocity to affect to the specified gradient
  65292. * @returns the current particle system
  65293. */
  65294. GPUParticleSystem.prototype.addVelocityGradient = function (gradient, factor) {
  65295. if (!this._velocityGradients) {
  65296. this._velocityGradients = [];
  65297. }
  65298. this._addFactorGradient(this._velocityGradients, gradient, factor);
  65299. if (this._velocityGradientsTexture) {
  65300. this._velocityGradientsTexture.dispose();
  65301. this._velocityGradientsTexture = null;
  65302. }
  65303. this._releaseBuffers();
  65304. return this;
  65305. };
  65306. /**
  65307. * Remove a specific velocity gradient
  65308. * @param gradient defines the gradient to remove
  65309. * @returns the current particle system
  65310. */
  65311. GPUParticleSystem.prototype.removeVelocityGradient = function (gradient) {
  65312. this._removeGradientAndTexture(gradient, this._velocityGradients, this._velocityGradientsTexture);
  65313. this._velocityGradientsTexture = null;
  65314. return this;
  65315. };
  65316. /**
  65317. * Adds a new limit velocity gradient
  65318. * @param gradient defines the gradient to use (between 0 and 1)
  65319. * @param factor defines the limit velocity value to affect to the specified gradient
  65320. * @returns the current particle system
  65321. */
  65322. GPUParticleSystem.prototype.addLimitVelocityGradient = function (gradient, factor) {
  65323. if (!this._limitVelocityGradients) {
  65324. this._limitVelocityGradients = [];
  65325. }
  65326. this._addFactorGradient(this._limitVelocityGradients, gradient, factor);
  65327. if (this._limitVelocityGradientsTexture) {
  65328. this._limitVelocityGradientsTexture.dispose();
  65329. this._limitVelocityGradientsTexture = null;
  65330. }
  65331. this._releaseBuffers();
  65332. return this;
  65333. };
  65334. /**
  65335. * Remove a specific limit velocity gradient
  65336. * @param gradient defines the gradient to remove
  65337. * @returns the current particle system
  65338. */
  65339. GPUParticleSystem.prototype.removeLimitVelocityGradient = function (gradient) {
  65340. this._removeGradientAndTexture(gradient, this._limitVelocityGradients, this._limitVelocityGradientsTexture);
  65341. this._limitVelocityGradientsTexture = null;
  65342. return this;
  65343. };
  65344. /**
  65345. * Adds a new drag gradient
  65346. * @param gradient defines the gradient to use (between 0 and 1)
  65347. * @param factor defines the drag value to affect to the specified gradient
  65348. * @returns the current particle system
  65349. */
  65350. GPUParticleSystem.prototype.addDragGradient = function (gradient, factor) {
  65351. if (!this._dragGradients) {
  65352. this._dragGradients = [];
  65353. }
  65354. this._addFactorGradient(this._dragGradients, gradient, factor);
  65355. if (this._dragGradientsTexture) {
  65356. this._dragGradientsTexture.dispose();
  65357. this._dragGradientsTexture = null;
  65358. }
  65359. this._releaseBuffers();
  65360. return this;
  65361. };
  65362. /**
  65363. * Remove a specific drag gradient
  65364. * @param gradient defines the gradient to remove
  65365. * @returns the current particle system
  65366. */
  65367. GPUParticleSystem.prototype.removeDragGradient = function (gradient) {
  65368. this._removeGradientAndTexture(gradient, this._dragGradients, this._dragGradientsTexture);
  65369. this._dragGradientsTexture = null;
  65370. return this;
  65371. };
  65372. /**
  65373. * Not supported by GPUParticleSystem
  65374. * @param gradient defines the gradient to use (between 0 and 1)
  65375. * @param factor defines the emit rate value to affect to the specified gradient
  65376. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65377. * @returns the current particle system
  65378. */
  65379. GPUParticleSystem.prototype.addEmitRateGradient = function (gradient, factor, factor2) {
  65380. // Do nothing as emit rate is not supported by GPUParticleSystem
  65381. return this;
  65382. };
  65383. /**
  65384. * Not supported by GPUParticleSystem
  65385. * @param gradient defines the gradient to remove
  65386. * @returns the current particle system
  65387. */
  65388. GPUParticleSystem.prototype.removeEmitRateGradient = function (gradient) {
  65389. // Do nothing as emit rate is not supported by GPUParticleSystem
  65390. return this;
  65391. };
  65392. /**
  65393. * Not supported by GPUParticleSystem
  65394. * @param gradient defines the gradient to use (between 0 and 1)
  65395. * @param factor defines the start size value to affect to the specified gradient
  65396. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65397. * @returns the current particle system
  65398. */
  65399. GPUParticleSystem.prototype.addStartSizeGradient = function (gradient, factor, factor2) {
  65400. // Do nothing as start size is not supported by GPUParticleSystem
  65401. return this;
  65402. };
  65403. /**
  65404. * Not supported by GPUParticleSystem
  65405. * @param gradient defines the gradient to remove
  65406. * @returns the current particle system
  65407. */
  65408. GPUParticleSystem.prototype.removeStartSizeGradient = function (gradient) {
  65409. // Do nothing as start size is not supported by GPUParticleSystem
  65410. return this;
  65411. };
  65412. /**
  65413. * Not supported by GPUParticleSystem
  65414. * @param gradient defines the gradient to use (between 0 and 1)
  65415. * @param min defines the color remap minimal range
  65416. * @param max defines the color remap maximal range
  65417. * @returns the current particle system
  65418. */
  65419. GPUParticleSystem.prototype.addColorRemapGradient = function (gradient, min, max) {
  65420. // Do nothing as start size is not supported by GPUParticleSystem
  65421. return this;
  65422. };
  65423. /**
  65424. * Not supported by GPUParticleSystem
  65425. * @param gradient defines the gradient to remove
  65426. * @returns the current particle system
  65427. */
  65428. GPUParticleSystem.prototype.removeColorRemapGradient = function (gradient) {
  65429. // Do nothing as start size is not supported by GPUParticleSystem
  65430. return this;
  65431. };
  65432. /**
  65433. * Not supported by GPUParticleSystem
  65434. * @param gradient defines the gradient to use (between 0 and 1)
  65435. * @param min defines the alpha remap minimal range
  65436. * @param max defines the alpha remap maximal range
  65437. * @returns the current particle system
  65438. */
  65439. GPUParticleSystem.prototype.addAlphaRemapGradient = function (gradient, min, max) {
  65440. // Do nothing as start size is not supported by GPUParticleSystem
  65441. return this;
  65442. };
  65443. /**
  65444. * Not supported by GPUParticleSystem
  65445. * @param gradient defines the gradient to remove
  65446. * @returns the current particle system
  65447. */
  65448. GPUParticleSystem.prototype.removeAlphaRemapGradient = function (gradient) {
  65449. // Do nothing as start size is not supported by GPUParticleSystem
  65450. return this;
  65451. };
  65452. /**
  65453. * Not supported by GPUParticleSystem
  65454. * @param gradient defines the gradient to use (between 0 and 1)
  65455. * @param color defines the color to affect to the specified gradient
  65456. * @returns the current particle system
  65457. */
  65458. GPUParticleSystem.prototype.addRampGradient = function (gradient, color) {
  65459. //Not supported by GPUParticleSystem
  65460. return this;
  65461. };
  65462. /**
  65463. * Not supported by GPUParticleSystem
  65464. * @param gradient defines the gradient to remove
  65465. * @returns the current particle system
  65466. */
  65467. GPUParticleSystem.prototype.removeRampGradient = function (gradient) {
  65468. //Not supported by GPUParticleSystem
  65469. return this;
  65470. };
  65471. /**
  65472. * Not supported by GPUParticleSystem
  65473. * @returns the list of ramp gradients
  65474. */
  65475. GPUParticleSystem.prototype.getRampGradients = function () {
  65476. return null;
  65477. };
  65478. Object.defineProperty(GPUParticleSystem.prototype, "useRampGradients", {
  65479. /**
  65480. * Not supported by GPUParticleSystem
  65481. * Gets or sets a boolean indicating that ramp gradients must be used
  65482. * @see http://doc.babylonjs.com/babylon101/particles#ramp-gradients
  65483. */
  65484. get: function () {
  65485. //Not supported by GPUParticleSystem
  65486. return false;
  65487. },
  65488. set: function (value) {
  65489. //Not supported by GPUParticleSystem
  65490. },
  65491. enumerable: true,
  65492. configurable: true
  65493. });
  65494. /**
  65495. * Not supported by GPUParticleSystem
  65496. * @param gradient defines the gradient to use (between 0 and 1)
  65497. * @param factor defines the life time factor to affect to the specified gradient
  65498. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  65499. * @returns the current particle system
  65500. */
  65501. GPUParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  65502. //Not supported by GPUParticleSystem
  65503. return this;
  65504. };
  65505. /**
  65506. * Not supported by GPUParticleSystem
  65507. * @param gradient defines the gradient to remove
  65508. * @returns the current particle system
  65509. */
  65510. GPUParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  65511. //Not supported by GPUParticleSystem
  65512. return this;
  65513. };
  65514. GPUParticleSystem.prototype._reset = function () {
  65515. this._releaseBuffers();
  65516. };
  65517. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  65518. var updateVertexBuffers = {};
  65519. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  65520. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  65521. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  65522. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  65523. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  65524. var offset = 12;
  65525. if (!this._colorGradientsTexture) {
  65526. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  65527. offset += 4;
  65528. }
  65529. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  65530. offset += 3;
  65531. if (!this._isBillboardBased) {
  65532. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  65533. offset += 3;
  65534. }
  65535. if (this._angularSpeedGradientsTexture) {
  65536. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1);
  65537. offset += 1;
  65538. }
  65539. else {
  65540. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  65541. offset += 2;
  65542. }
  65543. if (this._isAnimationSheetEnabled) {
  65544. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  65545. offset += 1;
  65546. if (this.spriteRandomStartCell) {
  65547. updateVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1);
  65548. offset += 1;
  65549. }
  65550. }
  65551. if (this.noiseTexture) {
  65552. updateVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3);
  65553. offset += 3;
  65554. updateVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3);
  65555. offset += 3;
  65556. }
  65557. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  65558. this._engine.bindArrayBuffer(null);
  65559. return vao;
  65560. };
  65561. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  65562. var renderVertexBuffers = {};
  65563. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  65564. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  65565. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  65566. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  65567. var offset = 12;
  65568. if (!this._colorGradientsTexture) {
  65569. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  65570. offset += 4;
  65571. }
  65572. if (this.billboardMode === BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED) {
  65573. renderVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3, this._attributesStrideSize, true);
  65574. }
  65575. offset += 3; // Direction
  65576. if (!this._isBillboardBased) {
  65577. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  65578. offset += 3;
  65579. }
  65580. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 1, this._attributesStrideSize, true);
  65581. if (this._angularSpeedGradientsTexture) {
  65582. offset++;
  65583. }
  65584. else {
  65585. offset += 2;
  65586. }
  65587. if (this._isAnimationSheetEnabled) {
  65588. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  65589. offset += 1;
  65590. if (this.spriteRandomStartCell) {
  65591. renderVertexBuffers["cellStartOffset"] = source.createVertexBuffer("cellStartOffset", offset, 1, this._attributesStrideSize, true);
  65592. offset += 1;
  65593. }
  65594. }
  65595. if (this.noiseTexture) {
  65596. renderVertexBuffers["noiseCoordinates1"] = source.createVertexBuffer("noiseCoordinates1", offset, 3, this._attributesStrideSize, true);
  65597. offset += 3;
  65598. renderVertexBuffers["noiseCoordinates2"] = source.createVertexBuffer("noiseCoordinates2", offset, 3, this._attributesStrideSize, true);
  65599. offset += 3;
  65600. }
  65601. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  65602. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  65603. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  65604. this._engine.bindArrayBuffer(null);
  65605. return vao;
  65606. };
  65607. GPUParticleSystem.prototype._initialize = function (force) {
  65608. if (force === void 0) { force = false; }
  65609. if (this._buffer0 && !force) {
  65610. return;
  65611. }
  65612. var engine = this._scene.getEngine();
  65613. var data = new Array();
  65614. if (!this.isBillboardBased) {
  65615. this._attributesStrideSize += 3;
  65616. }
  65617. if (this._colorGradientsTexture) {
  65618. this._attributesStrideSize -= 4;
  65619. }
  65620. if (this._angularSpeedGradientsTexture) {
  65621. this._attributesStrideSize -= 1;
  65622. }
  65623. if (this._isAnimationSheetEnabled) {
  65624. this._attributesStrideSize += 1;
  65625. if (this.spriteRandomStartCell) {
  65626. this._attributesStrideSize += 1;
  65627. }
  65628. }
  65629. if (this.noiseTexture) {
  65630. this._attributesStrideSize += 6;
  65631. }
  65632. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  65633. // position
  65634. data.push(0.0);
  65635. data.push(0.0);
  65636. data.push(0.0);
  65637. // Age and life
  65638. data.push(0.0); // create the particle as a dead one to create a new one at start
  65639. data.push(0.0);
  65640. // Seed
  65641. data.push(Math.random());
  65642. data.push(Math.random());
  65643. data.push(Math.random());
  65644. data.push(Math.random());
  65645. // Size
  65646. data.push(0.0);
  65647. data.push(0.0);
  65648. data.push(0.0);
  65649. if (!this._colorGradientsTexture) {
  65650. // color
  65651. data.push(0.0);
  65652. data.push(0.0);
  65653. data.push(0.0);
  65654. data.push(0.0);
  65655. }
  65656. // direction
  65657. data.push(0.0);
  65658. data.push(0.0);
  65659. data.push(0.0);
  65660. if (!this.isBillboardBased) {
  65661. // initialDirection
  65662. data.push(0.0);
  65663. data.push(0.0);
  65664. data.push(0.0);
  65665. }
  65666. // angle
  65667. data.push(0.0);
  65668. if (!this._angularSpeedGradientsTexture) {
  65669. data.push(0.0);
  65670. }
  65671. if (this._isAnimationSheetEnabled) {
  65672. data.push(0.0);
  65673. if (this.spriteRandomStartCell) {
  65674. data.push(0.0);
  65675. }
  65676. }
  65677. if (this.noiseTexture) { // Random coordinates for reading into noise texture
  65678. data.push(Math.random());
  65679. data.push(Math.random());
  65680. data.push(Math.random());
  65681. data.push(Math.random());
  65682. data.push(Math.random());
  65683. data.push(Math.random());
  65684. }
  65685. }
  65686. // Sprite data
  65687. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  65688. -0.5, 0.5, 0, 1,
  65689. -0.5, -0.5, 0, 0,
  65690. 0.5, -0.5, 1, 0]);
  65691. // Buffers
  65692. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65693. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  65694. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  65695. // Update VAO
  65696. this._updateVAO = [];
  65697. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  65698. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  65699. // Render VAO
  65700. this._renderVAO = [];
  65701. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  65702. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  65703. // Links
  65704. this._sourceBuffer = this._buffer0;
  65705. this._targetBuffer = this._buffer1;
  65706. };
  65707. /** @hidden */
  65708. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  65709. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  65710. if (this._isBillboardBased) {
  65711. defines += "\n#define BILLBOARD";
  65712. }
  65713. if (this._colorGradientsTexture) {
  65714. defines += "\n#define COLORGRADIENTS";
  65715. }
  65716. if (this._sizeGradientsTexture) {
  65717. defines += "\n#define SIZEGRADIENTS";
  65718. }
  65719. if (this._angularSpeedGradientsTexture) {
  65720. defines += "\n#define ANGULARSPEEDGRADIENTS";
  65721. }
  65722. if (this._velocityGradientsTexture) {
  65723. defines += "\n#define VELOCITYGRADIENTS";
  65724. }
  65725. if (this._limitVelocityGradientsTexture) {
  65726. defines += "\n#define LIMITVELOCITYGRADIENTS";
  65727. }
  65728. if (this._dragGradientsTexture) {
  65729. defines += "\n#define DRAGGRADIENTS";
  65730. }
  65731. if (this.isAnimationSheetEnabled) {
  65732. defines += "\n#define ANIMATESHEET";
  65733. if (this.spriteRandomStartCell) {
  65734. defines += "\n#define ANIMATESHEETRANDOMSTART";
  65735. }
  65736. }
  65737. if (this.noiseTexture) {
  65738. defines += "\n#define NOISE";
  65739. }
  65740. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  65741. return;
  65742. }
  65743. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  65744. if (!this._colorGradientsTexture) {
  65745. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  65746. }
  65747. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  65748. if (!this._isBillboardBased) {
  65749. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  65750. }
  65751. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  65752. if (this.isAnimationSheetEnabled) {
  65753. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  65754. if (this.spriteRandomStartCell) {
  65755. this._updateEffectOptions.transformFeedbackVaryings.push("outCellStartOffset");
  65756. }
  65757. }
  65758. if (this.noiseTexture) {
  65759. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates1");
  65760. this._updateEffectOptions.transformFeedbackVaryings.push("outNoiseCoordinates2");
  65761. }
  65762. this._updateEffectOptions.defines = defines;
  65763. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  65764. };
  65765. /** @hidden */
  65766. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  65767. var defines = "";
  65768. if (this._scene.clipPlane) {
  65769. defines = "\n#define CLIPPLANE";
  65770. }
  65771. if (this._scene.clipPlane2) {
  65772. defines = "\n#define CLIPPLANE2";
  65773. }
  65774. if (this._scene.clipPlane3) {
  65775. defines = "\n#define CLIPPLANE3";
  65776. }
  65777. if (this._scene.clipPlane4) {
  65778. defines = "\n#define CLIPPLANE4";
  65779. }
  65780. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_MULTIPLY) {
  65781. defines = "\n#define BLENDMULTIPLYMODE";
  65782. }
  65783. if (this._isBillboardBased) {
  65784. defines += "\n#define BILLBOARD";
  65785. switch (this.billboardMode) {
  65786. case BABYLON.ParticleSystem.BILLBOARDMODE_Y:
  65787. defines += "\n#define BILLBOARDY";
  65788. break;
  65789. case BABYLON.ParticleSystem.BILLBOARDMODE_STRETCHED:
  65790. defines += "\n#define BILLBOARDSTRETCHED";
  65791. break;
  65792. case BABYLON.ParticleSystem.BILLBOARDMODE_ALL:
  65793. default:
  65794. break;
  65795. }
  65796. }
  65797. if (this._colorGradientsTexture) {
  65798. defines += "\n#define COLORGRADIENTS";
  65799. }
  65800. if (this.isAnimationSheetEnabled) {
  65801. defines += "\n#define ANIMATESHEET";
  65802. }
  65803. if (this._imageProcessingConfiguration) {
  65804. this._imageProcessingConfiguration.prepareDefines(this._imageProcessingConfigurationDefines);
  65805. defines += "\n" + this._imageProcessingConfigurationDefines.toString();
  65806. }
  65807. if (this._renderEffect && this._renderEffect.defines === defines) {
  65808. return;
  65809. }
  65810. var uniforms = ["view", "projection", "colorDead", "invView", "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "sheetInfos", "translationPivot", "eyePosition"];
  65811. var samplers = ["textureSampler", "colorGradientSampler"];
  65812. if (BABYLON.ImageProcessingConfiguration) {
  65813. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._imageProcessingConfigurationDefines);
  65814. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._imageProcessingConfigurationDefines);
  65815. }
  65816. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "direction", "initialDirection", "angle", "cellIndex"], uniforms, samplers, this._scene.getEngine(), defines);
  65817. };
  65818. /**
  65819. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  65820. * @param preWarm defines if we are in the pre-warmimg phase
  65821. */
  65822. GPUParticleSystem.prototype.animate = function (preWarm) {
  65823. if (preWarm === void 0) { preWarm = false; }
  65824. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  65825. this._actualFrame += this._timeDelta;
  65826. if (!this._stopped) {
  65827. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  65828. this.stop();
  65829. }
  65830. }
  65831. };
  65832. GPUParticleSystem.prototype._createFactorGradientTexture = function (factorGradients, textureName) {
  65833. var texture = this[textureName];
  65834. if (!factorGradients || !factorGradients.length || texture) {
  65835. return;
  65836. }
  65837. var data = new Float32Array(this._rawTextureWidth);
  65838. for (var x = 0; x < this._rawTextureWidth; x++) {
  65839. var ratio = x / this._rawTextureWidth;
  65840. BABYLON.Tools.GetCurrentGradient(ratio, factorGradients, function (currentGradient, nextGradient, scale) {
  65841. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  65842. });
  65843. }
  65844. this[textureName] = BABYLON.RawTexture.CreateRTexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65845. };
  65846. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  65847. this._createFactorGradientTexture(this._sizeGradients, "_sizeGradientsTexture");
  65848. };
  65849. GPUParticleSystem.prototype._createAngularSpeedGradientTexture = function () {
  65850. this._createFactorGradientTexture(this._angularSpeedGradients, "_angularSpeedGradientsTexture");
  65851. };
  65852. GPUParticleSystem.prototype._createVelocityGradientTexture = function () {
  65853. this._createFactorGradientTexture(this._velocityGradients, "_velocityGradientsTexture");
  65854. };
  65855. GPUParticleSystem.prototype._createLimitVelocityGradientTexture = function () {
  65856. this._createFactorGradientTexture(this._limitVelocityGradients, "_limitVelocityGradientsTexture");
  65857. };
  65858. GPUParticleSystem.prototype._createDragGradientTexture = function () {
  65859. this._createFactorGradientTexture(this._dragGradients, "_dragGradientsTexture");
  65860. };
  65861. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  65862. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  65863. return;
  65864. }
  65865. var data = new Uint8Array(this._rawTextureWidth * 4);
  65866. var tmpColor = BABYLON.Tmp.Color4[0];
  65867. for (var x = 0; x < this._rawTextureWidth; x++) {
  65868. var ratio = x / this._rawTextureWidth;
  65869. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  65870. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  65871. data[x * 4] = tmpColor.r * 255;
  65872. data[x * 4 + 1] = tmpColor.g * 255;
  65873. data[x * 4 + 2] = tmpColor.b * 255;
  65874. data[x * 4 + 3] = tmpColor.a * 255;
  65875. });
  65876. }
  65877. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, this._rawTextureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  65878. };
  65879. /**
  65880. * Renders the particle system in its current state
  65881. * @param preWarm defines if the system should only update the particles but not render them
  65882. * @returns the current number of particles
  65883. */
  65884. GPUParticleSystem.prototype.render = function (preWarm) {
  65885. if (preWarm === void 0) { preWarm = false; }
  65886. if (!this._started) {
  65887. return 0;
  65888. }
  65889. this._createColorGradientTexture();
  65890. this._createSizeGradientTexture();
  65891. this._createAngularSpeedGradientTexture();
  65892. this._createVelocityGradientTexture();
  65893. this._createLimitVelocityGradientTexture();
  65894. this._createDragGradientTexture();
  65895. this._recreateUpdateEffect();
  65896. this._recreateRenderEffect();
  65897. if (!this.isReady()) {
  65898. return 0;
  65899. }
  65900. if (!preWarm) {
  65901. if (!this._preWarmDone && this.preWarmCycles) {
  65902. for (var index = 0; index < this.preWarmCycles; index++) {
  65903. this.animate(true);
  65904. this.render(true);
  65905. }
  65906. this._preWarmDone = true;
  65907. }
  65908. if (this._currentRenderId === this._scene.getRenderId()) {
  65909. return 0;
  65910. }
  65911. this._currentRenderId = this._scene.getRenderId();
  65912. }
  65913. // Get everything ready to render
  65914. this._initialize();
  65915. this._accumulatedCount += this.emitRate * this._timeDelta;
  65916. if (this._accumulatedCount > 1) {
  65917. var intPart = this._accumulatedCount | 0;
  65918. this._accumulatedCount -= intPart;
  65919. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  65920. }
  65921. if (!this._currentActiveCount) {
  65922. return 0;
  65923. }
  65924. // Enable update effect
  65925. this._engine.enableEffect(this._updateEffect);
  65926. this._engine.setState(false);
  65927. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  65928. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  65929. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  65930. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  65931. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  65932. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  65933. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  65934. if (!this._colorGradientsTexture) {
  65935. this._updateEffect.setDirectColor4("color1", this.color1);
  65936. this._updateEffect.setDirectColor4("color2", this.color2);
  65937. }
  65938. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  65939. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  65940. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  65941. this._updateEffect.setVector3("gravity", this.gravity);
  65942. if (this._sizeGradientsTexture) {
  65943. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  65944. }
  65945. if (this._angularSpeedGradientsTexture) {
  65946. this._updateEffect.setTexture("angularSpeedGradientSampler", this._angularSpeedGradientsTexture);
  65947. }
  65948. if (this._velocityGradientsTexture) {
  65949. this._updateEffect.setTexture("velocityGradientSampler", this._velocityGradientsTexture);
  65950. }
  65951. if (this._limitVelocityGradientsTexture) {
  65952. this._updateEffect.setTexture("limitVelocityGradientSampler", this._limitVelocityGradientsTexture);
  65953. this._updateEffect.setFloat("limitVelocityDamping", this.limitVelocityDamping);
  65954. }
  65955. if (this._dragGradientsTexture) {
  65956. this._updateEffect.setTexture("dragGradientSampler", this._dragGradientsTexture);
  65957. }
  65958. if (this.particleEmitterType) {
  65959. this.particleEmitterType.applyToShader(this._updateEffect);
  65960. }
  65961. if (this._isAnimationSheetEnabled) {
  65962. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  65963. }
  65964. if (this.noiseTexture) {
  65965. this._updateEffect.setTexture("noiseSampler", this.noiseTexture);
  65966. this._updateEffect.setVector3("noiseStrength", this.noiseStrength);
  65967. }
  65968. var emitterWM;
  65969. if (this.emitter.position) {
  65970. var emitterMesh = this.emitter;
  65971. emitterWM = emitterMesh.getWorldMatrix();
  65972. }
  65973. else {
  65974. var emitterPosition = this.emitter;
  65975. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  65976. }
  65977. this._updateEffect.setMatrix("emitterWM", emitterWM);
  65978. // Bind source VAO
  65979. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  65980. // Update
  65981. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  65982. this._engine.setRasterizerState(false);
  65983. this._engine.beginTransformFeedback(true);
  65984. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  65985. this._engine.endTransformFeedback();
  65986. this._engine.setRasterizerState(true);
  65987. this._engine.bindTransformFeedbackBuffer(null);
  65988. if (!preWarm) {
  65989. // Enable render effect
  65990. this._engine.enableEffect(this._renderEffect);
  65991. var viewMatrix = this._scene.getViewMatrix();
  65992. this._renderEffect.setMatrix("view", viewMatrix);
  65993. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  65994. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  65995. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  65996. if (this._colorGradientsTexture) {
  65997. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  65998. }
  65999. else {
  66000. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  66001. }
  66002. if (this._isAnimationSheetEnabled && this.particleTexture) {
  66003. var baseSize = this.particleTexture.getBaseSize();
  66004. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  66005. }
  66006. if (this._isBillboardBased) {
  66007. var camera = this._scene.activeCamera;
  66008. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  66009. }
  66010. if (this._scene.clipPlane || this._scene.clipPlane2 || this._scene.clipPlane3 || this._scene.clipPlane4) {
  66011. var invView = viewMatrix.clone();
  66012. invView.invert();
  66013. this._renderEffect.setMatrix("invView", invView);
  66014. BABYLON.MaterialHelper.BindClipPlane(this._renderEffect, this._scene);
  66015. }
  66016. // image processing
  66017. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  66018. this._imageProcessingConfiguration.bind(this._renderEffect);
  66019. }
  66020. // Draw order
  66021. switch (this.blendMode) {
  66022. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  66023. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  66024. break;
  66025. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  66026. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  66027. break;
  66028. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  66029. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  66030. break;
  66031. case BABYLON.ParticleSystem.BLENDMODE_MULTIPLY:
  66032. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_MULTIPLY);
  66033. break;
  66034. }
  66035. if (this.forceDepthWrite) {
  66036. this._engine.setDepthWrite(true);
  66037. }
  66038. // Bind source VAO
  66039. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  66040. // Render
  66041. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  66042. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  66043. }
  66044. // Switch VAOs
  66045. this._targetIndex++;
  66046. if (this._targetIndex === 2) {
  66047. this._targetIndex = 0;
  66048. }
  66049. // Switch buffers
  66050. var tmpBuffer = this._sourceBuffer;
  66051. this._sourceBuffer = this._targetBuffer;
  66052. this._targetBuffer = tmpBuffer;
  66053. return this._currentActiveCount;
  66054. };
  66055. /**
  66056. * Rebuilds the particle system
  66057. */
  66058. GPUParticleSystem.prototype.rebuild = function () {
  66059. this._initialize(true);
  66060. };
  66061. GPUParticleSystem.prototype._releaseBuffers = function () {
  66062. if (this._buffer0) {
  66063. this._buffer0.dispose();
  66064. this._buffer0 = null;
  66065. }
  66066. if (this._buffer1) {
  66067. this._buffer1.dispose();
  66068. this._buffer1 = null;
  66069. }
  66070. if (this._spriteBuffer) {
  66071. this._spriteBuffer.dispose();
  66072. this._spriteBuffer = null;
  66073. }
  66074. };
  66075. GPUParticleSystem.prototype._releaseVAOs = function () {
  66076. if (!this._updateVAO) {
  66077. return;
  66078. }
  66079. for (var index = 0; index < this._updateVAO.length; index++) {
  66080. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  66081. }
  66082. this._updateVAO = [];
  66083. for (var index = 0; index < this._renderVAO.length; index++) {
  66084. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  66085. }
  66086. this._renderVAO = [];
  66087. };
  66088. /**
  66089. * Disposes the particle system and free the associated resources
  66090. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  66091. */
  66092. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  66093. if (disposeTexture === void 0) { disposeTexture = true; }
  66094. var index = this._scene.particleSystems.indexOf(this);
  66095. if (index > -1) {
  66096. this._scene.particleSystems.splice(index, 1);
  66097. }
  66098. this._releaseBuffers();
  66099. this._releaseVAOs();
  66100. if (this._colorGradientsTexture) {
  66101. this._colorGradientsTexture.dispose();
  66102. this._colorGradientsTexture = null;
  66103. }
  66104. if (this._sizeGradientsTexture) {
  66105. this._sizeGradientsTexture.dispose();
  66106. this._sizeGradientsTexture = null;
  66107. }
  66108. if (this._angularSpeedGradientsTexture) {
  66109. this._angularSpeedGradientsTexture.dispose();
  66110. this._angularSpeedGradientsTexture = null;
  66111. }
  66112. if (this._velocityGradientsTexture) {
  66113. this._velocityGradientsTexture.dispose();
  66114. this._velocityGradientsTexture = null;
  66115. }
  66116. if (this._limitVelocityGradientsTexture) {
  66117. this._limitVelocityGradientsTexture.dispose();
  66118. this._limitVelocityGradientsTexture = null;
  66119. }
  66120. if (this._dragGradientsTexture) {
  66121. this._dragGradientsTexture.dispose();
  66122. this._dragGradientsTexture = null;
  66123. }
  66124. if (this._randomTexture) {
  66125. this._randomTexture.dispose();
  66126. this._randomTexture = null;
  66127. }
  66128. if (this._randomTexture2) {
  66129. this._randomTexture2.dispose();
  66130. this._randomTexture2 = null;
  66131. }
  66132. if (disposeTexture && this.particleTexture) {
  66133. this.particleTexture.dispose();
  66134. this.particleTexture = null;
  66135. }
  66136. if (disposeTexture && this.noiseTexture) {
  66137. this.noiseTexture.dispose();
  66138. this.noiseTexture = null;
  66139. }
  66140. // Callback
  66141. this.onDisposeObservable.notifyObservers(this);
  66142. this.onDisposeObservable.clear();
  66143. };
  66144. /**
  66145. * Clones the particle system.
  66146. * @param name The name of the cloned object
  66147. * @param newEmitter The new emitter to use
  66148. * @returns the cloned particle system
  66149. */
  66150. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  66151. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  66152. BABYLON.Tools.DeepCopy(this, result);
  66153. if (newEmitter === undefined) {
  66154. newEmitter = this.emitter;
  66155. }
  66156. result.emitter = newEmitter;
  66157. if (this.particleTexture) {
  66158. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  66159. }
  66160. return result;
  66161. };
  66162. /**
  66163. * Serializes the particle system to a JSON object.
  66164. * @returns the JSON object
  66165. */
  66166. GPUParticleSystem.prototype.serialize = function () {
  66167. var serializationObject = {};
  66168. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  66169. serializationObject.activeParticleCount = this.activeParticleCount;
  66170. return serializationObject;
  66171. };
  66172. /**
  66173. * Parses a JSON object to create a GPU particle system.
  66174. * @param parsedParticleSystem The JSON object to parse
  66175. * @param scene The scene to create the particle system in
  66176. * @param rootUrl The root url to use to load external dependencies like texture
  66177. * @param doNotStart Ignore the preventAutoStart attribute and does not start
  66178. * @returns the parsed GPU particle system
  66179. */
  66180. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl, doNotStart) {
  66181. if (doNotStart === void 0) { doNotStart = false; }
  66182. var name = parsedParticleSystem.name;
  66183. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  66184. if (parsedParticleSystem.activeParticleCount) {
  66185. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  66186. }
  66187. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  66188. // Auto start
  66189. if (parsedParticleSystem.preventAutoStart) {
  66190. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  66191. }
  66192. if (!doNotStart && !particleSystem.preventAutoStart) {
  66193. particleSystem.start();
  66194. }
  66195. return particleSystem;
  66196. };
  66197. return GPUParticleSystem;
  66198. }(BABYLON.BaseParticleSystem));
  66199. BABYLON.GPUParticleSystem = GPUParticleSystem;
  66200. })(BABYLON || (BABYLON = {}));
  66201. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  66202. var BABYLON;
  66203. (function (BABYLON) {
  66204. /**
  66205. * Represents one particle of a solid particle system.
  66206. */
  66207. var SolidParticle = /** @class */ (function () {
  66208. /**
  66209. * Creates a Solid Particle object.
  66210. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  66211. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  66212. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  66213. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  66214. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  66215. * @param shapeId (integer) is the model shape identifier in the SPS.
  66216. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  66217. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  66218. */
  66219. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  66220. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  66221. /**
  66222. * particle global index
  66223. */
  66224. this.idx = 0;
  66225. /**
  66226. * The color of the particle
  66227. */
  66228. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66229. /**
  66230. * The world space position of the particle.
  66231. */
  66232. this.position = BABYLON.Vector3.Zero();
  66233. /**
  66234. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  66235. */
  66236. this.rotation = BABYLON.Vector3.Zero();
  66237. /**
  66238. * The scaling of the particle.
  66239. */
  66240. this.scaling = BABYLON.Vector3.One();
  66241. /**
  66242. * The uvs of the particle.
  66243. */
  66244. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  66245. /**
  66246. * The current speed of the particle.
  66247. */
  66248. this.velocity = BABYLON.Vector3.Zero();
  66249. /**
  66250. * The pivot point in the particle local space.
  66251. */
  66252. this.pivot = BABYLON.Vector3.Zero();
  66253. /**
  66254. * Must the particle be translated from its pivot point in its local space ?
  66255. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  66256. * Default : false
  66257. */
  66258. this.translateFromPivot = false;
  66259. /**
  66260. * Is the particle active or not ?
  66261. */
  66262. this.alive = true;
  66263. /**
  66264. * Is the particle visible or not ?
  66265. */
  66266. this.isVisible = true;
  66267. /**
  66268. * Index of this particle in the global "positions" array (Internal use)
  66269. * @hidden
  66270. */
  66271. this._pos = 0;
  66272. /**
  66273. * @hidden Index of this particle in the global "indices" array (Internal use)
  66274. */
  66275. this._ind = 0;
  66276. /**
  66277. * ModelShape id of this particle
  66278. */
  66279. this.shapeId = 0;
  66280. /**
  66281. * Index of the particle in its shape id (Internal use)
  66282. */
  66283. this.idxInShape = 0;
  66284. /**
  66285. * @hidden Still set as invisible in order to skip useless computations (Internal use)
  66286. */
  66287. this._stillInvisible = false;
  66288. /**
  66289. * @hidden Last computed particle rotation matrix
  66290. */
  66291. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  66292. /**
  66293. * Parent particle Id, if any.
  66294. * Default null.
  66295. */
  66296. this.parentId = null;
  66297. /**
  66298. * @hidden Internal global position in the SPS.
  66299. */
  66300. this._globalPosition = BABYLON.Vector3.Zero();
  66301. this.idx = particleIndex;
  66302. this._pos = positionIndex;
  66303. this._ind = indiceIndex;
  66304. this._model = model;
  66305. this.shapeId = shapeId;
  66306. this.idxInShape = idxInShape;
  66307. this._sps = sps;
  66308. if (modelBoundingInfo) {
  66309. this._modelBoundingInfo = modelBoundingInfo;
  66310. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  66311. }
  66312. }
  66313. Object.defineProperty(SolidParticle.prototype, "scale", {
  66314. /**
  66315. * Legacy support, changed scale to scaling
  66316. */
  66317. get: function () {
  66318. return this.scaling;
  66319. },
  66320. /**
  66321. * Legacy support, changed scale to scaling
  66322. */
  66323. set: function (scale) {
  66324. this.scaling = scale;
  66325. },
  66326. enumerable: true,
  66327. configurable: true
  66328. });
  66329. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  66330. /**
  66331. * Legacy support, changed quaternion to rotationQuaternion
  66332. */
  66333. get: function () {
  66334. return this.rotationQuaternion;
  66335. },
  66336. /**
  66337. * Legacy support, changed quaternion to rotationQuaternion
  66338. */
  66339. set: function (q) {
  66340. this.rotationQuaternion = q;
  66341. },
  66342. enumerable: true,
  66343. configurable: true
  66344. });
  66345. /**
  66346. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  66347. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  66348. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  66349. * @returns true if it intersects
  66350. */
  66351. SolidParticle.prototype.intersectsMesh = function (target) {
  66352. if (!this._boundingInfo || !target._boundingInfo) {
  66353. return false;
  66354. }
  66355. if (this._sps._bSphereOnly) {
  66356. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  66357. }
  66358. return this._boundingInfo.intersects(target._boundingInfo, false);
  66359. };
  66360. return SolidParticle;
  66361. }());
  66362. BABYLON.SolidParticle = SolidParticle;
  66363. /**
  66364. * Represents the shape of the model used by one particle of a solid particle system.
  66365. * SPS internal tool, don't use it manually.
  66366. */
  66367. var ModelShape = /** @class */ (function () {
  66368. /**
  66369. * 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.
  66370. * SPS internal tool, don't use it manually.
  66371. * @hidden
  66372. */
  66373. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  66374. /**
  66375. * length of the shape in the model indices array (internal use)
  66376. * @hidden
  66377. */
  66378. this._indicesLength = 0;
  66379. this.shapeID = id;
  66380. this._shape = shape;
  66381. this._indicesLength = indicesLength;
  66382. this._shapeUV = shapeUV;
  66383. this._positionFunction = posFunction;
  66384. this._vertexFunction = vtxFunction;
  66385. }
  66386. return ModelShape;
  66387. }());
  66388. BABYLON.ModelShape = ModelShape;
  66389. /**
  66390. * Represents a Depth Sorted Particle in the solid particle system.
  66391. */
  66392. var DepthSortedParticle = /** @class */ (function () {
  66393. function DepthSortedParticle() {
  66394. /**
  66395. * Index of the particle in the "indices" array
  66396. */
  66397. this.ind = 0;
  66398. /**
  66399. * Length of the particle shape in the "indices" array
  66400. */
  66401. this.indicesLength = 0;
  66402. /**
  66403. * Squared distance from the particle to the camera
  66404. */
  66405. this.sqDistance = 0.0;
  66406. }
  66407. return DepthSortedParticle;
  66408. }());
  66409. BABYLON.DepthSortedParticle = DepthSortedParticle;
  66410. })(BABYLON || (BABYLON = {}));
  66411. //# sourceMappingURL=babylon.solidParticle.js.map
  66412. var BABYLON;
  66413. (function (BABYLON) {
  66414. /**
  66415. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  66416. *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.
  66417. * The SPS is also a particle system. It provides some methods to manage the particles.
  66418. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  66419. *
  66420. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  66421. */
  66422. var SolidParticleSystem = /** @class */ (function () {
  66423. /**
  66424. * Creates a SPS (Solid Particle System) object.
  66425. * @param name (String) is the SPS name, this will be the underlying mesh name.
  66426. * @param scene (Scene) is the scene in which the SPS is added.
  66427. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  66428. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  66429. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  66430. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  66431. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  66432. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  66433. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  66434. */
  66435. function SolidParticleSystem(name, scene, options) {
  66436. /**
  66437. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  66438. * Example : var p = SPS.particles[i];
  66439. */
  66440. this.particles = new Array();
  66441. /**
  66442. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  66443. */
  66444. this.nbParticles = 0;
  66445. /**
  66446. * If the particles must ever face the camera (default false). Useful for planar particles.
  66447. */
  66448. this.billboard = false;
  66449. /**
  66450. * Recompute normals when adding a shape
  66451. */
  66452. this.recomputeNormals = true;
  66453. /**
  66454. * This a counter ofr your own usage. It's not set by any SPS functions.
  66455. */
  66456. this.counter = 0;
  66457. /**
  66458. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  66459. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  66460. */
  66461. this.vars = {};
  66462. /**
  66463. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  66464. * @hidden
  66465. */
  66466. this._bSphereOnly = false;
  66467. /**
  66468. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  66469. * @hidden
  66470. */
  66471. this._bSphereRadiusFactor = 1.0;
  66472. this._positions = new Array();
  66473. this._indices = new Array();
  66474. this._normals = new Array();
  66475. this._colors = new Array();
  66476. this._uvs = new Array();
  66477. this._index = 0; // indices index
  66478. this._updatable = true;
  66479. this._pickable = false;
  66480. this._isVisibilityBoxLocked = false;
  66481. this._alwaysVisible = false;
  66482. this._depthSort = false;
  66483. this._shapeCounter = 0;
  66484. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  66485. this._color = new BABYLON.Color4(0, 0, 0, 0);
  66486. this._computeParticleColor = true;
  66487. this._computeParticleTexture = true;
  66488. this._computeParticleRotation = true;
  66489. this._computeParticleVertex = false;
  66490. this._computeBoundingBox = false;
  66491. this._depthSortParticles = true;
  66492. this._cam_axisZ = BABYLON.Vector3.Zero();
  66493. this._cam_axisY = BABYLON.Vector3.Zero();
  66494. this._cam_axisX = BABYLON.Vector3.Zero();
  66495. this._axisZ = BABYLON.Axis.Z;
  66496. this._camDir = BABYLON.Vector3.Zero();
  66497. this._camInvertedPosition = BABYLON.Vector3.Zero();
  66498. this._rotMatrix = new BABYLON.Matrix();
  66499. this._invertMatrix = new BABYLON.Matrix();
  66500. this._rotated = BABYLON.Vector3.Zero();
  66501. this._quaternion = new BABYLON.Quaternion();
  66502. this._vertex = BABYLON.Vector3.Zero();
  66503. this._normal = BABYLON.Vector3.Zero();
  66504. this._yaw = 0.0;
  66505. this._pitch = 0.0;
  66506. this._roll = 0.0;
  66507. this._halfroll = 0.0;
  66508. this._halfpitch = 0.0;
  66509. this._halfyaw = 0.0;
  66510. this._sinRoll = 0.0;
  66511. this._cosRoll = 0.0;
  66512. this._sinPitch = 0.0;
  66513. this._cosPitch = 0.0;
  66514. this._sinYaw = 0.0;
  66515. this._cosYaw = 0.0;
  66516. this._mustUnrotateFixedNormals = false;
  66517. this._minimum = BABYLON.Vector3.Zero();
  66518. this._maximum = BABYLON.Vector3.Zero();
  66519. this._minBbox = BABYLON.Vector3.Zero();
  66520. this._maxBbox = BABYLON.Vector3.Zero();
  66521. this._particlesIntersect = false;
  66522. this._depthSortFunction = function (p1, p2) {
  66523. return (p2.sqDistance - p1.sqDistance);
  66524. };
  66525. this._needs32Bits = false;
  66526. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  66527. this._scaledPivot = BABYLON.Vector3.Zero();
  66528. this._particleHasParent = false;
  66529. this.name = name;
  66530. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  66531. this._camera = scene.activeCamera;
  66532. this._pickable = options ? options.isPickable : false;
  66533. this._depthSort = options ? options.enableDepthSort : false;
  66534. this._particlesIntersect = options ? options.particleIntersection : false;
  66535. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  66536. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  66537. if (options && options.updatable !== undefined) {
  66538. this._updatable = options.updatable;
  66539. }
  66540. else {
  66541. this._updatable = true;
  66542. }
  66543. if (this._pickable) {
  66544. this.pickedParticles = [];
  66545. }
  66546. if (this._depthSort) {
  66547. this.depthSortedParticles = [];
  66548. }
  66549. }
  66550. /**
  66551. * Builds the SPS underlying mesh. Returns a standard Mesh.
  66552. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  66553. * @returns the created mesh
  66554. */
  66555. SolidParticleSystem.prototype.buildMesh = function () {
  66556. if (this.nbParticles === 0) {
  66557. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  66558. this.addShape(triangle, 1);
  66559. triangle.dispose();
  66560. }
  66561. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  66562. this._positions32 = new Float32Array(this._positions);
  66563. this._uvs32 = new Float32Array(this._uvs);
  66564. this._colors32 = new Float32Array(this._colors);
  66565. if (this.recomputeNormals) {
  66566. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  66567. }
  66568. this._normals32 = new Float32Array(this._normals);
  66569. this._fixedNormal32 = new Float32Array(this._normals);
  66570. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  66571. this._unrotateFixedNormals();
  66572. }
  66573. var vertexData = new BABYLON.VertexData();
  66574. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  66575. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  66576. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  66577. if (this._uvs32.length > 0) {
  66578. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  66579. }
  66580. if (this._colors32.length > 0) {
  66581. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  66582. }
  66583. var mesh = new BABYLON.Mesh(this.name, this._scene);
  66584. vertexData.applyToMesh(mesh, this._updatable);
  66585. this.mesh = mesh;
  66586. this.mesh.isPickable = this._pickable;
  66587. // free memory
  66588. if (!this._depthSort) {
  66589. this._indices = null;
  66590. }
  66591. this._positions = null;
  66592. this._normals = null;
  66593. this._uvs = null;
  66594. this._colors = null;
  66595. if (!this._updatable) {
  66596. this.particles.length = 0;
  66597. }
  66598. return mesh;
  66599. };
  66600. /**
  66601. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  66602. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  66603. * Thus the particles generated from `digest()` have their property `position` set yet.
  66604. * @param mesh ( Mesh ) is the mesh to be digested
  66605. * @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
  66606. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  66607. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  66608. * @returns the current SPS
  66609. */
  66610. SolidParticleSystem.prototype.digest = function (mesh, options) {
  66611. var size = (options && options.facetNb) || 1;
  66612. var number = (options && options.number) || 0;
  66613. var delta = (options && options.delta) || 0;
  66614. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66615. var meshInd = mesh.getIndices();
  66616. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66617. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66618. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66619. var f = 0; // facet counter
  66620. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  66621. // compute size from number
  66622. if (number) {
  66623. number = (number > totalFacets) ? totalFacets : number;
  66624. size = Math.round(totalFacets / number);
  66625. delta = 0;
  66626. }
  66627. else {
  66628. size = (size > totalFacets) ? totalFacets : size;
  66629. }
  66630. var facetPos = []; // submesh positions
  66631. var facetInd = []; // submesh indices
  66632. var facetUV = []; // submesh UV
  66633. var facetCol = []; // submesh colors
  66634. var barycenter = BABYLON.Vector3.Zero();
  66635. var sizeO = size;
  66636. while (f < totalFacets) {
  66637. size = sizeO + Math.floor((1 + delta) * Math.random());
  66638. if (f > totalFacets - size) {
  66639. size = totalFacets - f;
  66640. }
  66641. // reset temp arrays
  66642. facetPos.length = 0;
  66643. facetInd.length = 0;
  66644. facetUV.length = 0;
  66645. facetCol.length = 0;
  66646. // iterate over "size" facets
  66647. var fi = 0;
  66648. for (var j = f * 3; j < (f + size) * 3; j++) {
  66649. facetInd.push(fi);
  66650. var i = meshInd[j];
  66651. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  66652. if (meshUV) {
  66653. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  66654. }
  66655. if (meshCol) {
  66656. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  66657. }
  66658. fi++;
  66659. }
  66660. // create a model shape for each single particle
  66661. var idx = this.nbParticles;
  66662. var shape = this._posToShape(facetPos);
  66663. var shapeUV = this._uvsToShapeUV(facetUV);
  66664. // compute the barycenter of the shape
  66665. var v;
  66666. for (v = 0; v < shape.length; v++) {
  66667. barycenter.addInPlace(shape[v]);
  66668. }
  66669. barycenter.scaleInPlace(1 / shape.length);
  66670. // shift the shape from its barycenter to the origin
  66671. for (v = 0; v < shape.length; v++) {
  66672. shape[v].subtractInPlace(barycenter);
  66673. }
  66674. var bInfo;
  66675. if (this._particlesIntersect) {
  66676. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  66677. }
  66678. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  66679. // add the particle in the SPS
  66680. var currentPos = this._positions.length;
  66681. var currentInd = this._indices.length;
  66682. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  66683. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  66684. // initialize the particle position
  66685. this.particles[this.nbParticles].position.addInPlace(barycenter);
  66686. this._index += shape.length;
  66687. idx++;
  66688. this.nbParticles++;
  66689. this._shapeCounter++;
  66690. f += size;
  66691. }
  66692. return this;
  66693. };
  66694. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  66695. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  66696. var index = 0;
  66697. var idx = 0;
  66698. for (var p = 0; p < this.particles.length; p++) {
  66699. this._particle = this.particles[p];
  66700. this._shape = this._particle._model._shape;
  66701. if (this._particle.rotationQuaternion) {
  66702. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  66703. }
  66704. else {
  66705. this._yaw = this._particle.rotation.y;
  66706. this._pitch = this._particle.rotation.x;
  66707. this._roll = this._particle.rotation.z;
  66708. this._quaternionRotationYPR();
  66709. }
  66710. this._quaternionToRotationMatrix();
  66711. this._rotMatrix.invertToRef(this._invertMatrix);
  66712. for (var pt = 0; pt < this._shape.length; pt++) {
  66713. idx = index + pt * 3;
  66714. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  66715. this._fixedNormal32[idx] = this._normal.x;
  66716. this._fixedNormal32[idx + 1] = this._normal.y;
  66717. this._fixedNormal32[idx + 2] = this._normal.z;
  66718. }
  66719. index = idx + 3;
  66720. }
  66721. };
  66722. //reset copy
  66723. SolidParticleSystem.prototype._resetCopy = function () {
  66724. this._copy.position.x = 0;
  66725. this._copy.position.y = 0;
  66726. this._copy.position.z = 0;
  66727. this._copy.rotation.x = 0;
  66728. this._copy.rotation.y = 0;
  66729. this._copy.rotation.z = 0;
  66730. this._copy.rotationQuaternion = null;
  66731. this._copy.scaling.x = 1.0;
  66732. this._copy.scaling.y = 1.0;
  66733. this._copy.scaling.z = 1.0;
  66734. this._copy.uvs.x = 0;
  66735. this._copy.uvs.y = 0;
  66736. this._copy.uvs.z = 1.0;
  66737. this._copy.uvs.w = 1.0;
  66738. this._copy.color = null;
  66739. this._copy.translateFromPivot = false;
  66740. };
  66741. // _meshBuilder : inserts the shape model in the global SPS mesh
  66742. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  66743. var i;
  66744. var u = 0;
  66745. var c = 0;
  66746. var n = 0;
  66747. this._resetCopy();
  66748. if (options && options.positionFunction) { // call to custom positionFunction
  66749. options.positionFunction(this._copy, idx, idxInShape);
  66750. this._mustUnrotateFixedNormals = true;
  66751. }
  66752. if (this._copy.rotationQuaternion) {
  66753. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66754. }
  66755. else {
  66756. this._yaw = this._copy.rotation.y;
  66757. this._pitch = this._copy.rotation.x;
  66758. this._roll = this._copy.rotation.z;
  66759. this._quaternionRotationYPR();
  66760. }
  66761. this._quaternionToRotationMatrix();
  66762. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  66763. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  66764. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  66765. if (this._copy.translateFromPivot) {
  66766. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66767. }
  66768. else {
  66769. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66770. }
  66771. for (i = 0; i < shape.length; i++) {
  66772. this._vertex.x = shape[i].x;
  66773. this._vertex.y = shape[i].y;
  66774. this._vertex.z = shape[i].z;
  66775. if (options && options.vertexFunction) {
  66776. options.vertexFunction(this._copy, this._vertex, i);
  66777. }
  66778. this._vertex.x *= this._copy.scaling.x;
  66779. this._vertex.y *= this._copy.scaling.y;
  66780. this._vertex.z *= this._copy.scaling.z;
  66781. this._vertex.x -= this._scaledPivot.x;
  66782. this._vertex.y -= this._scaledPivot.y;
  66783. this._vertex.z -= this._scaledPivot.z;
  66784. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66785. this._rotated.addInPlace(this._pivotBackTranslation);
  66786. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  66787. if (meshUV) {
  66788. 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);
  66789. u += 2;
  66790. }
  66791. if (this._copy.color) {
  66792. this._color = this._copy.color;
  66793. }
  66794. else if (meshCol && meshCol[c] !== undefined) {
  66795. this._color.r = meshCol[c];
  66796. this._color.g = meshCol[c + 1];
  66797. this._color.b = meshCol[c + 2];
  66798. this._color.a = meshCol[c + 3];
  66799. }
  66800. else {
  66801. this._color.r = 1.0;
  66802. this._color.g = 1.0;
  66803. this._color.b = 1.0;
  66804. this._color.a = 1.0;
  66805. }
  66806. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  66807. c += 4;
  66808. if (!this.recomputeNormals && meshNor) {
  66809. this._normal.x = meshNor[n];
  66810. this._normal.y = meshNor[n + 1];
  66811. this._normal.z = meshNor[n + 2];
  66812. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  66813. normals.push(this._normal.x, this._normal.y, this._normal.z);
  66814. n += 3;
  66815. }
  66816. }
  66817. for (i = 0; i < meshInd.length; i++) {
  66818. var current_ind = p + meshInd[i];
  66819. indices.push(current_ind);
  66820. if (current_ind > 65535) {
  66821. this._needs32Bits = true;
  66822. }
  66823. }
  66824. if (this._pickable) {
  66825. var nbfaces = meshInd.length / 3;
  66826. for (i = 0; i < nbfaces; i++) {
  66827. this.pickedParticles.push({ idx: idx, faceId: i });
  66828. }
  66829. }
  66830. if (this._depthSort) {
  66831. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  66832. }
  66833. return this._copy;
  66834. };
  66835. // returns a shape array from positions array
  66836. SolidParticleSystem.prototype._posToShape = function (positions) {
  66837. var shape = [];
  66838. for (var i = 0; i < positions.length; i += 3) {
  66839. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  66840. }
  66841. return shape;
  66842. };
  66843. // returns a shapeUV array from a Vector4 uvs
  66844. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  66845. var shapeUV = [];
  66846. if (uvs) {
  66847. for (var i = 0; i < uvs.length; i++)
  66848. shapeUV.push(uvs[i]);
  66849. }
  66850. return shapeUV;
  66851. };
  66852. // adds a new particle object in the particles array
  66853. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  66854. if (bInfo === void 0) { bInfo = null; }
  66855. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  66856. this.particles.push(sp);
  66857. return sp;
  66858. };
  66859. /**
  66860. * Adds some particles to the SPS from the model shape. Returns the shape id.
  66861. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  66862. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  66863. * @param nb (positive integer) the number of particles to be created from this model
  66864. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  66865. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  66866. * @returns the number of shapes in the system
  66867. */
  66868. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  66869. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66870. var meshInd = mesh.getIndices();
  66871. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66872. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66873. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66874. var bbInfo;
  66875. if (this._particlesIntersect) {
  66876. bbInfo = mesh.getBoundingInfo();
  66877. }
  66878. var shape = this._posToShape(meshPos);
  66879. var shapeUV = this._uvsToShapeUV(meshUV);
  66880. var posfunc = options ? options.positionFunction : null;
  66881. var vtxfunc = options ? options.vertexFunction : null;
  66882. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  66883. // particles
  66884. var sp;
  66885. var currentCopy;
  66886. var idx = this.nbParticles;
  66887. for (var i = 0; i < nb; i++) {
  66888. var currentPos = this._positions.length;
  66889. var currentInd = this._indices.length;
  66890. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  66891. if (this._updatable) {
  66892. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  66893. sp.position.copyFrom(currentCopy.position);
  66894. sp.rotation.copyFrom(currentCopy.rotation);
  66895. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  66896. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  66897. }
  66898. if (currentCopy.color && sp.color) {
  66899. sp.color.copyFrom(currentCopy.color);
  66900. }
  66901. sp.scaling.copyFrom(currentCopy.scaling);
  66902. sp.uvs.copyFrom(currentCopy.uvs);
  66903. }
  66904. this._index += shape.length;
  66905. idx++;
  66906. }
  66907. this.nbParticles += nb;
  66908. this._shapeCounter++;
  66909. return this._shapeCounter - 1;
  66910. };
  66911. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  66912. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  66913. this._resetCopy();
  66914. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  66915. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  66916. }
  66917. if (this._copy.rotationQuaternion) {
  66918. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  66919. }
  66920. else {
  66921. this._yaw = this._copy.rotation.y;
  66922. this._pitch = this._copy.rotation.x;
  66923. this._roll = this._copy.rotation.z;
  66924. this._quaternionRotationYPR();
  66925. }
  66926. this._quaternionToRotationMatrix();
  66927. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  66928. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  66929. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  66930. if (this._copy.translateFromPivot) {
  66931. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  66932. }
  66933. else {
  66934. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  66935. }
  66936. this._shape = particle._model._shape;
  66937. for (var pt = 0; pt < this._shape.length; pt++) {
  66938. this._vertex.x = this._shape[pt].x;
  66939. this._vertex.y = this._shape[pt].y;
  66940. this._vertex.z = this._shape[pt].z;
  66941. if (particle._model._vertexFunction) {
  66942. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  66943. }
  66944. this._vertex.x *= this._copy.scaling.x;
  66945. this._vertex.y *= this._copy.scaling.y;
  66946. this._vertex.z *= this._copy.scaling.z;
  66947. this._vertex.x -= this._scaledPivot.x;
  66948. this._vertex.y -= this._scaledPivot.y;
  66949. this._vertex.z -= this._scaledPivot.z;
  66950. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  66951. this._rotated.addInPlace(this._pivotBackTranslation);
  66952. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  66953. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  66954. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  66955. }
  66956. particle.position.x = 0.0;
  66957. particle.position.y = 0.0;
  66958. particle.position.z = 0.0;
  66959. particle.rotation.x = 0.0;
  66960. particle.rotation.y = 0.0;
  66961. particle.rotation.z = 0.0;
  66962. particle.rotationQuaternion = null;
  66963. particle.scaling.x = 1.0;
  66964. particle.scaling.y = 1.0;
  66965. particle.scaling.z = 1.0;
  66966. particle.uvs.x = 0.0;
  66967. particle.uvs.y = 0.0;
  66968. particle.uvs.z = 1.0;
  66969. particle.uvs.w = 1.0;
  66970. particle.pivot.x = 0.0;
  66971. particle.pivot.y = 0.0;
  66972. particle.pivot.z = 0.0;
  66973. particle.translateFromPivot = false;
  66974. particle.parentId = null;
  66975. };
  66976. /**
  66977. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  66978. * @returns the SPS.
  66979. */
  66980. SolidParticleSystem.prototype.rebuildMesh = function () {
  66981. for (var p = 0; p < this.particles.length; p++) {
  66982. this._rebuildParticle(this.particles[p]);
  66983. }
  66984. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  66985. return this;
  66986. };
  66987. /**
  66988. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  66989. * This method calls `updateParticle()` for each particle of the SPS.
  66990. * For an animated SPS, it is usually called within the render loop.
  66991. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  66992. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  66993. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  66994. * @returns the SPS.
  66995. */
  66996. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  66997. if (start === void 0) { start = 0; }
  66998. if (end === void 0) { end = this.nbParticles - 1; }
  66999. if (update === void 0) { update = true; }
  67000. if (!this._updatable) {
  67001. return this;
  67002. }
  67003. // custom beforeUpdate
  67004. this.beforeUpdateParticles(start, end, update);
  67005. this._cam_axisX.x = 1.0;
  67006. this._cam_axisX.y = 0.0;
  67007. this._cam_axisX.z = 0.0;
  67008. this._cam_axisY.x = 0.0;
  67009. this._cam_axisY.y = 1.0;
  67010. this._cam_axisY.z = 0.0;
  67011. this._cam_axisZ.x = 0.0;
  67012. this._cam_axisZ.y = 0.0;
  67013. this._cam_axisZ.z = 1.0;
  67014. // cases when the World Matrix is to be computed first
  67015. if (this.billboard || this._depthSort) {
  67016. this.mesh.computeWorldMatrix(true);
  67017. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  67018. }
  67019. // if the particles will always face the camera
  67020. if (this.billboard) {
  67021. // compute the camera position and un-rotate it by the current mesh rotation
  67022. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  67023. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  67024. this._cam_axisZ.normalize();
  67025. // same for camera up vector extracted from the cam view matrix
  67026. var view = this._camera.getViewMatrix(true);
  67027. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  67028. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  67029. this._cam_axisY.normalize();
  67030. this._cam_axisX.normalize();
  67031. }
  67032. // if depthSort, compute the camera global position in the mesh local system
  67033. if (this._depthSort) {
  67034. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  67035. }
  67036. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  67037. var idx = 0; // current position index in the global array positions32
  67038. var index = 0; // position start index in the global array positions32 of the current particle
  67039. var colidx = 0; // current color index in the global array colors32
  67040. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  67041. var uvidx = 0; // current uv index in the global array uvs32
  67042. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  67043. var pt = 0; // current index in the particle model shape
  67044. if (this.mesh.isFacetDataEnabled) {
  67045. this._computeBoundingBox = true;
  67046. }
  67047. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  67048. if (this._computeBoundingBox) {
  67049. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  67050. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  67051. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  67052. }
  67053. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  67054. if (this.mesh._boundingInfo) {
  67055. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  67056. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  67057. }
  67058. }
  67059. }
  67060. // particle loop
  67061. index = this.particles[start]._pos;
  67062. var vpos = (index / 3) | 0;
  67063. colorIndex = vpos * 4;
  67064. uvIndex = vpos * 2;
  67065. for (var p = start; p <= end; p++) {
  67066. this._particle = this.particles[p];
  67067. this._shape = this._particle._model._shape;
  67068. this._shapeUV = this._particle._model._shapeUV;
  67069. // call to custom user function to update the particle properties
  67070. this.updateParticle(this._particle);
  67071. // camera-particle distance for depth sorting
  67072. if (this._depthSort && this._depthSortParticles) {
  67073. var dsp = this.depthSortedParticles[p];
  67074. dsp.ind = this._particle._ind;
  67075. dsp.indicesLength = this._particle._model._indicesLength;
  67076. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  67077. }
  67078. // skip the computations for inactive or already invisible particles
  67079. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  67080. // increment indexes for the next particle
  67081. pt = this._shape.length;
  67082. index += pt * 3;
  67083. colorIndex += pt * 4;
  67084. uvIndex += pt * 2;
  67085. continue;
  67086. }
  67087. if (this._particle.isVisible) {
  67088. this._particle._stillInvisible = false; // un-mark permanent invisibility
  67089. this._particleHasParent = (this._particle.parentId !== null);
  67090. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  67091. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  67092. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  67093. // particle rotation matrix
  67094. if (this.billboard) {
  67095. this._particle.rotation.x = 0.0;
  67096. this._particle.rotation.y = 0.0;
  67097. }
  67098. if (this._computeParticleRotation || this.billboard) {
  67099. if (this._particle.rotationQuaternion) {
  67100. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  67101. }
  67102. else {
  67103. this._yaw = this._particle.rotation.y;
  67104. this._pitch = this._particle.rotation.x;
  67105. this._roll = this._particle.rotation.z;
  67106. this._quaternionRotationYPR();
  67107. }
  67108. this._quaternionToRotationMatrix();
  67109. }
  67110. if (this._particleHasParent) {
  67111. this._parent = this.particles[this._particle.parentId];
  67112. 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];
  67113. 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];
  67114. 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];
  67115. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  67116. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  67117. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  67118. if (this._computeParticleRotation || this.billboard) {
  67119. 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];
  67120. 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];
  67121. 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];
  67122. 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];
  67123. 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];
  67124. 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];
  67125. 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];
  67126. 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];
  67127. 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];
  67128. }
  67129. }
  67130. else {
  67131. this._particle._globalPosition.x = this._particle.position.x;
  67132. this._particle._globalPosition.y = this._particle.position.y;
  67133. this._particle._globalPosition.z = this._particle.position.z;
  67134. if (this._computeParticleRotation || this.billboard) {
  67135. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  67136. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  67137. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  67138. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  67139. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  67140. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  67141. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  67142. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  67143. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  67144. }
  67145. }
  67146. if (this._particle.translateFromPivot) {
  67147. this._pivotBackTranslation.x = 0.0;
  67148. this._pivotBackTranslation.y = 0.0;
  67149. this._pivotBackTranslation.z = 0.0;
  67150. }
  67151. else {
  67152. this._pivotBackTranslation.x = this._scaledPivot.x;
  67153. this._pivotBackTranslation.y = this._scaledPivot.y;
  67154. this._pivotBackTranslation.z = this._scaledPivot.z;
  67155. }
  67156. // particle vertex loop
  67157. for (pt = 0; pt < this._shape.length; pt++) {
  67158. idx = index + pt * 3;
  67159. colidx = colorIndex + pt * 4;
  67160. uvidx = uvIndex + pt * 2;
  67161. this._vertex.x = this._shape[pt].x;
  67162. this._vertex.y = this._shape[pt].y;
  67163. this._vertex.z = this._shape[pt].z;
  67164. if (this._computeParticleVertex) {
  67165. this.updateParticleVertex(this._particle, this._vertex, pt);
  67166. }
  67167. // positions
  67168. this._vertex.x *= this._particle.scaling.x;
  67169. this._vertex.y *= this._particle.scaling.y;
  67170. this._vertex.z *= this._particle.scaling.z;
  67171. this._vertex.x -= this._scaledPivot.x;
  67172. this._vertex.y -= this._scaledPivot.y;
  67173. this._vertex.z -= this._scaledPivot.z;
  67174. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67175. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67176. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67177. this._rotated.x += this._pivotBackTranslation.x;
  67178. this._rotated.y += this._pivotBackTranslation.y;
  67179. this._rotated.z += this._pivotBackTranslation.z;
  67180. 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;
  67181. 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;
  67182. 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;
  67183. if (this._computeBoundingBox) {
  67184. if (this._positions32[idx] < this._minimum.x) {
  67185. this._minimum.x = this._positions32[idx];
  67186. }
  67187. if (this._positions32[idx] > this._maximum.x) {
  67188. this._maximum.x = this._positions32[idx];
  67189. }
  67190. if (this._positions32[idx + 1] < this._minimum.y) {
  67191. this._minimum.y = this._positions32[idx + 1];
  67192. }
  67193. if (this._positions32[idx + 1] > this._maximum.y) {
  67194. this._maximum.y = this._positions32[idx + 1];
  67195. }
  67196. if (this._positions32[idx + 2] < this._minimum.z) {
  67197. this._minimum.z = this._positions32[idx + 2];
  67198. }
  67199. if (this._positions32[idx + 2] > this._maximum.z) {
  67200. this._maximum.z = this._positions32[idx + 2];
  67201. }
  67202. }
  67203. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  67204. if (!this._computeParticleVertex) {
  67205. this._normal.x = this._fixedNormal32[idx];
  67206. this._normal.y = this._fixedNormal32[idx + 1];
  67207. this._normal.z = this._fixedNormal32[idx + 2];
  67208. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  67209. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  67210. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  67211. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  67212. 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;
  67213. 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;
  67214. }
  67215. if (this._computeParticleColor && this._particle.color) {
  67216. this._colors32[colidx] = this._particle.color.r;
  67217. this._colors32[colidx + 1] = this._particle.color.g;
  67218. this._colors32[colidx + 2] = this._particle.color.b;
  67219. this._colors32[colidx + 3] = this._particle.color.a;
  67220. }
  67221. if (this._computeParticleTexture) {
  67222. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67223. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67224. }
  67225. }
  67226. }
  67227. // particle just set invisible : scaled to zero and positioned at the origin
  67228. else {
  67229. this._particle._stillInvisible = true; // mark the particle as invisible
  67230. for (pt = 0; pt < this._shape.length; pt++) {
  67231. idx = index + pt * 3;
  67232. colidx = colorIndex + pt * 4;
  67233. uvidx = uvIndex + pt * 2;
  67234. this._positions32[idx] = 0.0;
  67235. this._positions32[idx + 1] = 0.0;
  67236. this._positions32[idx + 2] = 0.0;
  67237. this._normals32[idx] = 0.0;
  67238. this._normals32[idx + 1] = 0.0;
  67239. this._normals32[idx + 2] = 0.0;
  67240. if (this._computeParticleColor && this._particle.color) {
  67241. this._colors32[colidx] = this._particle.color.r;
  67242. this._colors32[colidx + 1] = this._particle.color.g;
  67243. this._colors32[colidx + 2] = this._particle.color.b;
  67244. this._colors32[colidx + 3] = this._particle.color.a;
  67245. }
  67246. if (this._computeParticleTexture) {
  67247. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  67248. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  67249. }
  67250. }
  67251. }
  67252. // if the particle intersections must be computed : update the bbInfo
  67253. if (this._particlesIntersect) {
  67254. var bInfo = this._particle._boundingInfo;
  67255. var bBox = bInfo.boundingBox;
  67256. var bSphere = bInfo.boundingSphere;
  67257. if (!this._bSphereOnly) {
  67258. // place, scale and rotate the particle bbox within the SPS local system, then update it
  67259. for (var b = 0; b < bBox.vectors.length; b++) {
  67260. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  67261. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  67262. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  67263. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  67264. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  67265. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  67266. 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;
  67267. 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;
  67268. 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;
  67269. }
  67270. bBox._update(this.mesh._worldMatrix);
  67271. }
  67272. // place and scale the particle bouding sphere in the SPS local system, then update it
  67273. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  67274. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  67275. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  67276. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  67277. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  67278. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  67279. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  67280. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  67281. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  67282. 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));
  67283. bSphere._update(this.mesh._worldMatrix);
  67284. }
  67285. // increment indexes for the next particle
  67286. index = idx + 3;
  67287. colorIndex = colidx + 4;
  67288. uvIndex = uvidx + 2;
  67289. }
  67290. // if the VBO must be updated
  67291. if (update) {
  67292. if (this._computeParticleColor) {
  67293. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  67294. }
  67295. if (this._computeParticleTexture) {
  67296. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  67297. }
  67298. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  67299. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  67300. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  67301. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  67302. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  67303. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  67304. for (var i = 0; i < this._normals32.length; i++) {
  67305. this._fixedNormal32[i] = this._normals32[i];
  67306. }
  67307. }
  67308. if (!this.mesh.areNormalsFrozen) {
  67309. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  67310. }
  67311. }
  67312. if (this._depthSort && this._depthSortParticles) {
  67313. this.depthSortedParticles.sort(this._depthSortFunction);
  67314. var dspl = this.depthSortedParticles.length;
  67315. var sorted = 0;
  67316. var lind = 0;
  67317. var sind = 0;
  67318. var sid = 0;
  67319. for (sorted = 0; sorted < dspl; sorted++) {
  67320. lind = this.depthSortedParticles[sorted].indicesLength;
  67321. sind = this.depthSortedParticles[sorted].ind;
  67322. for (var i = 0; i < lind; i++) {
  67323. this._indices32[sid] = this._indices[sind + i];
  67324. sid++;
  67325. }
  67326. }
  67327. this.mesh.updateIndices(this._indices32);
  67328. }
  67329. }
  67330. if (this._computeBoundingBox) {
  67331. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  67332. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  67333. }
  67334. this.afterUpdateParticles(start, end, update);
  67335. return this;
  67336. };
  67337. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  67338. this._halfroll = this._roll * 0.5;
  67339. this._halfpitch = this._pitch * 0.5;
  67340. this._halfyaw = this._yaw * 0.5;
  67341. this._sinRoll = Math.sin(this._halfroll);
  67342. this._cosRoll = Math.cos(this._halfroll);
  67343. this._sinPitch = Math.sin(this._halfpitch);
  67344. this._cosPitch = Math.cos(this._halfpitch);
  67345. this._sinYaw = Math.sin(this._halfyaw);
  67346. this._cosYaw = Math.cos(this._halfyaw);
  67347. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  67348. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  67349. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  67350. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  67351. };
  67352. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  67353. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  67354. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  67355. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  67356. this._rotMatrix.m[3] = 0;
  67357. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  67358. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  67359. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  67360. this._rotMatrix.m[7] = 0;
  67361. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  67362. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  67363. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  67364. this._rotMatrix.m[11] = 0;
  67365. this._rotMatrix.m[12] = 0;
  67366. this._rotMatrix.m[13] = 0;
  67367. this._rotMatrix.m[14] = 0;
  67368. this._rotMatrix.m[15] = 1.0;
  67369. };
  67370. /**
  67371. * Disposes the SPS.
  67372. */
  67373. SolidParticleSystem.prototype.dispose = function () {
  67374. this.mesh.dispose();
  67375. this.vars = null;
  67376. // drop references to internal big arrays for the GC
  67377. this._positions = null;
  67378. this._indices = null;
  67379. this._normals = null;
  67380. this._uvs = null;
  67381. this._colors = null;
  67382. this._indices32 = null;
  67383. this._positions32 = null;
  67384. this._normals32 = null;
  67385. this._fixedNormal32 = null;
  67386. this._uvs32 = null;
  67387. this._colors32 = null;
  67388. this.pickedParticles = null;
  67389. };
  67390. /**
  67391. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  67392. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67393. * @returns the SPS.
  67394. */
  67395. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  67396. if (!this._isVisibilityBoxLocked) {
  67397. this.mesh.refreshBoundingInfo();
  67398. }
  67399. return this;
  67400. };
  67401. /**
  67402. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  67403. * @param size the size (float) of the visibility box
  67404. * note : this doesn't lock the SPS mesh bounding box.
  67405. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67406. */
  67407. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  67408. var vis = size / 2;
  67409. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  67410. };
  67411. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  67412. /**
  67413. * Gets whether the SPS as always visible or not
  67414. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67415. */
  67416. get: function () {
  67417. return this._alwaysVisible;
  67418. },
  67419. /**
  67420. * Sets the SPS as always visible or not
  67421. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67422. */
  67423. set: function (val) {
  67424. this._alwaysVisible = val;
  67425. this.mesh.alwaysSelectAsActiveMesh = val;
  67426. },
  67427. enumerable: true,
  67428. configurable: true
  67429. });
  67430. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  67431. /**
  67432. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67433. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67434. */
  67435. get: function () {
  67436. return this._isVisibilityBoxLocked;
  67437. },
  67438. /**
  67439. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  67440. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  67441. */
  67442. set: function (val) {
  67443. this._isVisibilityBoxLocked = val;
  67444. var boundingInfo = this.mesh.getBoundingInfo();
  67445. boundingInfo.isLocked = val;
  67446. },
  67447. enumerable: true,
  67448. configurable: true
  67449. });
  67450. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  67451. /**
  67452. * Gets if `setParticles()` computes the particle rotations or not.
  67453. * Default value : true. The SPS is faster when it's set to false.
  67454. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67455. */
  67456. get: function () {
  67457. return this._computeParticleRotation;
  67458. },
  67459. /**
  67460. * Tells to `setParticles()` to compute the particle rotations or not.
  67461. * Default value : true. The SPS is faster when it's set to false.
  67462. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  67463. */
  67464. set: function (val) {
  67465. this._computeParticleRotation = val;
  67466. },
  67467. enumerable: true,
  67468. configurable: true
  67469. });
  67470. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  67471. /**
  67472. * Gets if `setParticles()` computes the particle colors or not.
  67473. * Default value : true. The SPS is faster when it's set to false.
  67474. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67475. */
  67476. get: function () {
  67477. return this._computeParticleColor;
  67478. },
  67479. /**
  67480. * Tells to `setParticles()` to compute the particle colors or not.
  67481. * Default value : true. The SPS is faster when it's set to false.
  67482. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  67483. */
  67484. set: function (val) {
  67485. this._computeParticleColor = val;
  67486. },
  67487. enumerable: true,
  67488. configurable: true
  67489. });
  67490. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  67491. /**
  67492. * Gets if `setParticles()` computes the particle textures or not.
  67493. * Default value : true. The SPS is faster when it's set to false.
  67494. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  67495. */
  67496. get: function () {
  67497. return this._computeParticleTexture;
  67498. },
  67499. set: function (val) {
  67500. this._computeParticleTexture = val;
  67501. },
  67502. enumerable: true,
  67503. configurable: true
  67504. });
  67505. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  67506. /**
  67507. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  67508. * Default value : false. The SPS is faster when it's set to false.
  67509. * Note : the particle custom vertex positions aren't stored values.
  67510. */
  67511. get: function () {
  67512. return this._computeParticleVertex;
  67513. },
  67514. /**
  67515. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  67516. * Default value : false. The SPS is faster when it's set to false.
  67517. * Note : the particle custom vertex positions aren't stored values.
  67518. */
  67519. set: function (val) {
  67520. this._computeParticleVertex = val;
  67521. },
  67522. enumerable: true,
  67523. configurable: true
  67524. });
  67525. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  67526. /**
  67527. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  67528. */
  67529. get: function () {
  67530. return this._computeBoundingBox;
  67531. },
  67532. /**
  67533. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  67534. */
  67535. set: function (val) {
  67536. this._computeBoundingBox = val;
  67537. },
  67538. enumerable: true,
  67539. configurable: true
  67540. });
  67541. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  67542. /**
  67543. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  67544. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67545. * Default : `true`
  67546. */
  67547. get: function () {
  67548. return this._depthSortParticles;
  67549. },
  67550. /**
  67551. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  67552. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  67553. * Default : `true`
  67554. */
  67555. set: function (val) {
  67556. this._depthSortParticles = val;
  67557. },
  67558. enumerable: true,
  67559. configurable: true
  67560. });
  67561. // =======================================================================
  67562. // Particle behavior logic
  67563. // these following methods may be overwritten by the user to fit his needs
  67564. /**
  67565. * This function does nothing. It may be overwritten to set all the particle first values.
  67566. * The SPS doesn't call this function, you may have to call it by your own.
  67567. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67568. */
  67569. SolidParticleSystem.prototype.initParticles = function () {
  67570. };
  67571. /**
  67572. * This function does nothing. It may be overwritten to recycle a particle.
  67573. * The SPS doesn't call this function, you may have to call it by your own.
  67574. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67575. * @param particle The particle to recycle
  67576. * @returns the recycled particle
  67577. */
  67578. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  67579. return particle;
  67580. };
  67581. /**
  67582. * Updates a particle : this function should be overwritten by the user.
  67583. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  67584. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  67585. * @example : just set a particle position or velocity and recycle conditions
  67586. * @param particle The particle to update
  67587. * @returns the updated particle
  67588. */
  67589. SolidParticleSystem.prototype.updateParticle = function (particle) {
  67590. return particle;
  67591. };
  67592. /**
  67593. * Updates a vertex of a particle : it can be overwritten by the user.
  67594. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  67595. * @param particle the current particle
  67596. * @param vertex the current index of the current particle
  67597. * @param pt the index of the current vertex in the particle shape
  67598. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  67599. * @example : just set a vertex particle position
  67600. * @returns the updated vertex
  67601. */
  67602. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  67603. return vertex;
  67604. };
  67605. /**
  67606. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  67607. * This does nothing and may be overwritten by the user.
  67608. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67609. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67610. * @param update the boolean update value actually passed to setParticles()
  67611. */
  67612. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  67613. };
  67614. /**
  67615. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  67616. * This will be passed three parameters.
  67617. * This does nothing and may be overwritten by the user.
  67618. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67619. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  67620. * @param update the boolean update value actually passed to setParticles()
  67621. */
  67622. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  67623. };
  67624. return SolidParticleSystem;
  67625. }());
  67626. BABYLON.SolidParticleSystem = SolidParticleSystem;
  67627. })(BABYLON || (BABYLON = {}));
  67628. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  67629. var BABYLON;
  67630. (function (BABYLON) {
  67631. /**
  67632. * Class containing static functions to help procedurally build meshes
  67633. */
  67634. var MeshBuilder = /** @class */ (function () {
  67635. function MeshBuilder() {
  67636. }
  67637. MeshBuilder.updateSideOrientation = function (orientation) {
  67638. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  67639. return BABYLON.Mesh.DOUBLESIDE;
  67640. }
  67641. if (orientation === undefined || orientation === null) {
  67642. return BABYLON.Mesh.FRONTSIDE;
  67643. }
  67644. return orientation;
  67645. };
  67646. /**
  67647. * Creates a box mesh
  67648. * * The parameter `size` sets the size (float) of each box side (default 1)
  67649. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value of `size`)
  67650. * * 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)
  67651. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  67652. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67653. * * 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
  67654. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67655. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  67656. * @param name defines the name of the mesh
  67657. * @param options defines the options used to create the mesh
  67658. * @param scene defines the hosting scene
  67659. * @returns the box mesh
  67660. */
  67661. MeshBuilder.CreateBox = function (name, options, scene) {
  67662. if (scene === void 0) { scene = null; }
  67663. var box = new BABYLON.Mesh(name, scene);
  67664. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67665. box._originalBuilderSideOrientation = options.sideOrientation;
  67666. var vertexData = BABYLON.VertexData.CreateBox(options);
  67667. vertexData.applyToMesh(box, options.updatable);
  67668. return box;
  67669. };
  67670. /**
  67671. * Creates a sphere mesh
  67672. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  67673. * * 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`)
  67674. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  67675. * * 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
  67676. * * 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)
  67677. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67678. * * 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
  67679. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67680. * @param name defines the name of the mesh
  67681. * @param options defines the options used to create the mesh
  67682. * @param scene defines the hosting scene
  67683. * @returns the sphere mesh
  67684. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  67685. */
  67686. MeshBuilder.CreateSphere = function (name, options, scene) {
  67687. var sphere = new BABYLON.Mesh(name, scene);
  67688. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67689. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67690. var vertexData = BABYLON.VertexData.CreateSphere(options);
  67691. vertexData.applyToMesh(sphere, options.updatable);
  67692. return sphere;
  67693. };
  67694. /**
  67695. * Creates a plane polygonal mesh. By default, this is a disc
  67696. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  67697. * * 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
  67698. * * 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
  67699. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67700. * * 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
  67701. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67702. * @param name defines the name of the mesh
  67703. * @param options defines the options used to create the mesh
  67704. * @param scene defines the hosting scene
  67705. * @returns the plane polygonal mesh
  67706. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  67707. */
  67708. MeshBuilder.CreateDisc = function (name, options, scene) {
  67709. if (scene === void 0) { scene = null; }
  67710. var disc = new BABYLON.Mesh(name, scene);
  67711. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67712. disc._originalBuilderSideOrientation = options.sideOrientation;
  67713. var vertexData = BABYLON.VertexData.CreateDisc(options);
  67714. vertexData.applyToMesh(disc, options.updatable);
  67715. return disc;
  67716. };
  67717. /**
  67718. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  67719. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  67720. * * 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`)
  67721. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  67722. * * 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
  67723. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67724. * * 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
  67725. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67726. * @param name defines the name of the mesh
  67727. * @param options defines the options used to create the mesh
  67728. * @param scene defines the hosting scene
  67729. * @returns the icosahedron mesh
  67730. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  67731. */
  67732. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  67733. var sphere = new BABYLON.Mesh(name, scene);
  67734. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67735. sphere._originalBuilderSideOrientation = options.sideOrientation;
  67736. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  67737. vertexData.applyToMesh(sphere, options.updatable);
  67738. return sphere;
  67739. };
  67740. ;
  67741. /**
  67742. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  67743. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  67744. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  67745. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  67746. * * 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
  67747. * * 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
  67748. * * 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
  67749. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67750. * * 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
  67751. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  67752. * * 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
  67753. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  67754. * * 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
  67755. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  67756. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67757. * @param name defines the name of the mesh
  67758. * @param options defines the options used to create the mesh
  67759. * @param scene defines the hosting scene
  67760. * @returns the ribbon mesh
  67761. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  67762. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  67763. */
  67764. MeshBuilder.CreateRibbon = function (name, options, scene) {
  67765. if (scene === void 0) { scene = null; }
  67766. var pathArray = options.pathArray;
  67767. var closeArray = options.closeArray;
  67768. var closePath = options.closePath;
  67769. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67770. var instance = options.instance;
  67771. var updatable = options.updatable;
  67772. if (instance) { // existing ribbon instance update
  67773. // positionFunction : ribbon case
  67774. // only pathArray and sideOrientation parameters are taken into account for positions update
  67775. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  67776. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  67777. var positionFunction = function (positions) {
  67778. var minlg = pathArray[0].length;
  67779. var mesh = instance;
  67780. var i = 0;
  67781. var ns = (mesh._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  67782. for (var si = 1; si <= ns; si++) {
  67783. for (var p = 0; p < pathArray.length; p++) {
  67784. var path = pathArray[p];
  67785. var l = path.length;
  67786. minlg = (minlg < l) ? minlg : l;
  67787. var j = 0;
  67788. while (j < minlg) {
  67789. positions[i] = path[j].x;
  67790. positions[i + 1] = path[j].y;
  67791. positions[i + 2] = path[j].z;
  67792. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  67793. BABYLON.Tmp.Vector3[0].x = path[j].x;
  67794. }
  67795. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  67796. BABYLON.Tmp.Vector3[1].x = path[j].x;
  67797. }
  67798. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  67799. BABYLON.Tmp.Vector3[0].y = path[j].y;
  67800. }
  67801. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  67802. BABYLON.Tmp.Vector3[1].y = path[j].y;
  67803. }
  67804. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  67805. BABYLON.Tmp.Vector3[0].z = path[j].z;
  67806. }
  67807. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  67808. BABYLON.Tmp.Vector3[1].z = path[j].z;
  67809. }
  67810. j++;
  67811. i += 3;
  67812. }
  67813. if (mesh._creationDataStorage && mesh._creationDataStorage.closePath) {
  67814. positions[i] = path[0].x;
  67815. positions[i + 1] = path[0].y;
  67816. positions[i + 2] = path[0].z;
  67817. i += 3;
  67818. }
  67819. }
  67820. }
  67821. };
  67822. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67823. positionFunction(positions);
  67824. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[2], BABYLON.Tmp.Vector3[3]);
  67825. instance._boundingInfo.update(instance._worldMatrix);
  67826. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  67827. if (options.colors) {
  67828. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67829. for (var c = 0; c < options.colors.length; c++) {
  67830. colors[c * 4] = options.colors[c].r;
  67831. colors[c * 4 + 1] = options.colors[c].g;
  67832. colors[c * 4 + 2] = options.colors[c].b;
  67833. colors[c * 4 + 3] = options.colors[c].a;
  67834. }
  67835. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  67836. }
  67837. if (options.uvs) {
  67838. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  67839. for (var i = 0; i < options.uvs.length; i++) {
  67840. uvs[i * 2] = options.uvs[i].x;
  67841. uvs[i * 2 + 1] = options.uvs[i].y;
  67842. }
  67843. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  67844. }
  67845. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  67846. var indices = instance.getIndices();
  67847. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  67848. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  67849. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  67850. if (instance._creationDataStorage && instance._creationDataStorage.closePath) {
  67851. var indexFirst = 0;
  67852. var indexLast = 0;
  67853. for (var p = 0; p < pathArray.length; p++) {
  67854. indexFirst = instance._creationDataStorage.idx[p] * 3;
  67855. if (p + 1 < pathArray.length) {
  67856. indexLast = (instance._creationDataStorage.idx[p + 1] - 1) * 3;
  67857. }
  67858. else {
  67859. indexLast = normals.length - 3;
  67860. }
  67861. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  67862. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  67863. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  67864. normals[indexLast] = normals[indexFirst];
  67865. normals[indexLast + 1] = normals[indexFirst + 1];
  67866. normals[indexLast + 2] = normals[indexFirst + 2];
  67867. }
  67868. }
  67869. if (!(instance.areNormalsFrozen)) {
  67870. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  67871. }
  67872. }
  67873. return instance;
  67874. }
  67875. else { // new ribbon creation
  67876. var ribbon = new BABYLON.Mesh(name, scene);
  67877. ribbon._originalBuilderSideOrientation = sideOrientation;
  67878. ribbon._creationDataStorage = new BABYLON._CreationDataStorage();
  67879. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  67880. if (closePath) {
  67881. ribbon._creationDataStorage.idx = vertexData._idx;
  67882. }
  67883. ribbon._creationDataStorage.closePath = closePath;
  67884. ribbon._creationDataStorage.closeArray = closeArray;
  67885. vertexData.applyToMesh(ribbon, updatable);
  67886. return ribbon;
  67887. }
  67888. };
  67889. /**
  67890. * Creates a cylinder or a cone mesh
  67891. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  67892. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  67893. * * 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.
  67894. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  67895. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  67896. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  67897. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  67898. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  67899. * * 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).
  67900. * * 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
  67901. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  67902. * * 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
  67903. * * 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.
  67904. * * If `enclose` is false, a ring surface is one element.
  67905. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  67906. * * 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
  67907. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67908. * * 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
  67909. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67910. * @param name defines the name of the mesh
  67911. * @param options defines the options used to create the mesh
  67912. * @param scene defines the hosting scene
  67913. * @returns the cylinder mesh
  67914. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  67915. */
  67916. MeshBuilder.CreateCylinder = function (name, options, scene) {
  67917. var cylinder = new BABYLON.Mesh(name, scene);
  67918. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67919. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  67920. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  67921. vertexData.applyToMesh(cylinder, options.updatable);
  67922. return cylinder;
  67923. };
  67924. /**
  67925. * Creates a torus mesh
  67926. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  67927. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  67928. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  67929. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67930. * * 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
  67931. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67932. * @param name defines the name of the mesh
  67933. * @param options defines the options used to create the mesh
  67934. * @param scene defines the hosting scene
  67935. * @returns the torus mesh
  67936. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  67937. */
  67938. MeshBuilder.CreateTorus = function (name, options, scene) {
  67939. var torus = new BABYLON.Mesh(name, scene);
  67940. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67941. torus._originalBuilderSideOrientation = options.sideOrientation;
  67942. var vertexData = BABYLON.VertexData.CreateTorus(options);
  67943. vertexData.applyToMesh(torus, options.updatable);
  67944. return torus;
  67945. };
  67946. /**
  67947. * Creates a torus knot mesh
  67948. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  67949. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  67950. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  67951. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  67952. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  67953. * * 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
  67954. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  67955. * @param name defines the name of the mesh
  67956. * @param options defines the options used to create the mesh
  67957. * @param scene defines the hosting scene
  67958. * @returns the torus knot mesh
  67959. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  67960. */
  67961. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  67962. var torusKnot = new BABYLON.Mesh(name, scene);
  67963. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  67964. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  67965. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  67966. vertexData.applyToMesh(torusKnot, options.updatable);
  67967. return torusKnot;
  67968. };
  67969. /**
  67970. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  67971. * * 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
  67972. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  67973. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  67974. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  67975. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  67976. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  67977. * * 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
  67978. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  67979. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  67980. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  67981. * @param name defines the name of the new line system
  67982. * @param options defines the options used to create the line system
  67983. * @param scene defines the hosting scene
  67984. * @returns a new line system mesh
  67985. */
  67986. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  67987. var instance = options.instance;
  67988. var lines = options.lines;
  67989. var colors = options.colors;
  67990. if (instance) { // lines update
  67991. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67992. var vertexColor;
  67993. var lineColors;
  67994. if (colors) {
  67995. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  67996. }
  67997. var i = 0;
  67998. var c = 0;
  67999. for (var l = 0; l < lines.length; l++) {
  68000. var points = lines[l];
  68001. for (var p = 0; p < points.length; p++) {
  68002. positions[i] = points[p].x;
  68003. positions[i + 1] = points[p].y;
  68004. positions[i + 2] = points[p].z;
  68005. if (colors && vertexColor) {
  68006. lineColors = colors[l];
  68007. vertexColor[c] = lineColors[p].r;
  68008. vertexColor[c + 1] = lineColors[p].g;
  68009. vertexColor[c + 2] = lineColors[p].b;
  68010. vertexColor[c + 3] = lineColors[p].a;
  68011. c += 4;
  68012. }
  68013. i += 3;
  68014. }
  68015. }
  68016. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  68017. if (colors && vertexColor) {
  68018. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  68019. }
  68020. return instance;
  68021. }
  68022. // line system creation
  68023. var useVertexColor = (colors) ? true : false;
  68024. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  68025. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  68026. vertexData.applyToMesh(lineSystem, options.updatable);
  68027. return lineSystem;
  68028. };
  68029. /**
  68030. * Creates a line mesh
  68031. * 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
  68032. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68033. * * The parameter `points` is an array successive Vector3
  68034. * * 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
  68035. * * The optional parameter `colors` is an array of successive Color4, one per line point
  68036. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  68037. * * When updating an instance, remember that only point positions can change, not the number of points
  68038. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68039. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  68040. * @param name defines the name of the new line system
  68041. * @param options defines the options used to create the line system
  68042. * @param scene defines the hosting scene
  68043. * @returns a new line mesh
  68044. */
  68045. MeshBuilder.CreateLines = function (name, options, scene) {
  68046. if (scene === void 0) { scene = null; }
  68047. var colors = (options.colors) ? [options.colors] : null;
  68048. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  68049. return lines;
  68050. };
  68051. /**
  68052. * Creates a dashed line mesh
  68053. * * 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
  68054. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  68055. * * The parameter `points` is an array successive Vector3
  68056. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  68057. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  68058. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  68059. * * 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
  68060. * * When updating an instance, remember that only point positions can change, not the number of points
  68061. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68062. * @param name defines the name of the mesh
  68063. * @param options defines the options used to create the mesh
  68064. * @param scene defines the hosting scene
  68065. * @returns the dashed line mesh
  68066. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  68067. */
  68068. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  68069. if (scene === void 0) { scene = null; }
  68070. var points = options.points;
  68071. var instance = options.instance;
  68072. var gapSize = options.gapSize || 1;
  68073. var dashSize = options.dashSize || 3;
  68074. if (instance) { // dashed lines update
  68075. var positionFunction = function (positions) {
  68076. var curvect = BABYLON.Vector3.Zero();
  68077. var nbSeg = positions.length / 6;
  68078. var lg = 0;
  68079. var nb = 0;
  68080. var shft = 0;
  68081. var dashshft = 0;
  68082. var curshft = 0;
  68083. var p = 0;
  68084. var i = 0;
  68085. var j = 0;
  68086. for (i = 0; i < points.length - 1; i++) {
  68087. points[i + 1].subtractToRef(points[i], curvect);
  68088. lg += curvect.length();
  68089. }
  68090. shft = lg / nbSeg;
  68091. var dashSize = instance._creationDataStorage.dashSize;
  68092. var gapSize = instance._creationDataStorage.gapSize;
  68093. dashshft = dashSize * shft / (dashSize + gapSize);
  68094. for (i = 0; i < points.length - 1; i++) {
  68095. points[i + 1].subtractToRef(points[i], curvect);
  68096. nb = Math.floor(curvect.length() / shft);
  68097. curvect.normalize();
  68098. j = 0;
  68099. while (j < nb && p < positions.length) {
  68100. curshft = shft * j;
  68101. positions[p] = points[i].x + curshft * curvect.x;
  68102. positions[p + 1] = points[i].y + curshft * curvect.y;
  68103. positions[p + 2] = points[i].z + curshft * curvect.z;
  68104. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  68105. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  68106. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  68107. p += 6;
  68108. j++;
  68109. }
  68110. }
  68111. while (p < positions.length) {
  68112. positions[p] = points[i].x;
  68113. positions[p + 1] = points[i].y;
  68114. positions[p + 2] = points[i].z;
  68115. p += 3;
  68116. }
  68117. };
  68118. instance.updateMeshPositions(positionFunction, false);
  68119. return instance;
  68120. }
  68121. // dashed lines creation
  68122. var dashedLines = new BABYLON.LinesMesh(name, scene);
  68123. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  68124. vertexData.applyToMesh(dashedLines, options.updatable);
  68125. dashedLines._creationDataStorage = new BABYLON._CreationDataStorage();
  68126. dashedLines._creationDataStorage.dashSize = dashSize;
  68127. dashedLines._creationDataStorage.gapSize = gapSize;
  68128. return dashedLines;
  68129. };
  68130. /**
  68131. * 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.
  68132. * * 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.
  68133. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68134. * * 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.
  68135. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  68136. * * 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
  68137. * * 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
  68138. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  68139. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68140. * * 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
  68141. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  68142. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68143. * @param name defines the name of the mesh
  68144. * @param options defines the options used to create the mesh
  68145. * @param scene defines the hosting scene
  68146. * @returns the extruded shape mesh
  68147. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68148. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68149. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68150. */
  68151. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  68152. if (scene === void 0) { scene = null; }
  68153. var path = options.path;
  68154. var shape = options.shape;
  68155. var scale = options.scale || 1;
  68156. var rotation = options.rotation || 0;
  68157. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68158. var updatable = options.updatable;
  68159. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68160. var instance = options.instance || null;
  68161. var invertUV = options.invertUV || false;
  68162. 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);
  68163. };
  68164. /**
  68165. * Creates an custom extruded shape mesh.
  68166. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  68167. * * 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.
  68168. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  68169. * * 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
  68170. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  68171. * * 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
  68172. * * It must returns a float value that will be the scale value applied to the shape on each path point
  68173. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  68174. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  68175. * * 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
  68176. * * 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
  68177. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  68178. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68179. * * 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
  68180. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68181. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68182. * @param name defines the name of the mesh
  68183. * @param options defines the options used to create the mesh
  68184. * @param scene defines the hosting scene
  68185. * @returns the custom extruded shape mesh
  68186. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  68187. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68188. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  68189. */
  68190. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  68191. var path = options.path;
  68192. var shape = options.shape;
  68193. var scaleFunction = options.scaleFunction || (function () { return 1; });
  68194. var rotationFunction = options.rotationFunction || (function () { return 0; });
  68195. var ribbonCloseArray = options.ribbonCloseArray || false;
  68196. var ribbonClosePath = options.ribbonClosePath || false;
  68197. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  68198. var updatable = options.updatable;
  68199. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68200. var instance = options.instance;
  68201. var invertUV = options.invertUV || false;
  68202. 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);
  68203. };
  68204. /**
  68205. * Creates lathe mesh.
  68206. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  68207. * * 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
  68208. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  68209. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  68210. * * The parameter `clip` (positive integer, default 0) is the number of sides to not create without effecting the general shape of the sides
  68211. * * 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
  68212. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  68213. * * 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
  68214. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68215. * * 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
  68216. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68217. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68218. * @param name defines the name of the mesh
  68219. * @param options defines the options used to create the mesh
  68220. * @param scene defines the hosting scene
  68221. * @returns the lathe mesh
  68222. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  68223. */
  68224. MeshBuilder.CreateLathe = function (name, options, scene) {
  68225. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  68226. var closed = (options.closed === undefined) ? true : options.closed;
  68227. var shape = options.shape;
  68228. var radius = options.radius || 1;
  68229. var tessellation = options.tessellation || 64;
  68230. var clip = options.clip || 0;
  68231. var updatable = options.updatable;
  68232. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68233. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68234. var pi2 = Math.PI * 2;
  68235. var paths = new Array();
  68236. var invertUV = options.invertUV || false;
  68237. var i = 0;
  68238. var p = 0;
  68239. var step = pi2 / tessellation * arc;
  68240. var rotated;
  68241. var path = new Array();
  68242. for (i = 0; i <= tessellation - clip; i++) {
  68243. var path = [];
  68244. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  68245. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  68246. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  68247. }
  68248. for (p = 0; p < shape.length; p++) {
  68249. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  68250. path.push(rotated);
  68251. }
  68252. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  68253. 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));
  68254. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  68255. }
  68256. paths.push(path);
  68257. }
  68258. // lathe ribbon
  68259. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68260. return lathe;
  68261. };
  68262. /**
  68263. * Creates a plane mesh
  68264. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  68265. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value of `size`)
  68266. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  68267. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68268. * * 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
  68269. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68270. * @param name defines the name of the mesh
  68271. * @param options defines the options used to create the mesh
  68272. * @param scene defines the hosting scene
  68273. * @returns the plane mesh
  68274. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68275. */
  68276. MeshBuilder.CreatePlane = function (name, options, scene) {
  68277. var plane = new BABYLON.Mesh(name, scene);
  68278. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68279. plane._originalBuilderSideOrientation = options.sideOrientation;
  68280. var vertexData = BABYLON.VertexData.CreatePlane(options);
  68281. vertexData.applyToMesh(plane, options.updatable);
  68282. if (options.sourcePlane) {
  68283. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  68284. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  68285. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  68286. if (vectorProduct.lengthSquared() > BABYLON.Epsilon) {
  68287. plane.rotate(vectorProduct, product);
  68288. }
  68289. }
  68290. return plane;
  68291. };
  68292. /**
  68293. * Creates a ground mesh
  68294. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  68295. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  68296. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68297. * @param name defines the name of the mesh
  68298. * @param options defines the options used to create the mesh
  68299. * @param scene defines the hosting scene
  68300. * @returns the ground mesh
  68301. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  68302. */
  68303. MeshBuilder.CreateGround = function (name, options, scene) {
  68304. var ground = new BABYLON.GroundMesh(name, scene);
  68305. ground._setReady(false);
  68306. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  68307. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  68308. ground._width = options.width || 1;
  68309. ground._height = options.height || 1;
  68310. ground._maxX = ground._width / 2;
  68311. ground._maxZ = ground._height / 2;
  68312. ground._minX = -ground._maxX;
  68313. ground._minZ = -ground._maxZ;
  68314. var vertexData = BABYLON.VertexData.CreateGround(options);
  68315. vertexData.applyToMesh(ground, options.updatable);
  68316. ground._setReady(true);
  68317. return ground;
  68318. };
  68319. /**
  68320. * Creates a tiled ground mesh
  68321. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  68322. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  68323. * * 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
  68324. * * 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
  68325. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68326. * @param name defines the name of the mesh
  68327. * @param options defines the options used to create the mesh
  68328. * @param scene defines the hosting scene
  68329. * @returns the tiled ground mesh
  68330. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  68331. */
  68332. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  68333. var tiledGround = new BABYLON.Mesh(name, scene);
  68334. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  68335. vertexData.applyToMesh(tiledGround, options.updatable);
  68336. return tiledGround;
  68337. };
  68338. /**
  68339. * Creates a ground mesh from a height map
  68340. * * The parameter `url` sets the URL of the height map image resource.
  68341. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  68342. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  68343. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  68344. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  68345. * * 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.
  68346. * * 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).
  68347. * * The parameter `alphaFilter` will filter any data where the alpha channel is below this value, defaults 0 (all data visible)
  68348. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  68349. * @param name defines the name of the mesh
  68350. * @param url defines the url to the height map
  68351. * @param options defines the options used to create the mesh
  68352. * @param scene defines the hosting scene
  68353. * @returns the ground mesh
  68354. * @see http://doc.babylonjs.com/babylon101/height_map
  68355. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  68356. */
  68357. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  68358. var width = options.width || 10.0;
  68359. var height = options.height || 10.0;
  68360. var subdivisions = options.subdivisions || 1 | 0;
  68361. var minHeight = options.minHeight || 0.0;
  68362. var maxHeight = options.maxHeight || 1.0;
  68363. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  68364. var alphaFilter = options.alphaFilter || 0.0;
  68365. var updatable = options.updatable;
  68366. var onReady = options.onReady;
  68367. var ground = new BABYLON.GroundMesh(name, scene);
  68368. ground._subdivisionsX = subdivisions;
  68369. ground._subdivisionsY = subdivisions;
  68370. ground._width = width;
  68371. ground._height = height;
  68372. ground._maxX = ground._width / 2.0;
  68373. ground._maxZ = ground._height / 2.0;
  68374. ground._minX = -ground._maxX;
  68375. ground._minZ = -ground._maxZ;
  68376. ground._setReady(false);
  68377. var onload = function (img) {
  68378. // Getting height map data
  68379. var canvas = document.createElement("canvas");
  68380. var context = canvas.getContext("2d");
  68381. if (!context) {
  68382. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  68383. }
  68384. if (scene.isDisposed) {
  68385. return;
  68386. }
  68387. var bufferWidth = img.width;
  68388. var bufferHeight = img.height;
  68389. canvas.width = bufferWidth;
  68390. canvas.height = bufferHeight;
  68391. context.drawImage(img, 0, 0);
  68392. // Create VertexData from map data
  68393. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  68394. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  68395. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  68396. width: width, height: height,
  68397. subdivisions: subdivisions,
  68398. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  68399. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight,
  68400. alphaFilter: alphaFilter
  68401. });
  68402. vertexData.applyToMesh(ground, updatable);
  68403. //execute ready callback, if set
  68404. if (onReady) {
  68405. onReady(ground);
  68406. }
  68407. ground._setReady(true);
  68408. };
  68409. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  68410. return ground;
  68411. };
  68412. /**
  68413. * Creates a polygon mesh
  68414. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  68415. * * 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
  68416. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68417. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68418. * * 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)
  68419. * * Remember you can only change the shape positions, not their number when updating a polygon
  68420. * @param name defines the name of the mesh
  68421. * @param options defines the options used to create the mesh
  68422. * @param scene defines the hosting scene
  68423. * @returns the polygon mesh
  68424. */
  68425. MeshBuilder.CreatePolygon = function (name, options, scene) {
  68426. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68427. var shape = options.shape;
  68428. var holes = options.holes || [];
  68429. var depth = options.depth || 0;
  68430. var contours = [];
  68431. var hole = [];
  68432. for (var i = 0; i < shape.length; i++) {
  68433. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  68434. }
  68435. var epsilon = 0.00000001;
  68436. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  68437. contours.pop();
  68438. }
  68439. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  68440. for (var hNb = 0; hNb < holes.length; hNb++) {
  68441. hole = [];
  68442. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  68443. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  68444. }
  68445. polygonTriangulation.addHole(hole);
  68446. }
  68447. var polygon = polygonTriangulation.build(options.updatable, depth);
  68448. polygon._originalBuilderSideOrientation = options.sideOrientation;
  68449. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  68450. vertexData.applyToMesh(polygon, options.updatable);
  68451. return polygon;
  68452. };
  68453. ;
  68454. /**
  68455. * Creates an extruded polygon mesh, with depth in the Y direction.
  68456. * * 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)
  68457. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  68458. * @param name defines the name of the mesh
  68459. * @param options defines the options used to create the mesh
  68460. * @param scene defines the hosting scene
  68461. * @returns the polygon mesh
  68462. */
  68463. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  68464. return MeshBuilder.CreatePolygon(name, options, scene);
  68465. };
  68466. ;
  68467. /**
  68468. * Creates a tube mesh.
  68469. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  68470. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  68471. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  68472. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  68473. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  68474. * * 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)
  68475. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  68476. * * 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
  68477. * * 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
  68478. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68479. * * 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
  68480. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  68481. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68482. * @param name defines the name of the mesh
  68483. * @param options defines the options used to create the mesh
  68484. * @param scene defines the hosting scene
  68485. * @returns the tube mesh
  68486. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  68487. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  68488. */
  68489. MeshBuilder.CreateTube = function (name, options, scene) {
  68490. var path = options.path;
  68491. var instance = options.instance;
  68492. var radius = 1.0;
  68493. if (options.radius !== undefined) {
  68494. radius = options.radius;
  68495. }
  68496. else if (instance) {
  68497. radius = instance._creationDataStorage.radius;
  68498. }
  68499. var tessellation = options.tessellation || 64 | 0;
  68500. var radiusFunction = options.radiusFunction || null;
  68501. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  68502. var invertUV = options.invertUV || false;
  68503. var updatable = options.updatable;
  68504. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68505. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  68506. // tube geometry
  68507. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  68508. var tangents = path3D.getTangents();
  68509. var normals = path3D.getNormals();
  68510. var distances = path3D.getDistances();
  68511. var pi2 = Math.PI * 2;
  68512. var step = pi2 / tessellation * arc;
  68513. var returnRadius = function () { return radius; };
  68514. var radiusFunctionFinal = radiusFunction || returnRadius;
  68515. var circlePath;
  68516. var rad;
  68517. var normal;
  68518. var rotated;
  68519. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68520. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68521. for (var i = 0; i < path.length; i++) {
  68522. rad = radiusFunctionFinal(i, distances[i]); // current radius
  68523. circlePath = Array(); // current circle array
  68524. normal = normals[i]; // current normal
  68525. for (var t = 0; t < tessellation; t++) {
  68526. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  68527. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  68528. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  68529. rotated.scaleInPlace(rad).addInPlace(path[i]);
  68530. circlePath[t] = rotated;
  68531. }
  68532. circlePaths[index] = circlePath;
  68533. index++;
  68534. }
  68535. // cap
  68536. var capPath = function (nbPoints, pathIndex) {
  68537. var pointCap = Array();
  68538. for (var i = 0; i < nbPoints; i++) {
  68539. pointCap.push(path[pathIndex]);
  68540. }
  68541. return pointCap;
  68542. };
  68543. switch (cap) {
  68544. case BABYLON.Mesh.NO_CAP:
  68545. break;
  68546. case BABYLON.Mesh.CAP_START:
  68547. circlePaths[0] = capPath(tessellation, 0);
  68548. circlePaths[1] = circlePaths[2].slice(0);
  68549. break;
  68550. case BABYLON.Mesh.CAP_END:
  68551. circlePaths[index] = circlePaths[index - 1].slice(0);
  68552. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68553. break;
  68554. case BABYLON.Mesh.CAP_ALL:
  68555. circlePaths[0] = capPath(tessellation, 0);
  68556. circlePaths[1] = circlePaths[2].slice(0);
  68557. circlePaths[index] = circlePaths[index - 1].slice(0);
  68558. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  68559. break;
  68560. default:
  68561. break;
  68562. }
  68563. return circlePaths;
  68564. };
  68565. var path3D;
  68566. var pathArray;
  68567. if (instance) { // tube update
  68568. var storage = instance._creationDataStorage;
  68569. var arc = options.arc || storage.arc;
  68570. path3D = storage.path3D.update(path);
  68571. pathArray = tubePathArray(path, path3D, storage.pathArray, radius, storage.tessellation, radiusFunction, storage.cap, arc);
  68572. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  68573. // Update mode, no need to recreate the storage.
  68574. storage.path3D = path3D;
  68575. storage.pathArray = pathArray;
  68576. storage.arc = arc;
  68577. storage.radius = radius;
  68578. return instance;
  68579. }
  68580. // tube creation
  68581. path3D = new BABYLON.Path3D(path);
  68582. var newPathArray = new Array();
  68583. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68584. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  68585. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  68586. tube._creationDataStorage.pathArray = pathArray;
  68587. tube._creationDataStorage.path3D = path3D;
  68588. tube._creationDataStorage.tessellation = tessellation;
  68589. tube._creationDataStorage.cap = cap;
  68590. tube._creationDataStorage.arc = options.arc;
  68591. tube._creationDataStorage.radius = radius;
  68592. return tube;
  68593. };
  68594. /**
  68595. * Creates a polyhedron mesh
  68596. * * 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
  68597. * * The parameter `size` (positive float, default 1) sets the polygon size
  68598. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  68599. * * 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`
  68600. * * 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
  68601. * * 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)`)
  68602. * * 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
  68603. * * 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
  68604. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  68605. * * 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
  68606. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  68607. * @param name defines the name of the mesh
  68608. * @param options defines the options used to create the mesh
  68609. * @param scene defines the hosting scene
  68610. * @returns the polyhedron mesh
  68611. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  68612. */
  68613. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  68614. var polyhedron = new BABYLON.Mesh(name, scene);
  68615. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  68616. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  68617. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  68618. vertexData.applyToMesh(polyhedron, options.updatable);
  68619. return polyhedron;
  68620. };
  68621. /**
  68622. * Creates a decal mesh.
  68623. * 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
  68624. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  68625. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  68626. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  68627. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  68628. * @param name defines the name of the mesh
  68629. * @param sourceMesh defines the mesh where the decal must be applied
  68630. * @param options defines the options used to create the mesh
  68631. * @param scene defines the hosting scene
  68632. * @returns the decal mesh
  68633. * @see http://doc.babylonjs.com/how_to/decals
  68634. */
  68635. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  68636. var indices = sourceMesh.getIndices();
  68637. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  68638. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  68639. var position = options.position || BABYLON.Vector3.Zero();
  68640. var normal = options.normal || BABYLON.Vector3.Up();
  68641. var size = options.size || BABYLON.Vector3.One();
  68642. var angle = options.angle || 0;
  68643. // Getting correct rotation
  68644. if (!normal) {
  68645. var target = new BABYLON.Vector3(0, 0, 1);
  68646. var camera = sourceMesh.getScene().activeCamera;
  68647. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  68648. normal = camera.globalPosition.subtract(cameraWorldTarget);
  68649. }
  68650. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  68651. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  68652. var pitch = Math.atan2(normal.y, len);
  68653. // Matrix
  68654. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  68655. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  68656. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  68657. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  68658. var vertexData = new BABYLON.VertexData();
  68659. vertexData.indices = [];
  68660. vertexData.positions = [];
  68661. vertexData.normals = [];
  68662. vertexData.uvs = [];
  68663. var currentVertexDataIndex = 0;
  68664. var extractDecalVector3 = function (indexId) {
  68665. var result = new BABYLON.PositionNormalVertex();
  68666. if (!indices || !positions || !normals) {
  68667. return result;
  68668. }
  68669. var vertexId = indices[indexId];
  68670. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  68671. // Send vector to decal local world
  68672. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  68673. // Get normal
  68674. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  68675. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  68676. return result;
  68677. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  68678. var clip = function (vertices, axis) {
  68679. if (vertices.length === 0) {
  68680. return vertices;
  68681. }
  68682. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  68683. var clipVertices = function (v0, v1) {
  68684. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  68685. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  68686. };
  68687. var result = new Array();
  68688. for (var index = 0; index < vertices.length; index += 3) {
  68689. var v1Out;
  68690. var v2Out;
  68691. var v3Out;
  68692. var total = 0;
  68693. var nV1 = null;
  68694. var nV2 = null;
  68695. var nV3 = null;
  68696. var nV4 = null;
  68697. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  68698. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  68699. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  68700. v1Out = d1 > 0;
  68701. v2Out = d2 > 0;
  68702. v3Out = d3 > 0;
  68703. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  68704. switch (total) {
  68705. case 0:
  68706. result.push(vertices[index]);
  68707. result.push(vertices[index + 1]);
  68708. result.push(vertices[index + 2]);
  68709. break;
  68710. case 1:
  68711. if (v1Out) {
  68712. nV1 = vertices[index + 1];
  68713. nV2 = vertices[index + 2];
  68714. nV3 = clipVertices(vertices[index], nV1);
  68715. nV4 = clipVertices(vertices[index], nV2);
  68716. }
  68717. if (v2Out) {
  68718. nV1 = vertices[index];
  68719. nV2 = vertices[index + 2];
  68720. nV3 = clipVertices(vertices[index + 1], nV1);
  68721. nV4 = clipVertices(vertices[index + 1], nV2);
  68722. result.push(nV3);
  68723. result.push(nV2.clone());
  68724. result.push(nV1.clone());
  68725. result.push(nV2.clone());
  68726. result.push(nV3.clone());
  68727. result.push(nV4);
  68728. break;
  68729. }
  68730. if (v3Out) {
  68731. nV1 = vertices[index];
  68732. nV2 = vertices[index + 1];
  68733. nV3 = clipVertices(vertices[index + 2], nV1);
  68734. nV4 = clipVertices(vertices[index + 2], nV2);
  68735. }
  68736. if (nV1 && nV2 && nV3 && nV4) {
  68737. result.push(nV1.clone());
  68738. result.push(nV2.clone());
  68739. result.push(nV3);
  68740. result.push(nV4);
  68741. result.push(nV3.clone());
  68742. result.push(nV2.clone());
  68743. }
  68744. break;
  68745. case 2:
  68746. if (!v1Out) {
  68747. nV1 = vertices[index].clone();
  68748. nV2 = clipVertices(nV1, vertices[index + 1]);
  68749. nV3 = clipVertices(nV1, vertices[index + 2]);
  68750. result.push(nV1);
  68751. result.push(nV2);
  68752. result.push(nV3);
  68753. }
  68754. if (!v2Out) {
  68755. nV1 = vertices[index + 1].clone();
  68756. nV2 = clipVertices(nV1, vertices[index + 2]);
  68757. nV3 = clipVertices(nV1, vertices[index]);
  68758. result.push(nV1);
  68759. result.push(nV2);
  68760. result.push(nV3);
  68761. }
  68762. if (!v3Out) {
  68763. nV1 = vertices[index + 2].clone();
  68764. nV2 = clipVertices(nV1, vertices[index]);
  68765. nV3 = clipVertices(nV1, vertices[index + 1]);
  68766. result.push(nV1);
  68767. result.push(nV2);
  68768. result.push(nV3);
  68769. }
  68770. break;
  68771. case 3:
  68772. break;
  68773. }
  68774. }
  68775. return result;
  68776. };
  68777. for (var index = 0; index < indices.length; index += 3) {
  68778. var faceVertices = new Array();
  68779. faceVertices.push(extractDecalVector3(index));
  68780. faceVertices.push(extractDecalVector3(index + 1));
  68781. faceVertices.push(extractDecalVector3(index + 2));
  68782. // Clip
  68783. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  68784. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  68785. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  68786. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  68787. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  68788. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  68789. if (faceVertices.length === 0) {
  68790. continue;
  68791. }
  68792. // Add UVs and get back to world
  68793. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  68794. var vertex = faceVertices[vIndex];
  68795. //TODO check for Int32Array | Uint32Array | Uint16Array
  68796. vertexData.indices.push(currentVertexDataIndex);
  68797. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  68798. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  68799. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  68800. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  68801. currentVertexDataIndex++;
  68802. }
  68803. }
  68804. // Return mesh
  68805. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  68806. vertexData.applyToMesh(decal);
  68807. decal.position = position.clone();
  68808. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  68809. return decal;
  68810. };
  68811. // Privates
  68812. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  68813. // extrusion geometry
  68814. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  68815. var tangents = path3D.getTangents();
  68816. var normals = path3D.getNormals();
  68817. var binormals = path3D.getBinormals();
  68818. var distances = path3D.getDistances();
  68819. var angle = 0;
  68820. var returnScale = function () { return scale !== null ? scale : 1; };
  68821. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  68822. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  68823. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  68824. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  68825. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  68826. for (var i = 0; i < curve.length; i++) {
  68827. var shapePath = new Array();
  68828. var angleStep = rotate(i, distances[i]);
  68829. var scaleRatio = scl(i, distances[i]);
  68830. for (var p = 0; p < shape.length; p++) {
  68831. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  68832. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  68833. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  68834. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  68835. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  68836. shapePath[p] = rotated;
  68837. }
  68838. shapePaths[index] = shapePath;
  68839. angle += angleStep;
  68840. index++;
  68841. }
  68842. // cap
  68843. var capPath = function (shapePath) {
  68844. var pointCap = Array();
  68845. var barycenter = BABYLON.Vector3.Zero();
  68846. var i;
  68847. for (i = 0; i < shapePath.length; i++) {
  68848. barycenter.addInPlace(shapePath[i]);
  68849. }
  68850. barycenter.scaleInPlace(1.0 / shapePath.length);
  68851. for (i = 0; i < shapePath.length; i++) {
  68852. pointCap.push(barycenter);
  68853. }
  68854. return pointCap;
  68855. };
  68856. switch (cap) {
  68857. case BABYLON.Mesh.NO_CAP:
  68858. break;
  68859. case BABYLON.Mesh.CAP_START:
  68860. shapePaths[0] = capPath(shapePaths[2]);
  68861. shapePaths[1] = shapePaths[2];
  68862. break;
  68863. case BABYLON.Mesh.CAP_END:
  68864. shapePaths[index] = shapePaths[index - 1];
  68865. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68866. break;
  68867. case BABYLON.Mesh.CAP_ALL:
  68868. shapePaths[0] = capPath(shapePaths[2]);
  68869. shapePaths[1] = shapePaths[2];
  68870. shapePaths[index] = shapePaths[index - 1];
  68871. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  68872. break;
  68873. default:
  68874. break;
  68875. }
  68876. return shapePaths;
  68877. };
  68878. var path3D;
  68879. var pathArray;
  68880. if (instance) { // instance update
  68881. var storage = instance._creationDataStorage;
  68882. path3D = storage.path3D.update(curve);
  68883. pathArray = extrusionPathArray(shape, curve, storage.path3D, storage.pathArray, scale, rotation, scaleFunction, rotateFunction, storage.cap, custom);
  68884. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  68885. return instance;
  68886. }
  68887. // extruded shape creation
  68888. path3D = new BABYLON.Path3D(curve);
  68889. var newShapePaths = new Array();
  68890. cap = (cap < 0 || cap > 3) ? 0 : cap;
  68891. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  68892. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  68893. extrudedGeneric._creationDataStorage.pathArray = pathArray;
  68894. extrudedGeneric._creationDataStorage.path3D = path3D;
  68895. extrudedGeneric._creationDataStorage.cap = cap;
  68896. return extrudedGeneric;
  68897. };
  68898. return MeshBuilder;
  68899. }());
  68900. BABYLON.MeshBuilder = MeshBuilder;
  68901. })(BABYLON || (BABYLON = {}));
  68902. //# sourceMappingURL=babylon.meshBuilder.js.map
  68903. var BABYLON;
  68904. (function (BABYLON) {
  68905. /**
  68906. * Draco compression (https://google.github.io/draco/)
  68907. *
  68908. * This class wraps the Draco module.
  68909. *
  68910. * **Encoder**
  68911. *
  68912. * The encoder is not currently implemented.
  68913. *
  68914. * **Decoder**
  68915. *
  68916. * 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.
  68917. *
  68918. * To update the configuration, use the following code:
  68919. * ```javascript
  68920. * BABYLON.DracoCompression.Configuration = {
  68921. * decoder: {
  68922. * wasmUrl: "<url to the WebAssembly library>",
  68923. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  68924. * fallbackUrl: "<url to the fallback JavaScript library>",
  68925. * }
  68926. * };
  68927. * ```
  68928. *
  68929. * 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.
  68930. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  68931. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  68932. *
  68933. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  68934. * ```javascript
  68935. * var dracoCompression = new BABYLON.DracoCompression();
  68936. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  68937. * [BABYLON.VertexBuffer.PositionKind]: 0
  68938. * });
  68939. * ```
  68940. *
  68941. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  68942. */
  68943. var DracoCompression = /** @class */ (function () {
  68944. /**
  68945. * Constructor
  68946. */
  68947. function DracoCompression() {
  68948. }
  68949. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  68950. /**
  68951. * Returns true if the decoder is available.
  68952. */
  68953. get: function () {
  68954. if (typeof DracoDecoderModule !== "undefined") {
  68955. return true;
  68956. }
  68957. var decoder = DracoCompression.Configuration.decoder;
  68958. if (decoder) {
  68959. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  68960. return true;
  68961. }
  68962. if (decoder.fallbackUrl) {
  68963. return true;
  68964. }
  68965. }
  68966. return false;
  68967. },
  68968. enumerable: true,
  68969. configurable: true
  68970. });
  68971. /**
  68972. * Stop all async operations and release resources.
  68973. */
  68974. DracoCompression.prototype.dispose = function () {
  68975. };
  68976. /**
  68977. * Decode Draco compressed mesh data to vertex data.
  68978. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  68979. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  68980. * @returns A promise that resolves with the decoded vertex data
  68981. */
  68982. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  68983. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  68984. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  68985. var module = wrappedModule.module;
  68986. var vertexData = new BABYLON.VertexData();
  68987. var buffer = new module.DecoderBuffer();
  68988. buffer.Init(dataView, dataView.byteLength);
  68989. var decoder = new module.Decoder();
  68990. var geometry;
  68991. var status;
  68992. try {
  68993. var type = decoder.GetEncodedGeometryType(buffer);
  68994. switch (type) {
  68995. case module.TRIANGULAR_MESH:
  68996. geometry = new module.Mesh();
  68997. status = decoder.DecodeBufferToMesh(buffer, geometry);
  68998. break;
  68999. case module.POINT_CLOUD:
  69000. geometry = new module.PointCloud();
  69001. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  69002. break;
  69003. default:
  69004. throw new Error("Invalid geometry type " + type);
  69005. }
  69006. if (!status.ok() || !geometry.ptr) {
  69007. throw new Error(status.error_msg());
  69008. }
  69009. var numPoints = geometry.num_points();
  69010. if (type === module.TRIANGULAR_MESH) {
  69011. var numFaces = geometry.num_faces();
  69012. var faceIndices = new module.DracoInt32Array();
  69013. try {
  69014. var indices = new Uint32Array(numFaces * 3);
  69015. for (var i = 0; i < numFaces; i++) {
  69016. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  69017. var offset = i * 3;
  69018. indices[offset + 0] = faceIndices.GetValue(0);
  69019. indices[offset + 1] = faceIndices.GetValue(1);
  69020. indices[offset + 2] = faceIndices.GetValue(2);
  69021. }
  69022. vertexData.indices = indices;
  69023. }
  69024. finally {
  69025. module.destroy(faceIndices);
  69026. }
  69027. }
  69028. for (var kind in attributes) {
  69029. var uniqueId = attributes[kind];
  69030. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  69031. var dracoData = new module.DracoFloat32Array();
  69032. try {
  69033. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  69034. var babylonData = new Float32Array(numPoints * attribute.num_components());
  69035. for (var i = 0; i < babylonData.length; i++) {
  69036. babylonData[i] = dracoData.GetValue(i);
  69037. }
  69038. vertexData.set(babylonData, kind);
  69039. }
  69040. finally {
  69041. module.destroy(dracoData);
  69042. }
  69043. }
  69044. }
  69045. finally {
  69046. if (geometry) {
  69047. module.destroy(geometry);
  69048. }
  69049. module.destroy(decoder);
  69050. module.destroy(buffer);
  69051. }
  69052. return vertexData;
  69053. });
  69054. };
  69055. DracoCompression._GetDecoderModule = function () {
  69056. if (!DracoCompression._DecoderModulePromise) {
  69057. var promise = null;
  69058. var config_1 = {};
  69059. if (typeof DracoDecoderModule !== "undefined") {
  69060. promise = Promise.resolve();
  69061. }
  69062. else {
  69063. var decoder = DracoCompression.Configuration.decoder;
  69064. if (decoder) {
  69065. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  69066. promise = Promise.all([
  69067. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  69068. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  69069. config_1.wasmBinary = data;
  69070. })
  69071. ]);
  69072. }
  69073. else if (decoder.fallbackUrl) {
  69074. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  69075. }
  69076. }
  69077. }
  69078. if (!promise) {
  69079. throw new Error("Draco decoder module is not available");
  69080. }
  69081. DracoCompression._DecoderModulePromise = promise.then(function () {
  69082. return new Promise(function (resolve) {
  69083. config_1.onModuleLoaded = function (decoderModule) {
  69084. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  69085. resolve({ module: decoderModule });
  69086. };
  69087. DracoDecoderModule(config_1);
  69088. });
  69089. });
  69090. }
  69091. return DracoCompression._DecoderModulePromise;
  69092. };
  69093. DracoCompression._LoadScriptAsync = function (url) {
  69094. return new Promise(function (resolve, reject) {
  69095. BABYLON.Tools.LoadScript(url, function () {
  69096. resolve();
  69097. }, function (message) {
  69098. reject(new Error(message));
  69099. });
  69100. });
  69101. };
  69102. DracoCompression._LoadFileAsync = function (url) {
  69103. return new Promise(function (resolve, reject) {
  69104. BABYLON.Tools.LoadFile(url, function (data) {
  69105. resolve(data);
  69106. }, undefined, undefined, true, function (request, exception) {
  69107. reject(exception);
  69108. });
  69109. });
  69110. };
  69111. /**
  69112. * The configuration. Defaults to the following urls:
  69113. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  69114. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  69115. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69116. */
  69117. DracoCompression.Configuration = {
  69118. decoder: {
  69119. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  69120. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  69121. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  69122. }
  69123. };
  69124. return DracoCompression;
  69125. }());
  69126. BABYLON.DracoCompression = DracoCompression;
  69127. })(BABYLON || (BABYLON = {}));
  69128. //# sourceMappingURL=babylon.dracoCompression.js.map
  69129. var BABYLON;
  69130. (function (BABYLON) {
  69131. // Sets the default audio engine to Babylon JS.
  69132. BABYLON.Engine.AudioEngineFactory = function (hostElement) { return new AudioEngine(hostElement); };
  69133. /**
  69134. * This represents the default audio engine used in babylon.
  69135. * It is responsible to play, synchronize and analyse sounds throughout the application.
  69136. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69137. */
  69138. var AudioEngine = /** @class */ (function () {
  69139. /**
  69140. * Instantiates a new audio engine.
  69141. *
  69142. * There should be only one per page as some browsers restrict the number
  69143. * of audio contexts you can create.
  69144. * @param hostElement defines the host element where to display the mute icon if necessary
  69145. */
  69146. function AudioEngine(hostElement) {
  69147. if (hostElement === void 0) { hostElement = null; }
  69148. var _this = this;
  69149. this._audioContext = null;
  69150. this._audioContextInitialized = false;
  69151. this._muteButton = null;
  69152. /**
  69153. * Gets whether the current host supports Web Audio and thus could create AudioContexts.
  69154. */
  69155. this.canUseWebAudio = false;
  69156. /**
  69157. * Defines if Babylon should emit a warning if WebAudio is not supported.
  69158. * @ignoreNaming
  69159. */
  69160. this.WarnedWebAudioUnsupported = false;
  69161. /**
  69162. * Gets whether or not mp3 are supported by your browser.
  69163. */
  69164. this.isMP3supported = false;
  69165. /**
  69166. * Gets whether or not ogg are supported by your browser.
  69167. */
  69168. this.isOGGsupported = false;
  69169. /**
  69170. * Gets whether audio has been unlocked on the device.
  69171. * Some Browsers have strong restrictions about Audio and won t autoplay unless
  69172. * a user interaction has happened.
  69173. */
  69174. this.unlocked = true;
  69175. /**
  69176. * Defines if the audio engine relies on a custom unlocked button.
  69177. * In this case, the embedded button will not be displayed.
  69178. */
  69179. this.useCustomUnlockedButton = false;
  69180. /**
  69181. * Event raised when audio has been unlocked on the browser.
  69182. */
  69183. this.onAudioUnlockedObservable = new BABYLON.Observable();
  69184. /**
  69185. * Event raised when audio has been locked on the browser.
  69186. */
  69187. this.onAudioLockedObservable = new BABYLON.Observable();
  69188. this._tryToRun = false;
  69189. this._onResize = function () {
  69190. _this._moveButtonToTopLeft();
  69191. };
  69192. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  69193. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  69194. this.canUseWebAudio = true;
  69195. }
  69196. var audioElem = document.createElement('audio');
  69197. this._hostElement = hostElement;
  69198. try {
  69199. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  69200. this.isMP3supported = true;
  69201. }
  69202. }
  69203. catch (e) {
  69204. // protect error during capability check.
  69205. }
  69206. try {
  69207. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  69208. this.isOGGsupported = true;
  69209. }
  69210. }
  69211. catch (e) {
  69212. // protect error during capability check.
  69213. }
  69214. }
  69215. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  69216. /**
  69217. * Gets the current AudioContext if available.
  69218. */
  69219. get: function () {
  69220. if (!this._audioContextInitialized) {
  69221. this._initializeAudioContext();
  69222. }
  69223. else {
  69224. if (!this.unlocked && !this._muteButton) {
  69225. this._displayMuteButton();
  69226. }
  69227. }
  69228. return this._audioContext;
  69229. },
  69230. enumerable: true,
  69231. configurable: true
  69232. });
  69233. /**
  69234. * Flags the audio engine in Locked state.
  69235. * This happens due to new browser policies preventing audio to autoplay.
  69236. */
  69237. AudioEngine.prototype.lock = function () {
  69238. this._triggerSuspendedState();
  69239. };
  69240. /**
  69241. * Unlocks the audio engine once a user action has been done on the dom.
  69242. * This is helpful to resume play once browser policies have been satisfied.
  69243. */
  69244. AudioEngine.prototype.unlock = function () {
  69245. this._triggerRunningState();
  69246. };
  69247. AudioEngine.prototype._resumeAudioContext = function () {
  69248. var result;
  69249. if (this._audioContext.resume) {
  69250. result = this._audioContext.resume();
  69251. }
  69252. return result || Promise.resolve();
  69253. };
  69254. AudioEngine.prototype._initializeAudioContext = function () {
  69255. try {
  69256. if (this.canUseWebAudio) {
  69257. this._audioContext = new AudioContext();
  69258. // create a global volume gain node
  69259. this.masterGain = this._audioContext.createGain();
  69260. this.masterGain.gain.value = 1;
  69261. this.masterGain.connect(this._audioContext.destination);
  69262. this._audioContextInitialized = true;
  69263. if (this._audioContext.state === "running") {
  69264. // Do not wait for the promise to unlock.
  69265. this._triggerRunningState();
  69266. }
  69267. }
  69268. }
  69269. catch (e) {
  69270. this.canUseWebAudio = false;
  69271. BABYLON.Tools.Error("Web Audio: " + e.message);
  69272. }
  69273. };
  69274. AudioEngine.prototype._triggerRunningState = function () {
  69275. var _this = this;
  69276. if (this._tryToRun) {
  69277. return;
  69278. }
  69279. this._tryToRun = true;
  69280. this._resumeAudioContext()
  69281. .then(function () {
  69282. _this._tryToRun = false;
  69283. if (_this._muteButton) {
  69284. _this._hideMuteButton();
  69285. }
  69286. }).catch(function () {
  69287. _this._tryToRun = false;
  69288. _this.unlocked = false;
  69289. });
  69290. // Notify users that the audio stack is unlocked/unmuted
  69291. this.unlocked = true;
  69292. this.onAudioUnlockedObservable.notifyObservers(this);
  69293. };
  69294. AudioEngine.prototype._triggerSuspendedState = function () {
  69295. this.unlocked = false;
  69296. this.onAudioLockedObservable.notifyObservers(this);
  69297. this._displayMuteButton();
  69298. };
  69299. AudioEngine.prototype._displayMuteButton = function () {
  69300. var _this = this;
  69301. if (this.useCustomUnlockedButton) {
  69302. return;
  69303. }
  69304. this._muteButton = document.createElement("BUTTON");
  69305. this._muteButton.className = "babylonUnmuteIcon";
  69306. this._muteButton.id = "babylonUnmuteIconBtn";
  69307. this._muteButton.title = "Unmute";
  69308. 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) }";
  69309. var style = document.createElement('style');
  69310. style.appendChild(document.createTextNode(css));
  69311. document.getElementsByTagName('head')[0].appendChild(style);
  69312. document.body.appendChild(this._muteButton);
  69313. this._moveButtonToTopLeft();
  69314. this._muteButton.addEventListener('touchend', function () {
  69315. _this._triggerRunningState();
  69316. }, true);
  69317. this._muteButton.addEventListener('click', function () {
  69318. _this._triggerRunningState();
  69319. }, true);
  69320. window.addEventListener("resize", this._onResize);
  69321. };
  69322. AudioEngine.prototype._moveButtonToTopLeft = function () {
  69323. if (this._hostElement && this._muteButton) {
  69324. this._muteButton.style.top = this._hostElement.offsetTop + 20 + "px";
  69325. this._muteButton.style.left = this._hostElement.offsetLeft + 20 + "px";
  69326. }
  69327. };
  69328. AudioEngine.prototype._hideMuteButton = function () {
  69329. if (this._muteButton) {
  69330. document.body.removeChild(this._muteButton);
  69331. this._muteButton = null;
  69332. }
  69333. };
  69334. /**
  69335. * Destroy and release the resources associated with the audio ccontext.
  69336. */
  69337. AudioEngine.prototype.dispose = function () {
  69338. if (this.canUseWebAudio && this._audioContextInitialized) {
  69339. if (this._connectedAnalyser && this._audioContext) {
  69340. this._connectedAnalyser.stopDebugCanvas();
  69341. this._connectedAnalyser.dispose();
  69342. this.masterGain.disconnect();
  69343. this.masterGain.connect(this._audioContext.destination);
  69344. this._connectedAnalyser = null;
  69345. }
  69346. this.masterGain.gain.value = 1;
  69347. }
  69348. this.WarnedWebAudioUnsupported = false;
  69349. this._hideMuteButton();
  69350. window.removeEventListener("resize", this._onResize);
  69351. this.onAudioUnlockedObservable.clear();
  69352. this.onAudioLockedObservable.clear();
  69353. };
  69354. /**
  69355. * Gets the global volume sets on the master gain.
  69356. * @returns the global volume if set or -1 otherwise
  69357. */
  69358. AudioEngine.prototype.getGlobalVolume = function () {
  69359. if (this.canUseWebAudio && this._audioContextInitialized) {
  69360. return this.masterGain.gain.value;
  69361. }
  69362. else {
  69363. return -1;
  69364. }
  69365. };
  69366. /**
  69367. * Sets the global volume of your experience (sets on the master gain).
  69368. * @param newVolume Defines the new global volume of the application
  69369. */
  69370. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  69371. if (this.canUseWebAudio && this._audioContextInitialized) {
  69372. this.masterGain.gain.value = newVolume;
  69373. }
  69374. };
  69375. /**
  69376. * Connect the audio engine to an audio analyser allowing some amazing
  69377. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  69378. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  69379. * @param analyser The analyser to connect to the engine
  69380. */
  69381. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  69382. if (this._connectedAnalyser) {
  69383. this._connectedAnalyser.stopDebugCanvas();
  69384. }
  69385. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  69386. this._connectedAnalyser = analyser;
  69387. this.masterGain.disconnect();
  69388. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  69389. }
  69390. };
  69391. return AudioEngine;
  69392. }());
  69393. BABYLON.AudioEngine = AudioEngine;
  69394. })(BABYLON || (BABYLON = {}));
  69395. //# sourceMappingURL=babylon.audioEngine.js.map
  69396. var BABYLON;
  69397. (function (BABYLON) {
  69398. /**
  69399. * Defines a sound that can be played in the application.
  69400. * The sound can either be an ambient track or a simple sound played in reaction to a user action.
  69401. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  69402. */
  69403. var Sound = /** @class */ (function () {
  69404. /**
  69405. * Create a sound and attach it to a scene
  69406. * @param name Name of your sound
  69407. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  69408. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  69409. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  69410. */
  69411. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  69412. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  69413. var _this = this;
  69414. /**
  69415. * Does the sound autoplay once loaded.
  69416. */
  69417. this.autoplay = false;
  69418. /**
  69419. * Does the sound loop after it finishes playing once.
  69420. */
  69421. this.loop = false;
  69422. /**
  69423. * Does the sound use a custom attenuation curve to simulate the falloff
  69424. * happening when the source gets further away from the camera.
  69425. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69426. */
  69427. this.useCustomAttenuation = false;
  69428. /**
  69429. * Is this sound currently played.
  69430. */
  69431. this.isPlaying = false;
  69432. /**
  69433. * Is this sound currently paused.
  69434. */
  69435. this.isPaused = false;
  69436. /**
  69437. * Does this sound enables spatial sound.
  69438. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69439. */
  69440. this.spatialSound = false;
  69441. /**
  69442. * Define the reference distance the sound should be heard perfectly.
  69443. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69444. */
  69445. this.refDistance = 1;
  69446. /**
  69447. * Define the roll off factor of spatial sounds.
  69448. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69449. */
  69450. this.rolloffFactor = 1;
  69451. /**
  69452. * Define the max distance the sound should be heard (intensity just became 0 at this point).
  69453. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69454. */
  69455. this.maxDistance = 100;
  69456. /**
  69457. * Define the distance attenuation model the sound will follow.
  69458. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69459. */
  69460. this.distanceModel = "linear";
  69461. /**
  69462. * Observable event when the current playing sound finishes.
  69463. */
  69464. this.onEndedObservable = new BABYLON.Observable();
  69465. this._panningModel = "equalpower";
  69466. this._playbackRate = 1;
  69467. this._streaming = false;
  69468. this._startTime = 0;
  69469. this._startOffset = 0;
  69470. this._position = BABYLON.Vector3.Zero();
  69471. /** @hidden */
  69472. this._positionInEmitterSpace = false;
  69473. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  69474. this._volume = 1;
  69475. this._isReadyToPlay = false;
  69476. this._isDirectional = false;
  69477. // Used if you'd like to create a directional sound.
  69478. // If not set, the sound will be omnidirectional
  69479. this._coneInnerAngle = 360;
  69480. this._coneOuterAngle = 360;
  69481. this._coneOuterGain = 0;
  69482. this._isOutputConnected = false;
  69483. this._urlType = "Unknown";
  69484. this.name = name;
  69485. this._scene = scene;
  69486. var compo = scene._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  69487. if (!compo) {
  69488. compo = new BABYLON.AudioSceneComponent(scene);
  69489. scene._addComponent(compo);
  69490. }
  69491. this._readyToPlayCallback = readyToPlayCallback;
  69492. // Default custom attenuation function is a linear attenuation
  69493. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  69494. if (currentDistance < maxDistance) {
  69495. return currentVolume * (1 - currentDistance / maxDistance);
  69496. }
  69497. else {
  69498. return 0;
  69499. }
  69500. };
  69501. if (options) {
  69502. this.autoplay = options.autoplay || false;
  69503. this.loop = options.loop || false;
  69504. // if volume === 0, we need another way to check this option
  69505. if (options.volume !== undefined) {
  69506. this._volume = options.volume;
  69507. }
  69508. this.spatialSound = options.spatialSound || false;
  69509. this.maxDistance = options.maxDistance || 100;
  69510. this.useCustomAttenuation = options.useCustomAttenuation || false;
  69511. this.rolloffFactor = options.rolloffFactor || 1;
  69512. this.refDistance = options.refDistance || 1;
  69513. this.distanceModel = options.distanceModel || "linear";
  69514. this._playbackRate = options.playbackRate || 1;
  69515. this._streaming = options.streaming || false;
  69516. }
  69517. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69518. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  69519. this._soundGain.gain.value = this._volume;
  69520. this._inputAudioNode = this._soundGain;
  69521. this._outputAudioNode = this._soundGain;
  69522. if (this.spatialSound) {
  69523. this._createSpatialParameters();
  69524. }
  69525. this._scene.mainSoundTrack.AddSound(this);
  69526. var validParameter = true;
  69527. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  69528. if (urlOrArrayBuffer) {
  69529. try {
  69530. if (typeof (urlOrArrayBuffer) === "string") {
  69531. this._urlType = "String";
  69532. }
  69533. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  69534. this._urlType = "ArrayBuffer";
  69535. }
  69536. else if (urlOrArrayBuffer instanceof MediaStream) {
  69537. this._urlType = "MediaStream";
  69538. }
  69539. else if (Array.isArray(urlOrArrayBuffer)) {
  69540. this._urlType = "Array";
  69541. }
  69542. var urls = [];
  69543. var codecSupportedFound = false;
  69544. switch (this._urlType) {
  69545. case "MediaStream":
  69546. this._streaming = true;
  69547. this._isReadyToPlay = true;
  69548. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(urlOrArrayBuffer);
  69549. if (this.autoplay) {
  69550. this.play();
  69551. }
  69552. if (this._readyToPlayCallback) {
  69553. this._readyToPlayCallback();
  69554. }
  69555. break;
  69556. case "ArrayBuffer":
  69557. if (urlOrArrayBuffer.byteLength > 0) {
  69558. codecSupportedFound = true;
  69559. this._soundLoaded(urlOrArrayBuffer);
  69560. }
  69561. break;
  69562. case "String":
  69563. urls.push(urlOrArrayBuffer);
  69564. case "Array":
  69565. if (urls.length === 0)
  69566. urls = urlOrArrayBuffer;
  69567. // If we found a supported format, we load it immediately and stop the loop
  69568. for (var i = 0; i < urls.length; i++) {
  69569. var url = urls[i];
  69570. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  69571. codecSupportedFound = true;
  69572. }
  69573. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  69574. codecSupportedFound = true;
  69575. }
  69576. if (url.indexOf(".wav", url.length - 4) !== -1) {
  69577. codecSupportedFound = true;
  69578. }
  69579. if (url.indexOf("blob:") !== -1) {
  69580. codecSupportedFound = true;
  69581. }
  69582. if (codecSupportedFound) {
  69583. // Loading sound using XHR2
  69584. if (!this._streaming) {
  69585. this._scene._loadFile(url, function (data) {
  69586. _this._soundLoaded(data);
  69587. }, undefined, true, true, function (exception) {
  69588. if (exception) {
  69589. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  69590. }
  69591. BABYLON.Tools.Error("Sound creation aborted.");
  69592. _this._scene.mainSoundTrack.RemoveSound(_this);
  69593. });
  69594. }
  69595. // Streaming sound using HTML5 Audio tag
  69596. else {
  69597. this._htmlAudioElement = new Audio(url);
  69598. this._htmlAudioElement.controls = false;
  69599. this._htmlAudioElement.loop = this.loop;
  69600. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  69601. this._htmlAudioElement.preload = "auto";
  69602. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  69603. _this._isReadyToPlay = true;
  69604. if (_this.autoplay) {
  69605. _this.play();
  69606. }
  69607. if (_this._readyToPlayCallback) {
  69608. _this._readyToPlayCallback();
  69609. }
  69610. });
  69611. document.body.appendChild(this._htmlAudioElement);
  69612. this._htmlAudioElement.load();
  69613. }
  69614. break;
  69615. }
  69616. }
  69617. break;
  69618. default:
  69619. validParameter = false;
  69620. break;
  69621. }
  69622. if (!validParameter) {
  69623. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  69624. }
  69625. else {
  69626. if (!codecSupportedFound) {
  69627. this._isReadyToPlay = true;
  69628. // Simulating a ready to play event to avoid breaking code path
  69629. if (this._readyToPlayCallback) {
  69630. window.setTimeout(function () {
  69631. if (_this._readyToPlayCallback) {
  69632. _this._readyToPlayCallback();
  69633. }
  69634. }, 1000);
  69635. }
  69636. }
  69637. }
  69638. }
  69639. catch (ex) {
  69640. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  69641. this._scene.mainSoundTrack.RemoveSound(this);
  69642. }
  69643. }
  69644. }
  69645. else {
  69646. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  69647. this._scene.mainSoundTrack.AddSound(this);
  69648. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  69649. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  69650. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  69651. }
  69652. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  69653. if (this._readyToPlayCallback) {
  69654. window.setTimeout(function () {
  69655. if (_this._readyToPlayCallback) {
  69656. _this._readyToPlayCallback();
  69657. }
  69658. }, 1000);
  69659. }
  69660. }
  69661. }
  69662. /**
  69663. * Release the sound and its associated resources
  69664. */
  69665. Sound.prototype.dispose = function () {
  69666. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69667. if (this.isPlaying) {
  69668. this.stop();
  69669. }
  69670. this._isReadyToPlay = false;
  69671. if (this.soundTrackId === -1) {
  69672. this._scene.mainSoundTrack.RemoveSound(this);
  69673. }
  69674. else if (this._scene.soundTracks) {
  69675. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  69676. }
  69677. if (this._soundGain) {
  69678. this._soundGain.disconnect();
  69679. this._soundGain = null;
  69680. }
  69681. if (this._soundPanner) {
  69682. this._soundPanner.disconnect();
  69683. this._soundPanner = null;
  69684. }
  69685. if (this._soundSource) {
  69686. this._soundSource.disconnect();
  69687. this._soundSource = null;
  69688. }
  69689. this._audioBuffer = null;
  69690. if (this._htmlAudioElement) {
  69691. this._htmlAudioElement.pause();
  69692. this._htmlAudioElement.src = "";
  69693. document.body.removeChild(this._htmlAudioElement);
  69694. }
  69695. if (this._streamingSource) {
  69696. this._streamingSource.disconnect();
  69697. }
  69698. if (this._connectedMesh && this._registerFunc) {
  69699. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  69700. this._connectedMesh = null;
  69701. }
  69702. }
  69703. };
  69704. /**
  69705. * Gets if the sounds is ready to be played or not.
  69706. * @returns true if ready, otherwise false
  69707. */
  69708. Sound.prototype.isReady = function () {
  69709. return this._isReadyToPlay;
  69710. };
  69711. Sound.prototype._soundLoaded = function (audioData) {
  69712. var _this = this;
  69713. if (!BABYLON.Engine.audioEngine.audioContext) {
  69714. return;
  69715. }
  69716. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  69717. _this._audioBuffer = buffer;
  69718. _this._isReadyToPlay = true;
  69719. if (_this.autoplay) {
  69720. _this.play();
  69721. }
  69722. if (_this._readyToPlayCallback) {
  69723. _this._readyToPlayCallback();
  69724. }
  69725. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  69726. };
  69727. /**
  69728. * Sets the data of the sound from an audiobuffer
  69729. * @param audioBuffer The audioBuffer containing the data
  69730. */
  69731. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  69732. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69733. this._audioBuffer = audioBuffer;
  69734. this._isReadyToPlay = true;
  69735. }
  69736. };
  69737. /**
  69738. * Updates the current sounds options such as maxdistance, loop...
  69739. * @param options A JSON object containing values named as the object properties
  69740. */
  69741. Sound.prototype.updateOptions = function (options) {
  69742. if (options) {
  69743. this.loop = options.loop || this.loop;
  69744. this.maxDistance = options.maxDistance || this.maxDistance;
  69745. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  69746. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  69747. this.refDistance = options.refDistance || this.refDistance;
  69748. this.distanceModel = options.distanceModel || this.distanceModel;
  69749. this._playbackRate = options.playbackRate || this._playbackRate;
  69750. this._updateSpatialParameters();
  69751. if (this.isPlaying) {
  69752. if (this._streaming && this._htmlAudioElement) {
  69753. this._htmlAudioElement.playbackRate = this._playbackRate;
  69754. }
  69755. else {
  69756. if (this._soundSource) {
  69757. this._soundSource.playbackRate.value = this._playbackRate;
  69758. }
  69759. }
  69760. }
  69761. }
  69762. };
  69763. Sound.prototype._createSpatialParameters = function () {
  69764. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  69765. if (this._scene.headphone) {
  69766. this._panningModel = "HRTF";
  69767. }
  69768. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  69769. this._updateSpatialParameters();
  69770. this._soundPanner.connect(this._outputAudioNode);
  69771. this._inputAudioNode = this._soundPanner;
  69772. }
  69773. };
  69774. Sound.prototype._updateSpatialParameters = function () {
  69775. if (this.spatialSound && this._soundPanner) {
  69776. if (this.useCustomAttenuation) {
  69777. // Tricks to disable in a way embedded Web Audio attenuation
  69778. this._soundPanner.distanceModel = "linear";
  69779. this._soundPanner.maxDistance = Number.MAX_VALUE;
  69780. this._soundPanner.refDistance = 1;
  69781. this._soundPanner.rolloffFactor = 1;
  69782. this._soundPanner.panningModel = this._panningModel;
  69783. }
  69784. else {
  69785. this._soundPanner.distanceModel = this.distanceModel;
  69786. this._soundPanner.maxDistance = this.maxDistance;
  69787. this._soundPanner.refDistance = this.refDistance;
  69788. this._soundPanner.rolloffFactor = this.rolloffFactor;
  69789. this._soundPanner.panningModel = this._panningModel;
  69790. }
  69791. }
  69792. };
  69793. /**
  69794. * Switch the panning model to HRTF:
  69795. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  69796. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69797. */
  69798. Sound.prototype.switchPanningModelToHRTF = function () {
  69799. this._panningModel = "HRTF";
  69800. this._switchPanningModel();
  69801. };
  69802. /**
  69803. * Switch the panning model to Equal Power:
  69804. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  69805. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  69806. */
  69807. Sound.prototype.switchPanningModelToEqualPower = function () {
  69808. this._panningModel = "equalpower";
  69809. this._switchPanningModel();
  69810. };
  69811. Sound.prototype._switchPanningModel = function () {
  69812. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69813. this._soundPanner.panningModel = this._panningModel;
  69814. }
  69815. };
  69816. /**
  69817. * Connect this sound to a sound track audio node like gain...
  69818. * @param soundTrackAudioNode the sound track audio node to connect to
  69819. */
  69820. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  69821. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  69822. if (this._isOutputConnected) {
  69823. this._outputAudioNode.disconnect();
  69824. }
  69825. this._outputAudioNode.connect(soundTrackAudioNode);
  69826. this._isOutputConnected = true;
  69827. }
  69828. };
  69829. /**
  69830. * Transform this sound into a directional source
  69831. * @param coneInnerAngle Size of the inner cone in degree
  69832. * @param coneOuterAngle Size of the outer cone in degree
  69833. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  69834. */
  69835. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  69836. if (coneOuterAngle < coneInnerAngle) {
  69837. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  69838. return;
  69839. }
  69840. this._coneInnerAngle = coneInnerAngle;
  69841. this._coneOuterAngle = coneOuterAngle;
  69842. this._coneOuterGain = coneOuterGain;
  69843. this._isDirectional = true;
  69844. if (this.isPlaying && this.loop) {
  69845. this.stop();
  69846. this.play();
  69847. }
  69848. };
  69849. Object.defineProperty(Sound.prototype, "directionalConeInnerAngle", {
  69850. /**
  69851. * Gets or sets the inner angle for the directional cone.
  69852. */
  69853. get: function () {
  69854. return this._coneInnerAngle;
  69855. },
  69856. /**
  69857. * Gets or sets the inner angle for the directional cone.
  69858. */
  69859. set: function (value) {
  69860. if (value != this._coneInnerAngle) {
  69861. if (this._coneOuterAngle < value) {
  69862. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69863. return;
  69864. }
  69865. this._coneInnerAngle = value;
  69866. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69867. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69868. }
  69869. }
  69870. },
  69871. enumerable: true,
  69872. configurable: true
  69873. });
  69874. Object.defineProperty(Sound.prototype, "directionalConeOuterAngle", {
  69875. /**
  69876. * Gets or sets the outer angle for the directional cone.
  69877. */
  69878. get: function () {
  69879. return this._coneOuterAngle;
  69880. },
  69881. /**
  69882. * Gets or sets the outer angle for the directional cone.
  69883. */
  69884. set: function (value) {
  69885. if (value != this._coneOuterAngle) {
  69886. if (value < this._coneInnerAngle) {
  69887. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  69888. return;
  69889. }
  69890. this._coneOuterAngle = value;
  69891. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  69892. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69893. }
  69894. }
  69895. },
  69896. enumerable: true,
  69897. configurable: true
  69898. });
  69899. /**
  69900. * Sets the position of the emitter if spatial sound is enabled
  69901. * @param newPosition Defines the new posisiton
  69902. */
  69903. Sound.prototype.setPosition = function (newPosition) {
  69904. this._position = newPosition;
  69905. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner && !isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69906. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69907. }
  69908. };
  69909. /**
  69910. * Sets the local direction of the emitter if spatial sound is enabled
  69911. * @param newLocalDirection Defines the new local direction
  69912. */
  69913. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  69914. this._localDirection = newLocalDirection;
  69915. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  69916. this._updateDirection();
  69917. }
  69918. };
  69919. Sound.prototype._updateDirection = function () {
  69920. if (!this._connectedMesh || !this._soundPanner) {
  69921. return;
  69922. }
  69923. var mat = this._connectedMesh.getWorldMatrix();
  69924. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  69925. direction.normalize();
  69926. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  69927. };
  69928. /** @hidden */
  69929. Sound.prototype.updateDistanceFromListener = function () {
  69930. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  69931. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  69932. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  69933. }
  69934. };
  69935. /**
  69936. * Sets a new custom attenuation function for the sound.
  69937. * @param callback Defines the function used for the attenuation
  69938. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-your-own-custom-attenuation-function
  69939. */
  69940. Sound.prototype.setAttenuationFunction = function (callback) {
  69941. this._customAttenuationFunction = callback;
  69942. };
  69943. /**
  69944. * Play the sound
  69945. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  69946. * @param offset (optional) Start the sound setting it at a specific time
  69947. */
  69948. Sound.prototype.play = function (time, offset) {
  69949. var _this = this;
  69950. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  69951. try {
  69952. if (this._startOffset < 0) {
  69953. time = -this._startOffset;
  69954. this._startOffset = 0;
  69955. }
  69956. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  69957. if (!this._soundSource || !this._streamingSource) {
  69958. if (this.spatialSound && this._soundPanner) {
  69959. if (!isNaN(this._position.x) && !isNaN(this._position.y) && !isNaN(this._position.z)) {
  69960. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  69961. }
  69962. if (this._isDirectional) {
  69963. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  69964. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  69965. this._soundPanner.coneOuterGain = this._coneOuterGain;
  69966. if (this._connectedMesh) {
  69967. this._updateDirection();
  69968. }
  69969. else {
  69970. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  69971. }
  69972. }
  69973. }
  69974. }
  69975. if (this._streaming) {
  69976. if (!this._streamingSource) {
  69977. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  69978. this._htmlAudioElement.onended = function () { _this._onended(); };
  69979. this._htmlAudioElement.playbackRate = this._playbackRate;
  69980. }
  69981. this._streamingSource.disconnect();
  69982. this._streamingSource.connect(this._inputAudioNode);
  69983. if (this._htmlAudioElement) {
  69984. // required to manage properly the new suspended default state of Chrome
  69985. // When the option 'streaming: true' is used, we need first to wait for
  69986. // the audio engine to be unlocked by a user gesture before trying to play
  69987. // an HTML Audio elememt
  69988. var tryToPlay = function () {
  69989. if (BABYLON.Engine.audioEngine.unlocked) {
  69990. var playPromise = _this._htmlAudioElement.play();
  69991. // In browsers that don’t yet support this functionality,
  69992. // playPromise won’t be defined.
  69993. if (playPromise !== undefined) {
  69994. playPromise.catch(function (error) {
  69995. // Automatic playback failed.
  69996. // Waiting for the audio engine to be unlocked by user click on unmute
  69997. BABYLON.Engine.audioEngine.lock();
  69998. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  69999. });
  70000. }
  70001. }
  70002. else {
  70003. BABYLON.Engine.audioEngine.onAudioUnlockedObservable.addOnce(function () { tryToPlay(); });
  70004. }
  70005. };
  70006. tryToPlay();
  70007. }
  70008. }
  70009. else {
  70010. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  70011. this._soundSource.buffer = this._audioBuffer;
  70012. this._soundSource.connect(this._inputAudioNode);
  70013. this._soundSource.loop = this.loop;
  70014. this._soundSource.playbackRate.value = this._playbackRate;
  70015. this._soundSource.onended = function () { _this._onended(); };
  70016. if (this._soundSource.buffer) {
  70017. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  70018. }
  70019. }
  70020. this._startTime = startTime;
  70021. this.isPlaying = true;
  70022. this.isPaused = false;
  70023. }
  70024. catch (ex) {
  70025. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  70026. }
  70027. }
  70028. };
  70029. Sound.prototype._onended = function () {
  70030. this.isPlaying = false;
  70031. if (this.onended) {
  70032. this.onended();
  70033. }
  70034. this.onEndedObservable.notifyObservers(this);
  70035. };
  70036. /**
  70037. * Stop the sound
  70038. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  70039. */
  70040. Sound.prototype.stop = function (time) {
  70041. if (this.isPlaying) {
  70042. if (this._streaming) {
  70043. if (this._htmlAudioElement) {
  70044. this._htmlAudioElement.pause();
  70045. // Test needed for Firefox or it will generate an Invalid State Error
  70046. if (this._htmlAudioElement.currentTime > 0) {
  70047. this._htmlAudioElement.currentTime = 0;
  70048. }
  70049. }
  70050. else {
  70051. this._streamingSource.disconnect();
  70052. }
  70053. }
  70054. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  70055. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  70056. this._soundSource.stop(stopTime);
  70057. this._soundSource.onended = function () { };
  70058. if (!this.isPaused) {
  70059. this._startOffset = 0;
  70060. }
  70061. }
  70062. this.isPlaying = false;
  70063. }
  70064. };
  70065. /**
  70066. * Put the sound in pause
  70067. */
  70068. Sound.prototype.pause = function () {
  70069. if (this.isPlaying) {
  70070. this.isPaused = true;
  70071. if (this._streaming) {
  70072. if (this._htmlAudioElement) {
  70073. this._htmlAudioElement.pause();
  70074. }
  70075. else {
  70076. this._streamingSource.disconnect();
  70077. }
  70078. }
  70079. else if (BABYLON.Engine.audioEngine.audioContext) {
  70080. this.stop(0);
  70081. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  70082. }
  70083. }
  70084. };
  70085. /**
  70086. * Sets a dedicated volume for this sounds
  70087. * @param newVolume Define the new volume of the sound
  70088. * @param time Define in how long the sound should be at this value
  70089. */
  70090. Sound.prototype.setVolume = function (newVolume, time) {
  70091. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  70092. if (time && BABYLON.Engine.audioEngine.audioContext) {
  70093. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  70094. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  70095. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  70096. }
  70097. else {
  70098. this._soundGain.gain.value = newVolume;
  70099. }
  70100. }
  70101. this._volume = newVolume;
  70102. };
  70103. /**
  70104. * Set the sound play back rate
  70105. * @param newPlaybackRate Define the playback rate the sound should be played at
  70106. */
  70107. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  70108. this._playbackRate = newPlaybackRate;
  70109. if (this.isPlaying) {
  70110. if (this._streaming && this._htmlAudioElement) {
  70111. this._htmlAudioElement.playbackRate = this._playbackRate;
  70112. }
  70113. else if (this._soundSource) {
  70114. this._soundSource.playbackRate.value = this._playbackRate;
  70115. }
  70116. }
  70117. };
  70118. /**
  70119. * Gets the volume of the sound.
  70120. * @returns the volume of the sound
  70121. */
  70122. Sound.prototype.getVolume = function () {
  70123. return this._volume;
  70124. };
  70125. /**
  70126. * Attach the sound to a dedicated mesh
  70127. * @param meshToConnectTo The mesh to connect the sound with
  70128. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70129. */
  70130. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  70131. var _this = this;
  70132. if (this._connectedMesh && this._registerFunc) {
  70133. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70134. this._registerFunc = null;
  70135. }
  70136. this._connectedMesh = meshToConnectTo;
  70137. if (!this.spatialSound) {
  70138. this.spatialSound = true;
  70139. this._createSpatialParameters();
  70140. if (this.isPlaying && this.loop) {
  70141. this.stop();
  70142. this.play();
  70143. }
  70144. }
  70145. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  70146. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  70147. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  70148. };
  70149. /**
  70150. * Detach the sound from the previously attached mesh
  70151. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#attaching-a-sound-to-a-mesh
  70152. */
  70153. Sound.prototype.detachFromMesh = function () {
  70154. if (this._connectedMesh && this._registerFunc) {
  70155. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  70156. this._registerFunc = null;
  70157. this._connectedMesh = null;
  70158. }
  70159. };
  70160. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  70161. if (!node.getBoundingInfo) {
  70162. return;
  70163. }
  70164. var mesh = node;
  70165. if (this._positionInEmitterSpace) {
  70166. mesh.worldMatrixFromCache.invertToRef(BABYLON.Tmp.Matrix[0]);
  70167. this.setPosition(BABYLON.Tmp.Matrix[0].getTranslation());
  70168. }
  70169. else {
  70170. var boundingInfo = mesh.getBoundingInfo();
  70171. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  70172. }
  70173. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  70174. this._updateDirection();
  70175. }
  70176. };
  70177. /**
  70178. * Clone the current sound in the scene.
  70179. * @returns the new sound clone
  70180. */
  70181. Sound.prototype.clone = function () {
  70182. var _this = this;
  70183. if (!this._streaming) {
  70184. var setBufferAndRun = function () {
  70185. if (_this._isReadyToPlay) {
  70186. clonedSound._audioBuffer = _this.getAudioBuffer();
  70187. clonedSound._isReadyToPlay = true;
  70188. if (clonedSound.autoplay) {
  70189. clonedSound.play();
  70190. }
  70191. }
  70192. else {
  70193. window.setTimeout(setBufferAndRun, 300);
  70194. }
  70195. };
  70196. var currentOptions = {
  70197. autoplay: this.autoplay, loop: this.loop,
  70198. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  70199. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  70200. refDistance: this.refDistance, distanceModel: this.distanceModel
  70201. };
  70202. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  70203. if (this.useCustomAttenuation) {
  70204. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  70205. }
  70206. clonedSound.setPosition(this._position);
  70207. clonedSound.setPlaybackRate(this._playbackRate);
  70208. setBufferAndRun();
  70209. return clonedSound;
  70210. }
  70211. // Can't clone a streaming sound
  70212. else {
  70213. return null;
  70214. }
  70215. };
  70216. /**
  70217. * Gets the current underlying audio buffer containing the data
  70218. * @returns the audio buffer
  70219. */
  70220. Sound.prototype.getAudioBuffer = function () {
  70221. return this._audioBuffer;
  70222. };
  70223. /**
  70224. * Serializes the Sound in a JSON representation
  70225. * @returns the JSON representation of the sound
  70226. */
  70227. Sound.prototype.serialize = function () {
  70228. var serializationObject = {
  70229. name: this.name,
  70230. url: this.name,
  70231. autoplay: this.autoplay,
  70232. loop: this.loop,
  70233. volume: this._volume,
  70234. spatialSound: this.spatialSound,
  70235. maxDistance: this.maxDistance,
  70236. rolloffFactor: this.rolloffFactor,
  70237. refDistance: this.refDistance,
  70238. distanceModel: this.distanceModel,
  70239. playbackRate: this._playbackRate,
  70240. panningModel: this._panningModel,
  70241. soundTrackId: this.soundTrackId
  70242. };
  70243. if (this.spatialSound) {
  70244. if (this._connectedMesh)
  70245. serializationObject.connectedMeshId = this._connectedMesh.id;
  70246. serializationObject.position = this._position.asArray();
  70247. serializationObject.refDistance = this.refDistance;
  70248. serializationObject.distanceModel = this.distanceModel;
  70249. serializationObject.isDirectional = this._isDirectional;
  70250. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  70251. serializationObject.coneInnerAngle = this._coneInnerAngle;
  70252. serializationObject.coneOuterAngle = this._coneOuterAngle;
  70253. serializationObject.coneOuterGain = this._coneOuterGain;
  70254. }
  70255. return serializationObject;
  70256. };
  70257. /**
  70258. * Parse a JSON representation of a sound to innstantiate in a given scene
  70259. * @param parsedSound Define the JSON representation of the sound (usually coming from the serialize method)
  70260. * @param scene Define the scene the new parsed sound should be created in
  70261. * @param rootUrl Define the rooturl of the load in case we need to fetch relative dependencies
  70262. * @param sourceSound Define a cound place holder if do not need to instantiate a new one
  70263. * @returns the newly parsed sound
  70264. */
  70265. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  70266. var soundName = parsedSound.name;
  70267. var soundUrl;
  70268. if (parsedSound.url) {
  70269. soundUrl = rootUrl + parsedSound.url;
  70270. }
  70271. else {
  70272. soundUrl = rootUrl + soundName;
  70273. }
  70274. var options = {
  70275. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  70276. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  70277. rolloffFactor: parsedSound.rolloffFactor,
  70278. refDistance: parsedSound.refDistance,
  70279. distanceModel: parsedSound.distanceModel,
  70280. playbackRate: parsedSound.playbackRate
  70281. };
  70282. var newSound;
  70283. if (!sourceSound) {
  70284. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  70285. scene._addPendingData(newSound);
  70286. }
  70287. else {
  70288. var setBufferAndRun = function () {
  70289. if (sourceSound._isReadyToPlay) {
  70290. newSound._audioBuffer = sourceSound.getAudioBuffer();
  70291. newSound._isReadyToPlay = true;
  70292. if (newSound.autoplay) {
  70293. newSound.play();
  70294. }
  70295. }
  70296. else {
  70297. window.setTimeout(setBufferAndRun, 300);
  70298. }
  70299. };
  70300. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  70301. setBufferAndRun();
  70302. }
  70303. if (parsedSound.position) {
  70304. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  70305. newSound.setPosition(soundPosition);
  70306. }
  70307. if (parsedSound.isDirectional) {
  70308. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  70309. if (parsedSound.localDirectionToMesh) {
  70310. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  70311. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  70312. }
  70313. }
  70314. if (parsedSound.connectedMeshId) {
  70315. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  70316. if (connectedMesh) {
  70317. newSound.attachToMesh(connectedMesh);
  70318. }
  70319. }
  70320. return newSound;
  70321. };
  70322. return Sound;
  70323. }());
  70324. BABYLON.Sound = Sound;
  70325. })(BABYLON || (BABYLON = {}));
  70326. //# sourceMappingURL=babylon.sound.js.map
  70327. var BABYLON;
  70328. (function (BABYLON) {
  70329. /**
  70330. * It could be useful to isolate your music & sounds on several tracks to better manage volume on a grouped instance of sounds.
  70331. * It will be also used in a future release to apply effects on a specific track.
  70332. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70333. */
  70334. var SoundTrack = /** @class */ (function () {
  70335. /**
  70336. * Creates a new sound track.
  70337. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-sound-tracks
  70338. * @param scene Define the scene the sound track belongs to
  70339. * @param options
  70340. */
  70341. function SoundTrack(scene, options) {
  70342. if (options === void 0) { options = {}; }
  70343. /**
  70344. * The unique identifier of the sound track in the scene.
  70345. */
  70346. this.id = -1;
  70347. this._isMainTrack = false;
  70348. this._isInitialized = false;
  70349. this._scene = scene;
  70350. this.soundCollection = new Array();
  70351. this._options = options;
  70352. if (!this._isMainTrack && this._scene.soundTracks) {
  70353. this._scene.soundTracks.push(this);
  70354. this.id = this._scene.soundTracks.length - 1;
  70355. }
  70356. }
  70357. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  70358. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  70359. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  70360. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  70361. if (this._options) {
  70362. if (this._options.volume) {
  70363. this._outputAudioNode.gain.value = this._options.volume;
  70364. }
  70365. if (this._options.mainTrack) {
  70366. this._isMainTrack = this._options.mainTrack;
  70367. }
  70368. }
  70369. this._isInitialized = true;
  70370. }
  70371. };
  70372. /**
  70373. * Release the sound track and its associated resources
  70374. */
  70375. SoundTrack.prototype.dispose = function () {
  70376. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  70377. if (this._connectedAnalyser) {
  70378. this._connectedAnalyser.stopDebugCanvas();
  70379. }
  70380. while (this.soundCollection.length) {
  70381. this.soundCollection[0].dispose();
  70382. }
  70383. if (this._outputAudioNode) {
  70384. this._outputAudioNode.disconnect();
  70385. }
  70386. this._outputAudioNode = null;
  70387. }
  70388. };
  70389. /**
  70390. * Adds a sound to this sound track
  70391. * @param sound define the cound to add
  70392. * @ignoreNaming
  70393. */
  70394. SoundTrack.prototype.AddSound = function (sound) {
  70395. if (!this._isInitialized) {
  70396. this._initializeSoundTrackAudioGraph();
  70397. }
  70398. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70399. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  70400. }
  70401. if (sound.soundTrackId) {
  70402. if (sound.soundTrackId === -1) {
  70403. this._scene.mainSoundTrack.RemoveSound(sound);
  70404. }
  70405. else if (this._scene.soundTracks) {
  70406. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  70407. }
  70408. }
  70409. this.soundCollection.push(sound);
  70410. sound.soundTrackId = this.id;
  70411. };
  70412. /**
  70413. * Removes a sound to this sound track
  70414. * @param sound define the cound to remove
  70415. * @ignoreNaming
  70416. */
  70417. SoundTrack.prototype.RemoveSound = function (sound) {
  70418. var index = this.soundCollection.indexOf(sound);
  70419. if (index !== -1) {
  70420. this.soundCollection.splice(index, 1);
  70421. }
  70422. };
  70423. /**
  70424. * Set a global volume for the full sound track.
  70425. * @param newVolume Define the new volume of the sound track
  70426. */
  70427. SoundTrack.prototype.setVolume = function (newVolume) {
  70428. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70429. this._outputAudioNode.gain.value = newVolume;
  70430. }
  70431. };
  70432. /**
  70433. * Switch the panning model to HRTF:
  70434. * Renders a stereo output of higher quality than equalpower — it uses a convolution with measured impulse responses from human subjects.
  70435. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70436. */
  70437. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  70438. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70439. for (var i = 0; i < this.soundCollection.length; i++) {
  70440. this.soundCollection[i].switchPanningModelToHRTF();
  70441. }
  70442. }
  70443. };
  70444. /**
  70445. * Switch the panning model to Equal Power:
  70446. * Represents the equal-power panning algorithm, generally regarded as simple and efficient. equalpower is the default value.
  70447. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#creating-a-spatial-3d-sound
  70448. */
  70449. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  70450. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70451. for (var i = 0; i < this.soundCollection.length; i++) {
  70452. this.soundCollection[i].switchPanningModelToEqualPower();
  70453. }
  70454. }
  70455. };
  70456. /**
  70457. * Connect the sound track to an audio analyser allowing some amazing
  70458. * synchornization between the sounds/music and your visualization (VuMeter for instance).
  70459. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music#using-the-analyser
  70460. * @param analyser The analyser to connect to the engine
  70461. */
  70462. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  70463. if (this._connectedAnalyser) {
  70464. this._connectedAnalyser.stopDebugCanvas();
  70465. }
  70466. this._connectedAnalyser = analyser;
  70467. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  70468. this._outputAudioNode.disconnect();
  70469. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  70470. }
  70471. };
  70472. return SoundTrack;
  70473. }());
  70474. BABYLON.SoundTrack = SoundTrack;
  70475. })(BABYLON || (BABYLON = {}));
  70476. //# sourceMappingURL=babylon.soundtrack.js.map
  70477. var BABYLON;
  70478. (function (BABYLON) {
  70479. /**
  70480. * Class used to work with sound analyzer using fast fourier transform (FFT)
  70481. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  70482. */
  70483. var Analyser = /** @class */ (function () {
  70484. /**
  70485. * Creates a new analyser
  70486. * @param scene defines hosting scene
  70487. */
  70488. function Analyser(scene) {
  70489. /**
  70490. * Gets or sets the smoothing
  70491. * @ignorenaming
  70492. */
  70493. this.SMOOTHING = 0.75;
  70494. /**
  70495. * Gets or sets the FFT table size
  70496. * @ignorenaming
  70497. */
  70498. this.FFT_SIZE = 512;
  70499. /**
  70500. * Gets or sets the bar graph amplitude
  70501. * @ignorenaming
  70502. */
  70503. this.BARGRAPHAMPLITUDE = 256;
  70504. /**
  70505. * Gets or sets the position of the debug canvas
  70506. * @ignorenaming
  70507. */
  70508. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  70509. /**
  70510. * Gets or sets the debug canvas size
  70511. * @ignorenaming
  70512. */
  70513. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  70514. this._scene = scene;
  70515. this._audioEngine = BABYLON.Engine.audioEngine;
  70516. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  70517. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  70518. this._webAudioAnalyser.minDecibels = -140;
  70519. this._webAudioAnalyser.maxDecibels = 0;
  70520. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70521. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  70522. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  70523. }
  70524. }
  70525. /**
  70526. * Get the number of data values you will have to play with for the visualization
  70527. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  70528. * @returns a number
  70529. */
  70530. Analyser.prototype.getFrequencyBinCount = function () {
  70531. if (this._audioEngine.canUseWebAudio) {
  70532. return this._webAudioAnalyser.frequencyBinCount;
  70533. }
  70534. else {
  70535. return 0;
  70536. }
  70537. };
  70538. /**
  70539. * Gets the current frequency data as a byte array
  70540. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70541. * @returns a Uint8Array
  70542. */
  70543. Analyser.prototype.getByteFrequencyData = function () {
  70544. if (this._audioEngine.canUseWebAudio) {
  70545. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70546. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70547. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  70548. }
  70549. return this._byteFreqs;
  70550. };
  70551. /**
  70552. * Gets the current waveform as a byte array
  70553. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  70554. * @returns a Uint8Array
  70555. */
  70556. Analyser.prototype.getByteTimeDomainData = function () {
  70557. if (this._audioEngine.canUseWebAudio) {
  70558. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70559. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70560. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  70561. }
  70562. return this._byteTime;
  70563. };
  70564. /**
  70565. * Gets the current frequency data as a float array
  70566. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  70567. * @returns a Float32Array
  70568. */
  70569. Analyser.prototype.getFloatFrequencyData = function () {
  70570. if (this._audioEngine.canUseWebAudio) {
  70571. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  70572. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  70573. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  70574. }
  70575. return this._floatFreqs;
  70576. };
  70577. /**
  70578. * Renders the debug canvas
  70579. */
  70580. Analyser.prototype.drawDebugCanvas = function () {
  70581. var _this = this;
  70582. if (this._audioEngine.canUseWebAudio) {
  70583. if (!this._debugCanvas) {
  70584. this._debugCanvas = document.createElement("canvas");
  70585. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  70586. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  70587. this._debugCanvas.style.position = "absolute";
  70588. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  70589. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  70590. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  70591. document.body.appendChild(this._debugCanvas);
  70592. this._registerFunc = function () {
  70593. _this.drawDebugCanvas();
  70594. };
  70595. this._scene.registerBeforeRender(this._registerFunc);
  70596. }
  70597. if (this._registerFunc && this._debugCanvasContext) {
  70598. var workingArray = this.getByteFrequencyData();
  70599. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  70600. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  70601. // Draw the frequency domain chart.
  70602. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  70603. var value = workingArray[i];
  70604. var percent = value / this.BARGRAPHAMPLITUDE;
  70605. var height = this.DEBUGCANVASSIZE.height * percent;
  70606. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  70607. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  70608. var hue = i / this.getFrequencyBinCount() * 360;
  70609. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  70610. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  70611. }
  70612. }
  70613. }
  70614. };
  70615. /**
  70616. * Stops rendering the debug canvas and removes it
  70617. */
  70618. Analyser.prototype.stopDebugCanvas = function () {
  70619. if (this._debugCanvas) {
  70620. if (this._registerFunc) {
  70621. this._scene.unregisterBeforeRender(this._registerFunc);
  70622. this._registerFunc = null;
  70623. }
  70624. document.body.removeChild(this._debugCanvas);
  70625. this._debugCanvas = null;
  70626. this._debugCanvasContext = null;
  70627. }
  70628. };
  70629. /**
  70630. * Connects two audio nodes
  70631. * @param inputAudioNode defines first node to connect
  70632. * @param outputAudioNode defines second node to connect
  70633. */
  70634. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  70635. if (this._audioEngine.canUseWebAudio) {
  70636. inputAudioNode.connect(this._webAudioAnalyser);
  70637. this._webAudioAnalyser.connect(outputAudioNode);
  70638. }
  70639. };
  70640. /**
  70641. * Releases all associated resources
  70642. */
  70643. Analyser.prototype.dispose = function () {
  70644. if (this._audioEngine.canUseWebAudio) {
  70645. this._webAudioAnalyser.disconnect();
  70646. }
  70647. };
  70648. return Analyser;
  70649. }());
  70650. BABYLON.Analyser = Analyser;
  70651. })(BABYLON || (BABYLON = {}));
  70652. //# sourceMappingURL=babylon.analyser.js.map
  70653. var BABYLON;
  70654. (function (BABYLON) {
  70655. /**
  70656. * Wraps one or more Sound objects and selects one with random weight for playback.
  70657. */
  70658. var WeightedSound = /** @class */ (function () {
  70659. /**
  70660. * Creates a new WeightedSound from the list of sounds given.
  70661. * @param loop When true a Sound will be selected and played when the current playing Sound completes.
  70662. * @param sounds Array of Sounds that will be selected from.
  70663. * @param weights Array of number values for selection weights; length must equal sounds, values will be normalized to 1
  70664. */
  70665. function WeightedSound(loop, sounds, weights) {
  70666. var _this = this;
  70667. /** When true a Sound will be selected and played when the current playing Sound completes. */
  70668. this.loop = false;
  70669. this._coneInnerAngle = 360;
  70670. this._coneOuterAngle = 360;
  70671. this._volume = 1;
  70672. /** A Sound is currently playing. */
  70673. this.isPlaying = false;
  70674. /** A Sound is currently paused. */
  70675. this.isPaused = false;
  70676. this._sounds = [];
  70677. this._weights = [];
  70678. if (sounds.length !== weights.length) {
  70679. throw new Error('Sounds length does not equal weights length');
  70680. }
  70681. this.loop = loop;
  70682. this._weights = weights;
  70683. // Normalize the weights
  70684. var weightSum = 0;
  70685. for (var _i = 0, weights_1 = weights; _i < weights_1.length; _i++) {
  70686. var weight = weights_1[_i];
  70687. weightSum += weight;
  70688. }
  70689. var invWeightSum = weightSum > 0 ? 1 / weightSum : 0;
  70690. for (var i = 0; i < this._weights.length; i++) {
  70691. this._weights[i] *= invWeightSum;
  70692. }
  70693. this._sounds = sounds;
  70694. for (var _a = 0, _b = this._sounds; _a < _b.length; _a++) {
  70695. var sound = _b[_a];
  70696. sound.onEndedObservable.add(function () { _this._onended(); });
  70697. }
  70698. }
  70699. Object.defineProperty(WeightedSound.prototype, "directionalConeInnerAngle", {
  70700. /**
  70701. * The size of cone in degrees for a directional sound in which there will be no attenuation.
  70702. */
  70703. get: function () {
  70704. return this._coneInnerAngle;
  70705. },
  70706. /**
  70707. * The size of cone in degress for a directional sound in which there will be no attenuation.
  70708. */
  70709. set: function (value) {
  70710. if (value !== this._coneInnerAngle) {
  70711. if (this._coneOuterAngle < value) {
  70712. BABYLON.Tools.Error("directionalConeInnerAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70713. return;
  70714. }
  70715. this._coneInnerAngle = value;
  70716. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70717. var sound = _a[_i];
  70718. sound.directionalConeInnerAngle = value;
  70719. }
  70720. }
  70721. },
  70722. enumerable: true,
  70723. configurable: true
  70724. });
  70725. Object.defineProperty(WeightedSound.prototype, "directionalConeOuterAngle", {
  70726. /**
  70727. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70728. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70729. */
  70730. get: function () {
  70731. return this._coneOuterAngle;
  70732. },
  70733. /**
  70734. * Size of cone in degrees for a directional sound outside of which there will be no sound.
  70735. * Listener angles between innerAngle and outerAngle will falloff linearly.
  70736. */
  70737. set: function (value) {
  70738. if (value !== this._coneOuterAngle) {
  70739. if (value < this._coneInnerAngle) {
  70740. BABYLON.Tools.Error("directionalConeOuterAngle: outer angle of the cone must be superior or equal to the inner angle.");
  70741. return;
  70742. }
  70743. this._coneOuterAngle = value;
  70744. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70745. var sound = _a[_i];
  70746. sound.directionalConeOuterAngle = value;
  70747. }
  70748. }
  70749. },
  70750. enumerable: true,
  70751. configurable: true
  70752. });
  70753. Object.defineProperty(WeightedSound.prototype, "volume", {
  70754. /**
  70755. * Playback volume.
  70756. */
  70757. get: function () {
  70758. return this._volume;
  70759. },
  70760. /**
  70761. * Playback volume.
  70762. */
  70763. set: function (value) {
  70764. if (value !== this._volume) {
  70765. for (var _i = 0, _a = this._sounds; _i < _a.length; _i++) {
  70766. var sound = _a[_i];
  70767. sound.setVolume(value);
  70768. }
  70769. }
  70770. },
  70771. enumerable: true,
  70772. configurable: true
  70773. });
  70774. WeightedSound.prototype._onended = function () {
  70775. if (this._currentIndex !== undefined) {
  70776. this._sounds[this._currentIndex].autoplay = false;
  70777. }
  70778. if (this.loop && this.isPlaying) {
  70779. this.play();
  70780. }
  70781. else {
  70782. this.isPlaying = false;
  70783. }
  70784. };
  70785. /**
  70786. * Suspend playback
  70787. */
  70788. WeightedSound.prototype.pause = function () {
  70789. this.isPaused = true;
  70790. if (this._currentIndex !== undefined) {
  70791. this._sounds[this._currentIndex].pause();
  70792. }
  70793. };
  70794. /**
  70795. * Stop playback
  70796. */
  70797. WeightedSound.prototype.stop = function () {
  70798. this.isPlaying = false;
  70799. if (this._currentIndex !== undefined) {
  70800. this._sounds[this._currentIndex].stop();
  70801. }
  70802. };
  70803. /**
  70804. * Start playback.
  70805. * @param startOffset Position the clip head at a specific time in seconds.
  70806. */
  70807. WeightedSound.prototype.play = function (startOffset) {
  70808. if (!this.isPaused) {
  70809. this.stop();
  70810. var randomValue = Math.random();
  70811. var total = 0;
  70812. for (var i = 0; i < this._weights.length; i++) {
  70813. total += this._weights[i];
  70814. if (randomValue <= total) {
  70815. this._currentIndex = i;
  70816. break;
  70817. }
  70818. }
  70819. }
  70820. var sound = this._sounds[this._currentIndex];
  70821. if (sound.isReady()) {
  70822. sound.play(0, this.isPaused ? undefined : startOffset);
  70823. }
  70824. else {
  70825. sound.autoplay = true;
  70826. }
  70827. this.isPlaying = true;
  70828. this.isPaused = false;
  70829. };
  70830. return WeightedSound;
  70831. }());
  70832. BABYLON.WeightedSound = WeightedSound;
  70833. })(BABYLON || (BABYLON = {}));
  70834. //# sourceMappingURL=babylon.weightedsound.js.map
  70835. var BABYLON;
  70836. (function (BABYLON) {
  70837. // Adds the parser to the scene parsers.
  70838. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_AUDIO, function (parsedData, scene, container, rootUrl) {
  70839. // TODO: add sound
  70840. var loadedSounds = [];
  70841. var loadedSound;
  70842. container.sounds = container.sounds || [];
  70843. if (parsedData.sounds !== undefined && parsedData.sounds !== null) {
  70844. for (var index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  70845. var parsedSound = parsedData.sounds[index];
  70846. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  70847. if (!parsedSound.url)
  70848. parsedSound.url = parsedSound.name;
  70849. if (!loadedSounds[parsedSound.url]) {
  70850. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  70851. loadedSounds[parsedSound.url] = loadedSound;
  70852. container.sounds.push(loadedSound);
  70853. }
  70854. else {
  70855. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  70856. }
  70857. }
  70858. else {
  70859. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  70860. }
  70861. }
  70862. }
  70863. loadedSounds = [];
  70864. });
  70865. Object.defineProperty(BABYLON.Scene.prototype, "mainSoundTrack", {
  70866. get: function () {
  70867. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70868. if (!compo) {
  70869. compo = new AudioSceneComponent(this);
  70870. this._addComponent(compo);
  70871. }
  70872. if (!this._mainSoundTrack) {
  70873. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  70874. }
  70875. return this._mainSoundTrack;
  70876. },
  70877. enumerable: true,
  70878. configurable: true
  70879. });
  70880. BABYLON.Scene.prototype.getSoundByName = function (name) {
  70881. var index;
  70882. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  70883. if (this.mainSoundTrack.soundCollection[index].name === name) {
  70884. return this.mainSoundTrack.soundCollection[index];
  70885. }
  70886. }
  70887. if (this.soundTracks) {
  70888. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  70889. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  70890. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  70891. return this.soundTracks[sdIndex].soundCollection[index];
  70892. }
  70893. }
  70894. }
  70895. }
  70896. return null;
  70897. };
  70898. Object.defineProperty(BABYLON.Scene.prototype, "audioEnabled", {
  70899. get: function () {
  70900. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70901. if (!compo) {
  70902. compo = new AudioSceneComponent(this);
  70903. this._addComponent(compo);
  70904. }
  70905. return compo.audioEnabled;
  70906. },
  70907. set: function (value) {
  70908. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70909. if (!compo) {
  70910. compo = new AudioSceneComponent(this);
  70911. this._addComponent(compo);
  70912. }
  70913. if (value) {
  70914. compo.enableAudio();
  70915. }
  70916. else {
  70917. compo.disableAudio();
  70918. }
  70919. },
  70920. enumerable: true,
  70921. configurable: true
  70922. });
  70923. Object.defineProperty(BABYLON.Scene.prototype, "headphone", {
  70924. get: function () {
  70925. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70926. if (!compo) {
  70927. compo = new AudioSceneComponent(this);
  70928. this._addComponent(compo);
  70929. }
  70930. return compo.headphone;
  70931. },
  70932. set: function (value) {
  70933. var compo = this._getComponent(BABYLON.SceneComponentConstants.NAME_AUDIO);
  70934. if (!compo) {
  70935. compo = new AudioSceneComponent(this);
  70936. this._addComponent(compo);
  70937. }
  70938. if (value) {
  70939. compo.switchAudioModeForHeadphones();
  70940. }
  70941. else {
  70942. compo.switchAudioModeForNormalSpeakers();
  70943. }
  70944. },
  70945. enumerable: true,
  70946. configurable: true
  70947. });
  70948. /**
  70949. * Defines the sound scene component responsible to manage any sounds
  70950. * in a given scene.
  70951. */
  70952. var AudioSceneComponent = /** @class */ (function () {
  70953. /**
  70954. * Creates a new instance of the component for the given scene
  70955. * @param scene Defines the scene to register the component in
  70956. */
  70957. function AudioSceneComponent(scene) {
  70958. /**
  70959. * The component name helpfull to identify the component in the list of scene components.
  70960. */
  70961. this.name = BABYLON.SceneComponentConstants.NAME_AUDIO;
  70962. this._audioEnabled = true;
  70963. this._headphone = false;
  70964. this.scene = scene;
  70965. scene.soundTracks = new Array();
  70966. scene.sounds = new Array();
  70967. }
  70968. Object.defineProperty(AudioSceneComponent.prototype, "audioEnabled", {
  70969. /**
  70970. * Gets whether audio is enabled or not.
  70971. * Please use related enable/disable method to switch state.
  70972. */
  70973. get: function () {
  70974. return this._audioEnabled;
  70975. },
  70976. enumerable: true,
  70977. configurable: true
  70978. });
  70979. Object.defineProperty(AudioSceneComponent.prototype, "headphone", {
  70980. /**
  70981. * Gets whether audio is outputing to headphone or not.
  70982. * Please use the according Switch methods to change output.
  70983. */
  70984. get: function () {
  70985. return this._headphone;
  70986. },
  70987. enumerable: true,
  70988. configurable: true
  70989. });
  70990. /**
  70991. * Registers the component in a given scene
  70992. */
  70993. AudioSceneComponent.prototype.register = function () {
  70994. this.scene._afterRenderStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDER_AUDIO, this, this._afterRender);
  70995. };
  70996. /**
  70997. * Rebuilds the elements related to this component in case of
  70998. * context lost for instance.
  70999. */
  71000. AudioSceneComponent.prototype.rebuild = function () {
  71001. // Nothing to do here. (Not rendering related)
  71002. };
  71003. /**
  71004. * Serializes the component data to the specified json object
  71005. * @param serializationObject The object to serialize to
  71006. */
  71007. AudioSceneComponent.prototype.serialize = function (serializationObject) {
  71008. serializationObject.sounds = [];
  71009. if (this.scene.soundTracks) {
  71010. for (var index = 0; index < this.scene.soundTracks.length; index++) {
  71011. var soundtrack = this.scene.soundTracks[index];
  71012. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  71013. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  71014. }
  71015. }
  71016. }
  71017. };
  71018. /**
  71019. * Adds all the element from the container to the scene
  71020. * @param container the container holding the elements
  71021. */
  71022. AudioSceneComponent.prototype.addFromContainer = function (container) {
  71023. var _this = this;
  71024. if (!container.sounds) {
  71025. return;
  71026. }
  71027. container.sounds.forEach(function (sound) {
  71028. sound.play();
  71029. sound.autoplay = true;
  71030. _this.scene.mainSoundTrack.AddSound(sound);
  71031. });
  71032. };
  71033. /**
  71034. * Removes all the elements in the container from the scene
  71035. * @param container contains the elements to remove
  71036. */
  71037. AudioSceneComponent.prototype.removeFromContainer = function (container) {
  71038. var _this = this;
  71039. if (!container.sounds) {
  71040. return;
  71041. }
  71042. container.sounds.forEach(function (sound) {
  71043. sound.stop();
  71044. sound.autoplay = false;
  71045. _this.scene.mainSoundTrack.RemoveSound(sound);
  71046. });
  71047. };
  71048. /**
  71049. * Disposes the component and the associated ressources.
  71050. */
  71051. AudioSceneComponent.prototype.dispose = function () {
  71052. var scene = this.scene;
  71053. if (scene._mainSoundTrack) {
  71054. scene.mainSoundTrack.dispose();
  71055. }
  71056. if (scene.soundTracks) {
  71057. for (var scIndex = 0; scIndex < scene.soundTracks.length; scIndex++) {
  71058. scene.soundTracks[scIndex].dispose();
  71059. }
  71060. }
  71061. };
  71062. /**
  71063. * Disables audio in the associated scene.
  71064. */
  71065. AudioSceneComponent.prototype.disableAudio = function () {
  71066. var scene = this.scene;
  71067. this._audioEnabled = false;
  71068. var i;
  71069. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71070. scene.mainSoundTrack.soundCollection[i].pause();
  71071. }
  71072. if (scene.soundTracks) {
  71073. for (i = 0; i < scene.soundTracks.length; i++) {
  71074. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71075. scene.soundTracks[i].soundCollection[j].pause();
  71076. }
  71077. }
  71078. }
  71079. };
  71080. /**
  71081. * Enables audio in the associated scene.
  71082. */
  71083. AudioSceneComponent.prototype.enableAudio = function () {
  71084. var scene = this.scene;
  71085. this._audioEnabled = true;
  71086. var i;
  71087. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71088. if (scene.mainSoundTrack.soundCollection[i].isPaused) {
  71089. scene.mainSoundTrack.soundCollection[i].play();
  71090. }
  71091. }
  71092. if (scene.soundTracks) {
  71093. for (i = 0; i < scene.soundTracks.length; i++) {
  71094. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71095. if (scene.soundTracks[i].soundCollection[j].isPaused) {
  71096. scene.soundTracks[i].soundCollection[j].play();
  71097. }
  71098. }
  71099. }
  71100. }
  71101. };
  71102. /**
  71103. * Switch audio to headphone output.
  71104. */
  71105. AudioSceneComponent.prototype.switchAudioModeForHeadphones = function () {
  71106. var scene = this.scene;
  71107. this._headphone = true;
  71108. scene.mainSoundTrack.switchPanningModelToHRTF();
  71109. if (scene.soundTracks) {
  71110. for (var i = 0; i < scene.soundTracks.length; i++) {
  71111. scene.soundTracks[i].switchPanningModelToHRTF();
  71112. }
  71113. }
  71114. };
  71115. /**
  71116. * Switch audio to normal speakers.
  71117. */
  71118. AudioSceneComponent.prototype.switchAudioModeForNormalSpeakers = function () {
  71119. var scene = this.scene;
  71120. this._headphone = false;
  71121. scene.mainSoundTrack.switchPanningModelToEqualPower();
  71122. if (scene.soundTracks) {
  71123. for (var i = 0; i < scene.soundTracks.length; i++) {
  71124. scene.soundTracks[i].switchPanningModelToEqualPower();
  71125. }
  71126. }
  71127. };
  71128. AudioSceneComponent.prototype._afterRender = function () {
  71129. var scene = this.scene;
  71130. if (!this._audioEnabled || !scene._mainSoundTrack || !scene.soundTracks || (scene._mainSoundTrack.soundCollection.length === 0 && scene.soundTracks.length === 1)) {
  71131. return;
  71132. }
  71133. var listeningCamera;
  71134. var audioEngine = BABYLON.Engine.audioEngine;
  71135. if (scene.activeCameras.length > 0) {
  71136. listeningCamera = scene.activeCameras[0];
  71137. }
  71138. else {
  71139. listeningCamera = scene.activeCamera;
  71140. }
  71141. if (listeningCamera && audioEngine.audioContext) {
  71142. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  71143. // for VR cameras
  71144. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  71145. listeningCamera = listeningCamera.rigCameras[0];
  71146. }
  71147. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  71148. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  71149. cameraDirection.normalize();
  71150. // To avoid some errors on GearVR
  71151. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  71152. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  71153. }
  71154. var i;
  71155. for (i = 0; i < scene.mainSoundTrack.soundCollection.length; i++) {
  71156. var sound = scene.mainSoundTrack.soundCollection[i];
  71157. if (sound.useCustomAttenuation) {
  71158. sound.updateDistanceFromListener();
  71159. }
  71160. }
  71161. if (scene.soundTracks) {
  71162. for (i = 0; i < scene.soundTracks.length; i++) {
  71163. for (var j = 0; j < scene.soundTracks[i].soundCollection.length; j++) {
  71164. sound = scene.soundTracks[i].soundCollection[j];
  71165. if (sound.useCustomAttenuation) {
  71166. sound.updateDistanceFromListener();
  71167. }
  71168. }
  71169. }
  71170. }
  71171. }
  71172. };
  71173. return AudioSceneComponent;
  71174. }());
  71175. BABYLON.AudioSceneComponent = AudioSceneComponent;
  71176. })(BABYLON || (BABYLON = {}));
  71177. //# sourceMappingURL=babylon.audioSceneComponent.js.map
  71178. var BABYLON;
  71179. (function (BABYLON) {
  71180. /**
  71181. * This defines an action helpful to play a defined sound on a triggered action.
  71182. */
  71183. var PlaySoundAction = /** @class */ (function (_super) {
  71184. __extends(PlaySoundAction, _super);
  71185. /**
  71186. * Instantiate the action
  71187. * @param triggerOptions defines the trigger options
  71188. * @param sound defines the sound to play
  71189. * @param condition defines the trigger related conditions
  71190. */
  71191. function PlaySoundAction(triggerOptions, sound, condition) {
  71192. var _this = _super.call(this, triggerOptions, condition) || this;
  71193. _this._sound = sound;
  71194. return _this;
  71195. }
  71196. /** @hidden */
  71197. PlaySoundAction.prototype._prepare = function () {
  71198. };
  71199. /**
  71200. * Execute the action and play the sound.
  71201. */
  71202. PlaySoundAction.prototype.execute = function () {
  71203. if (this._sound !== undefined)
  71204. this._sound.play();
  71205. };
  71206. /**
  71207. * Serializes the actions and its related information.
  71208. * @param parent defines the object to serialize in
  71209. * @returns the serialized object
  71210. */
  71211. PlaySoundAction.prototype.serialize = function (parent) {
  71212. return _super.prototype._serialize.call(this, {
  71213. name: "PlaySoundAction",
  71214. properties: [{ name: "sound", value: this._sound.name }]
  71215. }, parent);
  71216. };
  71217. return PlaySoundAction;
  71218. }(BABYLON.Action));
  71219. BABYLON.PlaySoundAction = PlaySoundAction;
  71220. /**
  71221. * This defines an action helpful to stop a defined sound on a triggered action.
  71222. */
  71223. var StopSoundAction = /** @class */ (function (_super) {
  71224. __extends(StopSoundAction, _super);
  71225. /**
  71226. * Instantiate the action
  71227. * @param triggerOptions defines the trigger options
  71228. * @param sound defines the sound to stop
  71229. * @param condition defines the trigger related conditions
  71230. */
  71231. function StopSoundAction(triggerOptions, sound, condition) {
  71232. var _this = _super.call(this, triggerOptions, condition) || this;
  71233. _this._sound = sound;
  71234. return _this;
  71235. }
  71236. /** @hidden */
  71237. StopSoundAction.prototype._prepare = function () {
  71238. };
  71239. /**
  71240. * Execute the action and stop the sound.
  71241. */
  71242. StopSoundAction.prototype.execute = function () {
  71243. if (this._sound !== undefined)
  71244. this._sound.stop();
  71245. };
  71246. /**
  71247. * Serializes the actions and its related information.
  71248. * @param parent defines the object to serialize in
  71249. * @returns the serialized object
  71250. */
  71251. StopSoundAction.prototype.serialize = function (parent) {
  71252. return _super.prototype._serialize.call(this, {
  71253. name: "StopSoundAction",
  71254. properties: [{ name: "sound", value: this._sound.name }]
  71255. }, parent);
  71256. };
  71257. return StopSoundAction;
  71258. }(BABYLON.Action));
  71259. BABYLON.StopSoundAction = StopSoundAction;
  71260. })(BABYLON || (BABYLON = {}));
  71261. //# sourceMappingURL=babylon.directAudioActions.js.map
  71262. var BABYLON;
  71263. (function (BABYLON) {
  71264. /**
  71265. * Class for creating a cube texture
  71266. */
  71267. var CubeTexture = /** @class */ (function (_super) {
  71268. __extends(CubeTexture, _super);
  71269. /**
  71270. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  71271. * as prefiltered data.
  71272. * @param rootUrl defines the url of the texture or the root name of the six images
  71273. * @param scene defines the scene the texture is attached to
  71274. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  71275. * @param noMipmap defines if mipmaps should be created or not
  71276. * @param files defines the six files to load for the different faces
  71277. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  71278. * @param onError defines a callback triggered in case of error during load
  71279. * @param format defines the internal format to use for the texture once loaded
  71280. * @param prefiltered defines whether or not the texture is created from prefiltered data
  71281. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  71282. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71283. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71284. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71285. * @return the cube texture
  71286. */
  71287. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  71288. if (extensions === void 0) { extensions = null; }
  71289. if (noMipmap === void 0) { noMipmap = false; }
  71290. if (files === void 0) { files = null; }
  71291. if (onLoad === void 0) { onLoad = null; }
  71292. if (onError === void 0) { onError = null; }
  71293. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71294. if (prefiltered === void 0) { prefiltered = false; }
  71295. if (forcedExtension === void 0) { forcedExtension = null; }
  71296. if (createPolynomials === void 0) { createPolynomials = false; }
  71297. if (lodScale === void 0) { lodScale = 0.8; }
  71298. if (lodOffset === void 0) { lodOffset = 0; }
  71299. var _this = _super.call(this, scene) || this;
  71300. /**
  71301. * Gets or sets the center of the bounding box associated with the cube texture.
  71302. * It must define where the camera used to render the texture was set
  71303. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71304. */
  71305. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71306. _this._rotationY = 0;
  71307. /** @hidden */
  71308. _this._prefiltered = false;
  71309. _this.name = rootUrl;
  71310. _this.url = rootUrl;
  71311. _this._noMipmap = noMipmap;
  71312. _this.hasAlpha = false;
  71313. _this._format = format;
  71314. _this.isCube = true;
  71315. _this._textureMatrix = BABYLON.Matrix.Identity();
  71316. _this._createPolynomials = createPolynomials;
  71317. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  71318. if (!rootUrl && !files) {
  71319. return _this;
  71320. }
  71321. var lastDot = rootUrl.lastIndexOf(".");
  71322. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  71323. var isDDS = (extension === ".dds");
  71324. var isEnv = (extension === ".env");
  71325. if (isEnv) {
  71326. _this.gammaSpace = false;
  71327. _this._prefiltered = false;
  71328. }
  71329. else {
  71330. _this._prefiltered = prefiltered;
  71331. if (prefiltered) {
  71332. _this.gammaSpace = false;
  71333. }
  71334. }
  71335. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  71336. if (!files) {
  71337. if (!isEnv && !isDDS && !extensions) {
  71338. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  71339. }
  71340. files = [];
  71341. if (extensions) {
  71342. for (var index = 0; index < extensions.length; index++) {
  71343. files.push(rootUrl + extensions[index]);
  71344. }
  71345. }
  71346. }
  71347. _this._files = files;
  71348. if (!_this._texture) {
  71349. if (!scene.useDelayedTextureLoading) {
  71350. if (prefiltered) {
  71351. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  71352. }
  71353. else {
  71354. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  71355. }
  71356. }
  71357. else {
  71358. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  71359. }
  71360. }
  71361. else if (onLoad) {
  71362. if (_this._texture.isReady) {
  71363. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  71364. }
  71365. else {
  71366. _this._texture.onLoadedObservable.add(onLoad);
  71367. }
  71368. }
  71369. return _this;
  71370. }
  71371. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  71372. /**
  71373. * Returns the bounding box size
  71374. * @see http://doc.babylonjs.com/how_to/reflect#using-local-cubemap-mode
  71375. */
  71376. get: function () {
  71377. return this._boundingBoxSize;
  71378. },
  71379. /**
  71380. * Gets or sets the size of the bounding box associated with the cube texture
  71381. * When defined, the cubemap will switch to local mode
  71382. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71383. * @example https://www.babylonjs-playground.com/#RNASML
  71384. */
  71385. set: function (value) {
  71386. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71387. return;
  71388. }
  71389. this._boundingBoxSize = value;
  71390. var scene = this.getScene();
  71391. if (scene) {
  71392. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71393. }
  71394. },
  71395. enumerable: true,
  71396. configurable: true
  71397. });
  71398. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  71399. /**
  71400. * Gets texture matrix rotation angle around Y axis radians.
  71401. */
  71402. get: function () {
  71403. return this._rotationY;
  71404. },
  71405. /**
  71406. * Sets texture matrix rotation angle around Y axis in radians.
  71407. */
  71408. set: function (value) {
  71409. this._rotationY = value;
  71410. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  71411. },
  71412. enumerable: true,
  71413. configurable: true
  71414. });
  71415. /**
  71416. * Creates a cube texture from an array of image urls
  71417. * @param files defines an array of image urls
  71418. * @param scene defines the hosting scene
  71419. * @param noMipmap specifies if mip maps are not used
  71420. * @returns a cube texture
  71421. */
  71422. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  71423. var rootUrlKey = "";
  71424. files.forEach(function (url) { return rootUrlKey += url; });
  71425. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  71426. };
  71427. /**
  71428. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  71429. * @param url defines the url of the prefiltered texture
  71430. * @param scene defines the scene the texture is attached to
  71431. * @param forcedExtension defines the extension of the file if different from the url
  71432. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  71433. * @return the prefiltered texture
  71434. */
  71435. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  71436. if (forcedExtension === void 0) { forcedExtension = null; }
  71437. if (createPolynomials === void 0) { createPolynomials = true; }
  71438. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  71439. };
  71440. /**
  71441. * Delays loading of the cube texture
  71442. */
  71443. CubeTexture.prototype.delayLoad = function () {
  71444. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  71445. return;
  71446. }
  71447. var scene = this.getScene();
  71448. if (!scene) {
  71449. return;
  71450. }
  71451. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  71452. this._texture = this._getFromCache(this.url, this._noMipmap);
  71453. if (!this._texture) {
  71454. if (this._prefiltered) {
  71455. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  71456. }
  71457. else {
  71458. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  71459. }
  71460. }
  71461. };
  71462. /**
  71463. * Returns the reflection texture matrix
  71464. * @returns the reflection texture matrix
  71465. */
  71466. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  71467. return this._textureMatrix;
  71468. };
  71469. /**
  71470. * Sets the reflection texture matrix
  71471. * @param value Reflection texture matrix
  71472. */
  71473. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  71474. this._textureMatrix = value;
  71475. };
  71476. /**
  71477. * Parses text to create a cube texture
  71478. * @param parsedTexture define the serialized text to read from
  71479. * @param scene defines the hosting scene
  71480. * @param rootUrl defines the root url of the cube texture
  71481. * @returns a cube texture
  71482. */
  71483. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  71484. var texture = BABYLON.SerializationHelper.Parse(function () {
  71485. var prefiltered = false;
  71486. if (parsedTexture.prefiltered) {
  71487. prefiltered = parsedTexture.prefiltered;
  71488. }
  71489. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  71490. }, parsedTexture, scene);
  71491. // Local Cubemaps
  71492. if (parsedTexture.boundingBoxPosition) {
  71493. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  71494. }
  71495. if (parsedTexture.boundingBoxSize) {
  71496. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  71497. }
  71498. // Animations
  71499. if (parsedTexture.animations) {
  71500. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  71501. var parsedAnimation = parsedTexture.animations[animationIndex];
  71502. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  71503. }
  71504. }
  71505. return texture;
  71506. };
  71507. /**
  71508. * Makes a clone, or deep copy, of the cube texture
  71509. * @returns a new cube texture
  71510. */
  71511. CubeTexture.prototype.clone = function () {
  71512. var _this = this;
  71513. return BABYLON.SerializationHelper.Clone(function () {
  71514. var scene = _this.getScene();
  71515. if (!scene) {
  71516. return _this;
  71517. }
  71518. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  71519. }, this);
  71520. };
  71521. __decorate([
  71522. BABYLON.serialize("rotationY")
  71523. ], CubeTexture.prototype, "rotationY", null);
  71524. return CubeTexture;
  71525. }(BABYLON.BaseTexture));
  71526. BABYLON.CubeTexture = CubeTexture;
  71527. })(BABYLON || (BABYLON = {}));
  71528. //# sourceMappingURL=babylon.cubeTexture.js.map
  71529. var BABYLON;
  71530. (function (BABYLON) {
  71531. /**
  71532. * Raw cube texture where the raw buffers are passed in
  71533. */
  71534. var RawCubeTexture = /** @class */ (function (_super) {
  71535. __extends(RawCubeTexture, _super);
  71536. /**
  71537. * Creates a cube texture where the raw buffers are passed in.
  71538. * @param scene defines the scene the texture is attached to
  71539. * @param data defines the array of data to use to create each face
  71540. * @param size defines the size of the textures
  71541. * @param format defines the format of the data
  71542. * @param type defines the type of the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  71543. * @param generateMipMaps defines if the engine should generate the mip levels
  71544. * @param invertY defines if data must be stored with Y axis inverted
  71545. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  71546. * @param compression defines the compression used (null by default)
  71547. */
  71548. function RawCubeTexture(scene, data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  71549. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71550. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71551. if (generateMipMaps === void 0) { generateMipMaps = false; }
  71552. if (invertY === void 0) { invertY = false; }
  71553. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71554. if (compression === void 0) { compression = null; }
  71555. var _this = _super.call(this, "", scene) || this;
  71556. _this._texture = scene.getEngine().createRawCubeTexture(data, size, format, type, generateMipMaps, invertY, samplingMode, compression);
  71557. return _this;
  71558. }
  71559. /**
  71560. * Updates the raw cube texture.
  71561. * @param data defines the data to store
  71562. * @param format defines the data format
  71563. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  71564. * @param invertY defines if data must be stored with Y axis inverted
  71565. * @param compression defines the compression used (null by default)
  71566. * @param level defines which level of the texture to update
  71567. */
  71568. RawCubeTexture.prototype.update = function (data, format, type, invertY, compression, level) {
  71569. if (compression === void 0) { compression = null; }
  71570. if (level === void 0) { level = 0; }
  71571. this._texture.getEngine().updateRawCubeTexture(this._texture, data, format, type, invertY, compression);
  71572. };
  71573. /**
  71574. * Updates a raw cube texture with RGBD encoded data.
  71575. * @param data defines the array of data [mipmap][face] to use to create each face
  71576. * @param sphericalPolynomial defines the spherical polynomial for irradiance
  71577. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  71578. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  71579. * @returns a promsie that resolves when the operation is complete
  71580. */
  71581. RawCubeTexture.prototype.updateRGBDAsync = function (data, sphericalPolynomial, lodScale, lodOffset) {
  71582. if (sphericalPolynomial === void 0) { sphericalPolynomial = null; }
  71583. if (lodScale === void 0) { lodScale = 0.8; }
  71584. if (lodOffset === void 0) { lodOffset = 0; }
  71585. return RawCubeTexture._UpdateRGBDAsync(this._texture, data, sphericalPolynomial, lodScale, lodOffset);
  71586. };
  71587. /**
  71588. * Clones the raw cube texture.
  71589. * @return a new cube texture
  71590. */
  71591. RawCubeTexture.prototype.clone = function () {
  71592. var _this = this;
  71593. return BABYLON.SerializationHelper.Clone(function () {
  71594. var scene = _this.getScene();
  71595. var internalTexture = _this._texture;
  71596. var texture = new RawCubeTexture(scene, internalTexture._bufferViewArray, internalTexture.width, internalTexture.format, internalTexture.type, internalTexture.generateMipMaps, internalTexture.invertY, internalTexture.samplingMode, internalTexture._compression);
  71597. if (internalTexture.dataSource === BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD) {
  71598. texture.updateRGBDAsync(internalTexture._bufferViewArrayArray, internalTexture._sphericalPolynomial, internalTexture._lodGenerationScale, internalTexture._lodGenerationOffset);
  71599. }
  71600. return texture;
  71601. }, this);
  71602. };
  71603. /** @hidden */
  71604. RawCubeTexture._UpdateRGBDAsync = function (internalTexture, data, sphericalPolynomial, lodScale, lodOffset) {
  71605. internalTexture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBERAW_RGBD;
  71606. internalTexture._bufferViewArrayArray = data;
  71607. internalTexture._lodGenerationScale = lodScale;
  71608. internalTexture._lodGenerationOffset = lodOffset;
  71609. internalTexture._sphericalPolynomial = sphericalPolynomial;
  71610. return BABYLON.EnvironmentTextureTools.UploadLevelsAsync(internalTexture, data).then(function () {
  71611. internalTexture.isReady = true;
  71612. });
  71613. };
  71614. return RawCubeTexture;
  71615. }(BABYLON.CubeTexture));
  71616. BABYLON.RawCubeTexture = RawCubeTexture;
  71617. })(BABYLON || (BABYLON = {}));
  71618. //# sourceMappingURL=babylon.rawCubeTexture.js.map
  71619. var BABYLON;
  71620. (function (BABYLON) {
  71621. /**
  71622. * This Helps creating a texture that will be created from a camera in your scene.
  71623. * It is basically a dynamic texture that could be used to create special effects for instance.
  71624. * Actually, It is the base of lot of effects in the framework like post process, shadows, effect layers and rendering pipelines...
  71625. */
  71626. var RenderTargetTexture = /** @class */ (function (_super) {
  71627. __extends(RenderTargetTexture, _super);
  71628. /**
  71629. * Instantiate a render target texture. This is mainly used to render of screen the scene to for instance apply post processse
  71630. * or used a shadow, depth texture...
  71631. * @param name The friendly name of the texture
  71632. * @param size The size of the RTT (number if square, or {width: number, height:number} or {ratio:} to define a ratio from the main scene)
  71633. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  71634. * @param generateMipMaps True if mip maps need to be generated after render.
  71635. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  71636. * @param type The type of the buffer in the RTT (int, half float, float...)
  71637. * @param isCube True if a cube texture needs to be created
  71638. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  71639. * @param generateDepthBuffer True to generate a depth buffer
  71640. * @param generateStencilBuffer True to generate a stencil buffer
  71641. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  71642. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  71643. */
  71644. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  71645. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  71646. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  71647. if (isCube === void 0) { isCube = false; }
  71648. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  71649. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  71650. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  71651. if (isMulti === void 0) { isMulti = false; }
  71652. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  71653. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  71654. _this.isCube = isCube;
  71655. /**
  71656. * Define if particles should be rendered in your texture.
  71657. */
  71658. _this.renderParticles = true;
  71659. /**
  71660. * Define if sprites should be rendered in your texture.
  71661. */
  71662. _this.renderSprites = false;
  71663. /**
  71664. * Override the default coordinates mode to projection for RTT as it is the most common case for rendered textures.
  71665. */
  71666. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  71667. /**
  71668. * Define if the camera viewport should be respected while rendering the texture or if the render should be done to the entire texture.
  71669. */
  71670. _this.ignoreCameraViewport = false;
  71671. /**
  71672. * An event triggered when the texture is unbind.
  71673. */
  71674. _this.onBeforeBindObservable = new BABYLON.Observable();
  71675. /**
  71676. * An event triggered when the texture is unbind.
  71677. */
  71678. _this.onAfterUnbindObservable = new BABYLON.Observable();
  71679. /**
  71680. * An event triggered before rendering the texture
  71681. */
  71682. _this.onBeforeRenderObservable = new BABYLON.Observable();
  71683. /**
  71684. * An event triggered after rendering the texture
  71685. */
  71686. _this.onAfterRenderObservable = new BABYLON.Observable();
  71687. /**
  71688. * An event triggered after the texture clear
  71689. */
  71690. _this.onClearObservable = new BABYLON.Observable();
  71691. _this._currentRefreshId = -1;
  71692. _this._refreshRate = 1;
  71693. _this._samples = 1;
  71694. /**
  71695. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  71696. * It must define where the camera used to render the texture is set
  71697. */
  71698. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  71699. scene = _this.getScene();
  71700. if (!scene) {
  71701. return _this;
  71702. }
  71703. _this.renderList = new Array();
  71704. _this._engine = scene.getEngine();
  71705. _this.name = name;
  71706. _this.isRenderTarget = true;
  71707. _this._initialSizeParameter = size;
  71708. _this._processSizeParameter(size);
  71709. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  71710. });
  71711. _this._generateMipMaps = generateMipMaps ? true : false;
  71712. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  71713. // Rendering groups
  71714. _this._renderingManager = new BABYLON.RenderingManager(scene);
  71715. _this._renderingManager._useSceneAutoClearSetup = true;
  71716. if (isMulti) {
  71717. return _this;
  71718. }
  71719. _this._renderTargetOptions = {
  71720. generateMipMaps: generateMipMaps,
  71721. type: type,
  71722. format: format,
  71723. samplingMode: samplingMode,
  71724. generateDepthBuffer: generateDepthBuffer,
  71725. generateStencilBuffer: generateStencilBuffer
  71726. };
  71727. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  71728. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71729. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  71730. }
  71731. if (isCube) {
  71732. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  71733. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  71734. _this._textureMatrix = BABYLON.Matrix.Identity();
  71735. }
  71736. else {
  71737. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  71738. }
  71739. return _this;
  71740. }
  71741. Object.defineProperty(RenderTargetTexture.prototype, "renderList", {
  71742. /**
  71743. * Use this list to define the list of mesh you want to render.
  71744. */
  71745. get: function () {
  71746. return this._renderList;
  71747. },
  71748. set: function (value) {
  71749. this._renderList = value;
  71750. if (this._renderList) {
  71751. this._hookArray(this._renderList);
  71752. }
  71753. },
  71754. enumerable: true,
  71755. configurable: true
  71756. });
  71757. RenderTargetTexture.prototype._hookArray = function (array) {
  71758. var _this = this;
  71759. var oldPush = array.push;
  71760. array.push = function () {
  71761. var items = [];
  71762. for (var _i = 0; _i < arguments.length; _i++) {
  71763. items[_i] = arguments[_i];
  71764. }
  71765. var wasEmpty = array.length === 0;
  71766. var result = oldPush.apply(array, items);
  71767. if (wasEmpty) {
  71768. _this.getScene().meshes.forEach(function (mesh) {
  71769. mesh._markSubMeshesAsLightDirty();
  71770. });
  71771. }
  71772. return result;
  71773. };
  71774. var oldSplice = array.splice;
  71775. array.splice = function (index, deleteCount) {
  71776. var deleted = oldSplice.apply(array, [index, deleteCount]);
  71777. if (array.length === 0) {
  71778. _this.getScene().meshes.forEach(function (mesh) {
  71779. mesh._markSubMeshesAsLightDirty();
  71780. });
  71781. }
  71782. return deleted;
  71783. };
  71784. };
  71785. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  71786. /**
  71787. * Set a after unbind callback in the texture.
  71788. * This has been kept for backward compatibility and use of onAfterUnbindObservable is recommended.
  71789. */
  71790. set: function (callback) {
  71791. if (this._onAfterUnbindObserver) {
  71792. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  71793. }
  71794. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  71795. },
  71796. enumerable: true,
  71797. configurable: true
  71798. });
  71799. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  71800. /**
  71801. * Set a before render callback in the texture.
  71802. * This has been kept for backward compatibility and use of onBeforeRenderObservable is recommended.
  71803. */
  71804. set: function (callback) {
  71805. if (this._onBeforeRenderObserver) {
  71806. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  71807. }
  71808. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  71809. },
  71810. enumerable: true,
  71811. configurable: true
  71812. });
  71813. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  71814. /**
  71815. * Set a after render callback in the texture.
  71816. * This has been kept for backward compatibility and use of onAfterRenderObservable is recommended.
  71817. */
  71818. set: function (callback) {
  71819. if (this._onAfterRenderObserver) {
  71820. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  71821. }
  71822. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  71823. },
  71824. enumerable: true,
  71825. configurable: true
  71826. });
  71827. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  71828. /**
  71829. * Set a clear callback in the texture.
  71830. * This has been kept for backward compatibility and use of onClearObservable is recommended.
  71831. */
  71832. set: function (callback) {
  71833. if (this._onClearObserver) {
  71834. this.onClearObservable.remove(this._onClearObserver);
  71835. }
  71836. this._onClearObserver = this.onClearObservable.add(callback);
  71837. },
  71838. enumerable: true,
  71839. configurable: true
  71840. });
  71841. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  71842. /**
  71843. * Gets render target creation options that were used.
  71844. */
  71845. get: function () {
  71846. return this._renderTargetOptions;
  71847. },
  71848. enumerable: true,
  71849. configurable: true
  71850. });
  71851. RenderTargetTexture.prototype._onRatioRescale = function () {
  71852. if (this._sizeRatio) {
  71853. this.resize(this._initialSizeParameter);
  71854. }
  71855. };
  71856. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  71857. get: function () {
  71858. return this._boundingBoxSize;
  71859. },
  71860. /**
  71861. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  71862. * When defined, the cubemap will switch to local mode
  71863. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  71864. * @example https://www.babylonjs-playground.com/#RNASML
  71865. */
  71866. set: function (value) {
  71867. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  71868. return;
  71869. }
  71870. this._boundingBoxSize = value;
  71871. var scene = this.getScene();
  71872. if (scene) {
  71873. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  71874. }
  71875. },
  71876. enumerable: true,
  71877. configurable: true
  71878. });
  71879. /**
  71880. * Creates a depth stencil texture.
  71881. * This is only available in WebGL 2 or with the depth texture extension available.
  71882. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  71883. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  71884. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  71885. */
  71886. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  71887. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  71888. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  71889. if (generateStencil === void 0) { generateStencil = false; }
  71890. if (!this.getScene()) {
  71891. return;
  71892. }
  71893. var engine = this.getScene().getEngine();
  71894. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  71895. bilinearFiltering: bilinearFiltering,
  71896. comparisonFunction: comparisonFunction,
  71897. generateStencil: generateStencil,
  71898. isCube: this.isCube
  71899. });
  71900. engine.setFrameBufferDepthStencilTexture(this);
  71901. };
  71902. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  71903. if (size.ratio) {
  71904. this._sizeRatio = size.ratio;
  71905. this._size = {
  71906. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  71907. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  71908. };
  71909. }
  71910. else {
  71911. this._size = size;
  71912. }
  71913. };
  71914. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  71915. /**
  71916. * Define the number of samples to use in case of MSAA.
  71917. * It defaults to one meaning no MSAA has been enabled.
  71918. */
  71919. get: function () {
  71920. return this._samples;
  71921. },
  71922. set: function (value) {
  71923. if (this._samples === value) {
  71924. return;
  71925. }
  71926. var scene = this.getScene();
  71927. if (!scene) {
  71928. return;
  71929. }
  71930. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  71931. },
  71932. enumerable: true,
  71933. configurable: true
  71934. });
  71935. /**
  71936. * Resets the refresh counter of the texture and start bak from scratch.
  71937. * Could be usefull to regenerate the texture if it is setup to render only once.
  71938. */
  71939. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  71940. this._currentRefreshId = -1;
  71941. };
  71942. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  71943. /**
  71944. * Define the refresh rate of the texture or the rendering frequency.
  71945. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  71946. */
  71947. get: function () {
  71948. return this._refreshRate;
  71949. },
  71950. set: function (value) {
  71951. this._refreshRate = value;
  71952. this.resetRefreshCounter();
  71953. },
  71954. enumerable: true,
  71955. configurable: true
  71956. });
  71957. /**
  71958. * Adds a post process to the render target rendering passes.
  71959. * @param postProcess define the post process to add
  71960. */
  71961. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  71962. if (!this._postProcessManager) {
  71963. var scene = this.getScene();
  71964. if (!scene) {
  71965. return;
  71966. }
  71967. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  71968. this._postProcesses = new Array();
  71969. }
  71970. this._postProcesses.push(postProcess);
  71971. this._postProcesses[0].autoClear = false;
  71972. };
  71973. /**
  71974. * Clear all the post processes attached to the render target
  71975. * @param dispose define if the cleared post processesshould also be disposed (false by default)
  71976. */
  71977. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  71978. if (dispose === void 0) { dispose = false; }
  71979. if (!this._postProcesses) {
  71980. return;
  71981. }
  71982. if (dispose) {
  71983. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  71984. var postProcess = _a[_i];
  71985. postProcess.dispose();
  71986. }
  71987. }
  71988. this._postProcesses = [];
  71989. };
  71990. /**
  71991. * Remove one of the post process from the list of attached post processes to the texture
  71992. * @param postProcess define the post process to remove from the list
  71993. */
  71994. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  71995. if (!this._postProcesses) {
  71996. return;
  71997. }
  71998. var index = this._postProcesses.indexOf(postProcess);
  71999. if (index === -1) {
  72000. return;
  72001. }
  72002. this._postProcesses.splice(index, 1);
  72003. if (this._postProcesses.length > 0) {
  72004. this._postProcesses[0].autoClear = false;
  72005. }
  72006. };
  72007. /** @hidden */
  72008. RenderTargetTexture.prototype._shouldRender = function () {
  72009. if (this._currentRefreshId === -1) { // At least render once
  72010. this._currentRefreshId = 1;
  72011. return true;
  72012. }
  72013. if (this.refreshRate === this._currentRefreshId) {
  72014. this._currentRefreshId = 1;
  72015. return true;
  72016. }
  72017. this._currentRefreshId++;
  72018. return false;
  72019. };
  72020. /**
  72021. * Gets the actual render size of the texture.
  72022. * @returns the width of the render size
  72023. */
  72024. RenderTargetTexture.prototype.getRenderSize = function () {
  72025. return this.getRenderWidth();
  72026. };
  72027. /**
  72028. * Gets the actual render width of the texture.
  72029. * @returns the width of the render size
  72030. */
  72031. RenderTargetTexture.prototype.getRenderWidth = function () {
  72032. if (this._size.width) {
  72033. return this._size.width;
  72034. }
  72035. return this._size;
  72036. };
  72037. /**
  72038. * Gets the actual render height of the texture.
  72039. * @returns the height of the render size
  72040. */
  72041. RenderTargetTexture.prototype.getRenderHeight = function () {
  72042. if (this._size.width) {
  72043. return this._size.height;
  72044. }
  72045. return this._size;
  72046. };
  72047. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  72048. /**
  72049. * Get if the texture can be rescaled or not.
  72050. */
  72051. get: function () {
  72052. return true;
  72053. },
  72054. enumerable: true,
  72055. configurable: true
  72056. });
  72057. /**
  72058. * Resize the texture using a ratio.
  72059. * @param ratio the ratio to apply to the texture size in order to compute the new target size
  72060. */
  72061. RenderTargetTexture.prototype.scale = function (ratio) {
  72062. var newSize = this.getRenderSize() * ratio;
  72063. this.resize(newSize);
  72064. };
  72065. /**
  72066. * Get the texture reflection matrix used to rotate/transform the reflection.
  72067. * @returns the reflection matrix
  72068. */
  72069. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  72070. if (this.isCube) {
  72071. return this._textureMatrix;
  72072. }
  72073. return _super.prototype.getReflectionTextureMatrix.call(this);
  72074. };
  72075. /**
  72076. * Resize the texture to a new desired size.
  72077. * Be carrefull as it will recreate all the data in the new texture.
  72078. * @param size Define the new size. It can be:
  72079. * - a number for squared texture,
  72080. * - an object containing { width: number, height: number }
  72081. * - or an object containing a ratio { ratio: number }
  72082. */
  72083. RenderTargetTexture.prototype.resize = function (size) {
  72084. this.releaseInternalTexture();
  72085. var scene = this.getScene();
  72086. if (!scene) {
  72087. return;
  72088. }
  72089. this._processSizeParameter(size);
  72090. if (this.isCube) {
  72091. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  72092. }
  72093. else {
  72094. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  72095. }
  72096. };
  72097. /**
  72098. * Renders all the objects from the render list into the texture.
  72099. * @param useCameraPostProcess Define if camera post processes should be used during the rendering
  72100. * @param dumpForDebug Define if the rendering result should be dumped (copied) for debugging purpose
  72101. */
  72102. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  72103. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  72104. if (dumpForDebug === void 0) { dumpForDebug = false; }
  72105. var scene = this.getScene();
  72106. if (!scene) {
  72107. return;
  72108. }
  72109. var engine = scene.getEngine();
  72110. if (this.useCameraPostProcesses !== undefined) {
  72111. useCameraPostProcess = this.useCameraPostProcesses;
  72112. }
  72113. if (this._waitingRenderList) {
  72114. this.renderList = [];
  72115. for (var index = 0; index < this._waitingRenderList.length; index++) {
  72116. var id = this._waitingRenderList[index];
  72117. var mesh_1 = scene.getMeshByID(id);
  72118. if (mesh_1) {
  72119. this.renderList.push(mesh_1);
  72120. }
  72121. }
  72122. delete this._waitingRenderList;
  72123. }
  72124. // Is predicate defined?
  72125. if (this.renderListPredicate) {
  72126. if (this.renderList) {
  72127. this.renderList.splice(0); // Clear previous renderList
  72128. }
  72129. else {
  72130. this.renderList = [];
  72131. }
  72132. var scene = this.getScene();
  72133. if (!scene) {
  72134. return;
  72135. }
  72136. var sceneMeshes = scene.meshes;
  72137. for (var index = 0; index < sceneMeshes.length; index++) {
  72138. var mesh = sceneMeshes[index];
  72139. if (this.renderListPredicate(mesh)) {
  72140. this.renderList.push(mesh);
  72141. }
  72142. }
  72143. }
  72144. this.onBeforeBindObservable.notifyObservers(this);
  72145. // Set custom projection.
  72146. // Needs to be before binding to prevent changing the aspect ratio.
  72147. var camera;
  72148. if (this.activeCamera) {
  72149. camera = this.activeCamera;
  72150. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72151. if (this.activeCamera !== scene.activeCamera) {
  72152. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  72153. }
  72154. }
  72155. else {
  72156. camera = scene.activeCamera;
  72157. if (camera) {
  72158. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  72159. }
  72160. }
  72161. // Prepare renderingManager
  72162. this._renderingManager.reset();
  72163. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  72164. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  72165. var sceneRenderId = scene.getRenderId();
  72166. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  72167. var mesh = currentRenderList[meshIndex];
  72168. if (mesh) {
  72169. if (!mesh.isReady(this.refreshRate === 0)) {
  72170. this.resetRefreshCounter();
  72171. continue;
  72172. }
  72173. mesh._preActivateForIntermediateRendering(sceneRenderId);
  72174. var isMasked = void 0;
  72175. if (!this.renderList && camera) {
  72176. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  72177. }
  72178. else {
  72179. isMasked = false;
  72180. }
  72181. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  72182. mesh._activate(sceneRenderId);
  72183. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  72184. var subMesh = mesh.subMeshes[subIndex];
  72185. scene._activeIndices.addCount(subMesh.indexCount, false);
  72186. this._renderingManager.dispatch(subMesh, mesh);
  72187. }
  72188. }
  72189. }
  72190. }
  72191. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  72192. var particleSystem = scene.particleSystems[particleIndex];
  72193. var emitter = particleSystem.emitter;
  72194. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  72195. continue;
  72196. }
  72197. if (currentRenderList.indexOf(emitter) >= 0) {
  72198. this._renderingManager.dispatchParticles(particleSystem);
  72199. }
  72200. }
  72201. if (this.isCube) {
  72202. for (var face = 0; face < 6; face++) {
  72203. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72204. scene.incrementRenderId();
  72205. scene.resetCachedMaterial();
  72206. }
  72207. }
  72208. else {
  72209. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  72210. }
  72211. this.onAfterUnbindObservable.notifyObservers(this);
  72212. if (scene.activeCamera) {
  72213. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  72214. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  72215. }
  72216. engine.setViewport(scene.activeCamera.viewport);
  72217. }
  72218. scene.resetCachedMaterial();
  72219. };
  72220. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  72221. var minimum = 128;
  72222. var x = renderDimension * scale;
  72223. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  72224. // Ensure we don't exceed the render dimension (while staying POT)
  72225. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  72226. };
  72227. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72228. var _this = this;
  72229. if (!this._texture) {
  72230. return;
  72231. }
  72232. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  72233. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72234. });
  72235. };
  72236. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  72237. var scene = this.getScene();
  72238. if (!scene) {
  72239. return;
  72240. }
  72241. var engine = scene.getEngine();
  72242. if (!this._texture) {
  72243. return;
  72244. }
  72245. // Bind
  72246. if (this._postProcessManager) {
  72247. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  72248. }
  72249. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  72250. if (this._texture) {
  72251. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  72252. }
  72253. }
  72254. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  72255. // Clear
  72256. if (this.onClearObservable.hasObservers()) {
  72257. this.onClearObservable.notifyObservers(engine);
  72258. }
  72259. else {
  72260. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  72261. }
  72262. if (!this._doNotChangeAspectRatio) {
  72263. scene.updateTransformMatrix(true);
  72264. }
  72265. // Render
  72266. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  72267. if (this._postProcessManager) {
  72268. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  72269. }
  72270. else if (useCameraPostProcess) {
  72271. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  72272. }
  72273. if (!this._doNotChangeAspectRatio) {
  72274. scene.updateTransformMatrix(true);
  72275. }
  72276. // Dump ?
  72277. if (dumpForDebug) {
  72278. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  72279. }
  72280. // Unbind
  72281. if (!this.isCube || faceIndex === 5) {
  72282. if (this.isCube) {
  72283. if (faceIndex === 5) {
  72284. engine.generateMipMapsForCubemap(this._texture);
  72285. }
  72286. }
  72287. this.unbindFrameBuffer(engine, faceIndex);
  72288. }
  72289. else {
  72290. this.onAfterRenderObservable.notifyObservers(faceIndex);
  72291. }
  72292. };
  72293. /**
  72294. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  72295. * This allowed control for front to back rendering or reversly depending of the special needs.
  72296. *
  72297. * @param renderingGroupId The rendering group id corresponding to its index
  72298. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  72299. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  72300. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  72301. */
  72302. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  72303. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  72304. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  72305. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  72306. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  72307. };
  72308. /**
  72309. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  72310. *
  72311. * @param renderingGroupId The rendering group id corresponding to its index
  72312. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  72313. */
  72314. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  72315. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  72316. this._renderingManager._useSceneAutoClearSetup = false;
  72317. };
  72318. /**
  72319. * Clones the texture.
  72320. * @returns the cloned texture
  72321. */
  72322. RenderTargetTexture.prototype.clone = function () {
  72323. var textureSize = this.getSize();
  72324. 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);
  72325. // Base texture
  72326. newTexture.hasAlpha = this.hasAlpha;
  72327. newTexture.level = this.level;
  72328. // RenderTarget Texture
  72329. newTexture.coordinatesMode = this.coordinatesMode;
  72330. if (this.renderList) {
  72331. newTexture.renderList = this.renderList.slice(0);
  72332. }
  72333. return newTexture;
  72334. };
  72335. /**
  72336. * Serialize the texture to a JSON representation we can easily use in the resepective Parse function.
  72337. * @returns The JSON representation of the texture
  72338. */
  72339. RenderTargetTexture.prototype.serialize = function () {
  72340. if (!this.name) {
  72341. return null;
  72342. }
  72343. var serializationObject = _super.prototype.serialize.call(this);
  72344. serializationObject.renderTargetSize = this.getRenderSize();
  72345. serializationObject.renderList = [];
  72346. if (this.renderList) {
  72347. for (var index = 0; index < this.renderList.length; index++) {
  72348. serializationObject.renderList.push(this.renderList[index].id);
  72349. }
  72350. }
  72351. return serializationObject;
  72352. };
  72353. /**
  72354. * This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  72355. */
  72356. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  72357. var objBuffer = this.getInternalTexture();
  72358. var scene = this.getScene();
  72359. if (objBuffer && scene) {
  72360. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  72361. }
  72362. };
  72363. /**
  72364. * Dispose the texture and release its associated resources.
  72365. */
  72366. RenderTargetTexture.prototype.dispose = function () {
  72367. if (this._postProcessManager) {
  72368. this._postProcessManager.dispose();
  72369. this._postProcessManager = null;
  72370. }
  72371. this.clearPostProcesses(true);
  72372. if (this._resizeObserver) {
  72373. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  72374. this._resizeObserver = null;
  72375. }
  72376. this.renderList = null;
  72377. // Remove from custom render targets
  72378. var scene = this.getScene();
  72379. if (!scene) {
  72380. return;
  72381. }
  72382. var index = scene.customRenderTargets.indexOf(this);
  72383. if (index >= 0) {
  72384. scene.customRenderTargets.splice(index, 1);
  72385. }
  72386. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  72387. var camera = _a[_i];
  72388. index = camera.customRenderTargets.indexOf(this);
  72389. if (index >= 0) {
  72390. camera.customRenderTargets.splice(index, 1);
  72391. }
  72392. }
  72393. _super.prototype.dispose.call(this);
  72394. };
  72395. /** @hidden */
  72396. RenderTargetTexture.prototype._rebuild = function () {
  72397. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  72398. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  72399. }
  72400. if (this._postProcessManager) {
  72401. this._postProcessManager._rebuild();
  72402. }
  72403. };
  72404. /**
  72405. * Clear the info related to rendering groups preventing retention point in material dispose.
  72406. */
  72407. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  72408. if (this._renderingManager) {
  72409. this._renderingManager.freeRenderingGroups();
  72410. }
  72411. };
  72412. /**
  72413. * The texture will only be rendered once which can be useful to improve performance if everything in your render is static for instance.
  72414. */
  72415. RenderTargetTexture.REFRESHRATE_RENDER_ONCE = 0;
  72416. /**
  72417. * The texture will only be rendered rendered every frame and is recomended for dynamic contents.
  72418. */
  72419. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  72420. /**
  72421. * The texture will be rendered every 2 frames which could be enough if your dynamic objects are not
  72422. * the central point of your effect and can save a lot of performances.
  72423. */
  72424. RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  72425. return RenderTargetTexture;
  72426. }(BABYLON.Texture));
  72427. BABYLON.RenderTargetTexture = RenderTargetTexture;
  72428. })(BABYLON || (BABYLON = {}));
  72429. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  72430. var BABYLON;
  72431. (function (BABYLON) {
  72432. ;
  72433. /**
  72434. * A multi render target, like a render target provides the ability to render to a texture.
  72435. * Unlike the render target, it can render to several draw buffers in one draw.
  72436. * This is specially interesting in deferred rendering or for any effects requiring more than
  72437. * just one color from a single pass.
  72438. */
  72439. var MultiRenderTarget = /** @class */ (function (_super) {
  72440. __extends(MultiRenderTarget, _super);
  72441. /**
  72442. * Instantiate a new multi render target texture.
  72443. * A multi render target, like a render target provides the ability to render to a texture.
  72444. * Unlike the render target, it can render to several draw buffers in one draw.
  72445. * This is specially interesting in deferred rendering or for any effects requiring more than
  72446. * just one color from a single pass.
  72447. * @param name Define the name of the texture
  72448. * @param size Define the size of the buffers to render to
  72449. * @param count Define the number of target we are rendering into
  72450. * @param scene Define the scene the texture belongs to
  72451. * @param options Define the options used to create the multi render target
  72452. */
  72453. function MultiRenderTarget(name, size, count, scene, options) {
  72454. var _this = this;
  72455. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  72456. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  72457. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  72458. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  72459. _this._engine = scene.getEngine();
  72460. if (!_this.isSupported) {
  72461. _this.dispose();
  72462. return;
  72463. }
  72464. var types = [];
  72465. var samplingModes = [];
  72466. for (var i = 0; i < count; i++) {
  72467. if (options && options.types && options.types[i] !== undefined) {
  72468. types.push(options.types[i]);
  72469. }
  72470. else {
  72471. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  72472. }
  72473. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  72474. samplingModes.push(options.samplingModes[i]);
  72475. }
  72476. else {
  72477. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  72478. }
  72479. }
  72480. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  72481. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  72482. _this._size = size;
  72483. _this._multiRenderTargetOptions = {
  72484. samplingModes: samplingModes,
  72485. generateMipMaps: generateMipMaps,
  72486. generateDepthBuffer: generateDepthBuffer,
  72487. generateStencilBuffer: generateStencilBuffer,
  72488. generateDepthTexture: generateDepthTexture,
  72489. types: types,
  72490. textureCount: count
  72491. };
  72492. _this._createInternalTextures();
  72493. _this._createTextures();
  72494. return _this;
  72495. }
  72496. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  72497. /**
  72498. * Get if draw buffers are currently supported by the used hardware and browser.
  72499. */
  72500. get: function () {
  72501. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  72502. },
  72503. enumerable: true,
  72504. configurable: true
  72505. });
  72506. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  72507. /**
  72508. * Get the list of textures generated by the multi render target.
  72509. */
  72510. get: function () {
  72511. return this._textures;
  72512. },
  72513. enumerable: true,
  72514. configurable: true
  72515. });
  72516. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  72517. /**
  72518. * Get the depth texture generated by the multi render target if options.generateDepthTexture has been set
  72519. */
  72520. get: function () {
  72521. return this._textures[this._textures.length - 1];
  72522. },
  72523. enumerable: true,
  72524. configurable: true
  72525. });
  72526. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  72527. /**
  72528. * Set the wrapping mode on U of all the textures we are rendering to.
  72529. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72530. */
  72531. set: function (wrap) {
  72532. if (this._textures) {
  72533. for (var i = 0; i < this._textures.length; i++) {
  72534. this._textures[i].wrapU = wrap;
  72535. }
  72536. }
  72537. },
  72538. enumerable: true,
  72539. configurable: true
  72540. });
  72541. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  72542. /**
  72543. * Set the wrapping mode on V of all the textures we are rendering to.
  72544. * Can be any of the Texture. (CLAMP_ADDRESSMODE, MIRROR_ADDRESSMODE or WRAP_ADDRESSMODE)
  72545. */
  72546. set: function (wrap) {
  72547. if (this._textures) {
  72548. for (var i = 0; i < this._textures.length; i++) {
  72549. this._textures[i].wrapV = wrap;
  72550. }
  72551. }
  72552. },
  72553. enumerable: true,
  72554. configurable: true
  72555. });
  72556. /** @hidden */
  72557. MultiRenderTarget.prototype._rebuild = function () {
  72558. this.releaseInternalTextures();
  72559. this._createInternalTextures();
  72560. for (var i = 0; i < this._internalTextures.length; i++) {
  72561. var texture = this._textures[i];
  72562. texture._texture = this._internalTextures[i];
  72563. }
  72564. // Keeps references to frame buffer and stencil/depth buffer
  72565. this._texture = this._internalTextures[0];
  72566. };
  72567. MultiRenderTarget.prototype._createInternalTextures = function () {
  72568. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  72569. };
  72570. MultiRenderTarget.prototype._createTextures = function () {
  72571. this._textures = [];
  72572. for (var i = 0; i < this._internalTextures.length; i++) {
  72573. var texture = new BABYLON.Texture(null, this.getScene());
  72574. texture._texture = this._internalTextures[i];
  72575. this._textures.push(texture);
  72576. }
  72577. // Keeps references to frame buffer and stencil/depth buffer
  72578. this._texture = this._internalTextures[0];
  72579. };
  72580. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  72581. /**
  72582. * Define the number of samples used if MSAA is enabled.
  72583. */
  72584. get: function () {
  72585. return this._samples;
  72586. },
  72587. set: function (value) {
  72588. if (this._samples === value) {
  72589. return;
  72590. }
  72591. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  72592. },
  72593. enumerable: true,
  72594. configurable: true
  72595. });
  72596. /**
  72597. * Resize all the textures in the multi render target.
  72598. * Be carrefull as it will recreate all the data in the new texture.
  72599. * @param size Define the new size
  72600. */
  72601. MultiRenderTarget.prototype.resize = function (size) {
  72602. this.releaseInternalTextures();
  72603. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  72604. this._createInternalTextures();
  72605. };
  72606. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  72607. var _this = this;
  72608. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  72609. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  72610. });
  72611. };
  72612. /**
  72613. * Dispose the render targets and their associated resources
  72614. */
  72615. MultiRenderTarget.prototype.dispose = function () {
  72616. this.releaseInternalTextures();
  72617. _super.prototype.dispose.call(this);
  72618. };
  72619. /**
  72620. * Release all the underlying texture used as draw buffers.
  72621. */
  72622. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  72623. if (!this._internalTextures) {
  72624. return;
  72625. }
  72626. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  72627. if (this._internalTextures[i] !== undefined) {
  72628. this._internalTextures[i].dispose();
  72629. this._internalTextures.splice(i, 1);
  72630. }
  72631. }
  72632. };
  72633. return MultiRenderTarget;
  72634. }(BABYLON.RenderTargetTexture));
  72635. BABYLON.MultiRenderTarget = MultiRenderTarget;
  72636. })(BABYLON || (BABYLON = {}));
  72637. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  72638. var BABYLON;
  72639. (function (BABYLON) {
  72640. /**
  72641. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72642. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72643. * You can then easily use it as a reflectionTexture on a flat surface.
  72644. * In case the surface is not a plane, please consider relying on reflection probes.
  72645. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72646. */
  72647. var MirrorTexture = /** @class */ (function (_super) {
  72648. __extends(MirrorTexture, _super);
  72649. /**
  72650. * Instantiates a Mirror Texture.
  72651. * Mirror texture can be used to simulate the view from a mirror in a scene.
  72652. * It will dynamically be rendered every frame to adapt to the camera point of view.
  72653. * You can then easily use it as a reflectionTexture on a flat surface.
  72654. * In case the surface is not a plane, please consider relying on reflection probes.
  72655. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72656. * @param name
  72657. * @param size
  72658. * @param scene
  72659. * @param generateMipMaps
  72660. * @param type
  72661. * @param samplingMode
  72662. * @param generateDepthBuffer
  72663. */
  72664. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  72665. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  72666. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  72667. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  72668. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  72669. _this.scene = scene;
  72670. /**
  72671. * Define the reflection plane we want to use. The mirrorPlane is usually set to the constructed reflector.
  72672. * 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.
  72673. * @see https://doc.babylonjs.com/how_to/reflect#mirrors
  72674. */
  72675. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  72676. _this._transformMatrix = BABYLON.Matrix.Zero();
  72677. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  72678. _this._adaptiveBlurKernel = 0;
  72679. _this._blurKernelX = 0;
  72680. _this._blurKernelY = 0;
  72681. _this._blurRatio = 1.0;
  72682. _this.ignoreCameraViewport = true;
  72683. _this._updateGammaSpace();
  72684. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  72685. _this._updateGammaSpace;
  72686. });
  72687. _this.onBeforeRenderObservable.add(function () {
  72688. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  72689. _this._savedViewMatrix = scene.getViewMatrix();
  72690. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  72691. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  72692. scene.clipPlane = _this.mirrorPlane;
  72693. scene.getEngine().cullBackFaces = false;
  72694. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  72695. });
  72696. _this.onAfterRenderObservable.add(function () {
  72697. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  72698. scene.getEngine().cullBackFaces = true;
  72699. scene._mirroredCameraPosition = null;
  72700. delete scene.clipPlane;
  72701. });
  72702. return _this;
  72703. }
  72704. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  72705. get: function () {
  72706. return this._blurRatio;
  72707. },
  72708. /**
  72709. * Define the blur ratio used to blur the reflection if needed.
  72710. */
  72711. set: function (value) {
  72712. if (this._blurRatio === value) {
  72713. return;
  72714. }
  72715. this._blurRatio = value;
  72716. this._preparePostProcesses();
  72717. },
  72718. enumerable: true,
  72719. configurable: true
  72720. });
  72721. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  72722. /**
  72723. * Define the adaptive blur kernel used to blur the reflection if needed.
  72724. * This will autocompute the closest best match for the `blurKernel`
  72725. */
  72726. set: function (value) {
  72727. this._adaptiveBlurKernel = value;
  72728. this._autoComputeBlurKernel();
  72729. },
  72730. enumerable: true,
  72731. configurable: true
  72732. });
  72733. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  72734. /**
  72735. * Define the blur kernel used to blur the reflection if needed.
  72736. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72737. */
  72738. set: function (value) {
  72739. this.blurKernelX = value;
  72740. this.blurKernelY = value;
  72741. },
  72742. enumerable: true,
  72743. configurable: true
  72744. });
  72745. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  72746. get: function () {
  72747. return this._blurKernelX;
  72748. },
  72749. /**
  72750. * Define the blur kernel on the X Axis used to blur the reflection if needed.
  72751. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72752. */
  72753. set: function (value) {
  72754. if (this._blurKernelX === value) {
  72755. return;
  72756. }
  72757. this._blurKernelX = value;
  72758. this._preparePostProcesses();
  72759. },
  72760. enumerable: true,
  72761. configurable: true
  72762. });
  72763. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  72764. get: function () {
  72765. return this._blurKernelY;
  72766. },
  72767. /**
  72768. * Define the blur kernel on the Y Axis used to blur the reflection if needed.
  72769. * Please consider using `adaptiveBlurKernel` as it could find the closest best value for you.
  72770. */
  72771. set: function (value) {
  72772. if (this._blurKernelY === value) {
  72773. return;
  72774. }
  72775. this._blurKernelY = value;
  72776. this._preparePostProcesses();
  72777. },
  72778. enumerable: true,
  72779. configurable: true
  72780. });
  72781. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  72782. var engine = this.getScene().getEngine();
  72783. var dw = this.getRenderWidth() / engine.getRenderWidth();
  72784. var dh = this.getRenderHeight() / engine.getRenderHeight();
  72785. this.blurKernelX = this._adaptiveBlurKernel * dw;
  72786. this.blurKernelY = this._adaptiveBlurKernel * dh;
  72787. };
  72788. MirrorTexture.prototype._onRatioRescale = function () {
  72789. if (this._sizeRatio) {
  72790. this.resize(this._initialSizeParameter);
  72791. if (!this._adaptiveBlurKernel) {
  72792. this._preparePostProcesses();
  72793. }
  72794. }
  72795. if (this._adaptiveBlurKernel) {
  72796. this._autoComputeBlurKernel();
  72797. }
  72798. };
  72799. MirrorTexture.prototype._updateGammaSpace = function () {
  72800. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  72801. };
  72802. MirrorTexture.prototype._preparePostProcesses = function () {
  72803. this.clearPostProcesses(true);
  72804. if (this._blurKernelX && this._blurKernelY) {
  72805. var engine = this.getScene().getEngine();
  72806. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  72807. 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);
  72808. this._blurX.autoClear = false;
  72809. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  72810. this._blurX.inputTexture = this._texture;
  72811. }
  72812. else {
  72813. this._blurX.alwaysForcePOT = true;
  72814. }
  72815. 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);
  72816. this._blurY.autoClear = false;
  72817. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  72818. this.addPostProcess(this._blurX);
  72819. this.addPostProcess(this._blurY);
  72820. }
  72821. else {
  72822. if (this._blurY) {
  72823. this.removePostProcess(this._blurY);
  72824. this._blurY.dispose();
  72825. this._blurY = null;
  72826. }
  72827. if (this._blurX) {
  72828. this.removePostProcess(this._blurX);
  72829. this._blurX.dispose();
  72830. this._blurX = null;
  72831. }
  72832. }
  72833. };
  72834. /**
  72835. * Clone the mirror texture.
  72836. * @returns the cloned texture
  72837. */
  72838. MirrorTexture.prototype.clone = function () {
  72839. var scene = this.getScene();
  72840. if (!scene) {
  72841. return this;
  72842. }
  72843. var textureSize = this.getSize();
  72844. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  72845. // Base texture
  72846. newTexture.hasAlpha = this.hasAlpha;
  72847. newTexture.level = this.level;
  72848. // Mirror Texture
  72849. newTexture.mirrorPlane = this.mirrorPlane.clone();
  72850. if (this.renderList) {
  72851. newTexture.renderList = this.renderList.slice(0);
  72852. }
  72853. return newTexture;
  72854. };
  72855. /**
  72856. * Serialize the texture to a JSON representation you could use in Parse later on
  72857. * @returns the serialized JSON representation
  72858. */
  72859. MirrorTexture.prototype.serialize = function () {
  72860. if (!this.name) {
  72861. return null;
  72862. }
  72863. var serializationObject = _super.prototype.serialize.call(this);
  72864. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  72865. return serializationObject;
  72866. };
  72867. /**
  72868. * Dispose the texture and release its associated resources.
  72869. */
  72870. MirrorTexture.prototype.dispose = function () {
  72871. _super.prototype.dispose.call(this);
  72872. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  72873. };
  72874. return MirrorTexture;
  72875. }(BABYLON.RenderTargetTexture));
  72876. BABYLON.MirrorTexture = MirrorTexture;
  72877. })(BABYLON || (BABYLON = {}));
  72878. //# sourceMappingURL=babylon.mirrorTexture.js.map
  72879. var BABYLON;
  72880. (function (BABYLON) {
  72881. /**
  72882. * Creates a refraction texture used by refraction channel of the standard material.
  72883. * It is like a mirror but to see through a material.
  72884. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72885. */
  72886. var RefractionTexture = /** @class */ (function (_super) {
  72887. __extends(RefractionTexture, _super);
  72888. /**
  72889. * Creates a refraction texture used by refraction channel of the standard material.
  72890. * It is like a mirror but to see through a material.
  72891. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72892. * @param name Define the texture name
  72893. * @param size Define the size of the underlying texture
  72894. * @param scene Define the scene the refraction belongs to
  72895. * @param generateMipMaps Define if we need to generate mips level for the refraction
  72896. */
  72897. function RefractionTexture(name, size, scene, generateMipMaps) {
  72898. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  72899. /**
  72900. * Define the reflection plane we want to use. The refractionPlane is usually set to the constructed refractor.
  72901. * 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.
  72902. * @see https://doc.babylonjs.com/how_to/reflect#refraction
  72903. */
  72904. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  72905. /**
  72906. * Define how deep under the surface we should see.
  72907. */
  72908. _this.depth = 2.0;
  72909. _this.onBeforeRenderObservable.add(function () {
  72910. scene.clipPlane = _this.refractionPlane;
  72911. });
  72912. _this.onAfterRenderObservable.add(function () {
  72913. delete scene.clipPlane;
  72914. });
  72915. return _this;
  72916. }
  72917. /**
  72918. * Clone the refraction texture.
  72919. * @returns the cloned texture
  72920. */
  72921. RefractionTexture.prototype.clone = function () {
  72922. var scene = this.getScene();
  72923. if (!scene) {
  72924. return this;
  72925. }
  72926. var textureSize = this.getSize();
  72927. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  72928. // Base texture
  72929. newTexture.hasAlpha = this.hasAlpha;
  72930. newTexture.level = this.level;
  72931. // Refraction Texture
  72932. newTexture.refractionPlane = this.refractionPlane.clone();
  72933. if (this.renderList) {
  72934. newTexture.renderList = this.renderList.slice(0);
  72935. }
  72936. newTexture.depth = this.depth;
  72937. return newTexture;
  72938. };
  72939. /**
  72940. * Serialize the texture to a JSON representation you could use in Parse later on
  72941. * @returns the serialized JSON representation
  72942. */
  72943. RefractionTexture.prototype.serialize = function () {
  72944. if (!this.name) {
  72945. return null;
  72946. }
  72947. var serializationObject = _super.prototype.serialize.call(this);
  72948. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  72949. serializationObject.depth = this.depth;
  72950. return serializationObject;
  72951. };
  72952. return RefractionTexture;
  72953. }(BABYLON.RenderTargetTexture));
  72954. BABYLON.RefractionTexture = RefractionTexture;
  72955. })(BABYLON || (BABYLON = {}));
  72956. //# sourceMappingURL=babylon.refractionTexture.js.map
  72957. var BABYLON;
  72958. (function (BABYLON) {
  72959. /**
  72960. * A class extending Texture allowing drawing on a texture
  72961. * @see http://doc.babylonjs.com/how_to/dynamictexture
  72962. */
  72963. var DynamicTexture = /** @class */ (function (_super) {
  72964. __extends(DynamicTexture, _super);
  72965. /**
  72966. * Creates a DynamicTexture
  72967. * @param name defines the name of the texture
  72968. * @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
  72969. * @param scene defines the scene where you want the texture
  72970. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  72971. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  72972. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  72973. */
  72974. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  72975. if (scene === void 0) { scene = null; }
  72976. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  72977. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  72978. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  72979. _this.name = name;
  72980. _this._engine = _this.getScene().getEngine();
  72981. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72982. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72983. _this._generateMipMaps = generateMipMaps;
  72984. if (options.getContext) {
  72985. _this._canvas = options;
  72986. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72987. }
  72988. else {
  72989. _this._canvas = document.createElement("canvas");
  72990. if (options.width || options.width === 0) {
  72991. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  72992. }
  72993. else {
  72994. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  72995. }
  72996. }
  72997. var textureSize = _this.getSize();
  72998. _this._canvas.width = textureSize.width;
  72999. _this._canvas.height = textureSize.height;
  73000. _this._context = _this._canvas.getContext("2d");
  73001. return _this;
  73002. }
  73003. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  73004. /**
  73005. * Gets the current state of canRescale
  73006. */
  73007. get: function () {
  73008. return true;
  73009. },
  73010. enumerable: true,
  73011. configurable: true
  73012. });
  73013. DynamicTexture.prototype._recreate = function (textureSize) {
  73014. this._canvas.width = textureSize.width;
  73015. this._canvas.height = textureSize.height;
  73016. this.releaseInternalTexture();
  73017. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  73018. };
  73019. /**
  73020. * Scales the texture
  73021. * @param ratio the scale factor to apply to both width and height
  73022. */
  73023. DynamicTexture.prototype.scale = function (ratio) {
  73024. var textureSize = this.getSize();
  73025. textureSize.width *= ratio;
  73026. textureSize.height *= ratio;
  73027. this._recreate(textureSize);
  73028. };
  73029. /**
  73030. * Resizes the texture
  73031. * @param width the new width
  73032. * @param height the new height
  73033. */
  73034. DynamicTexture.prototype.scaleTo = function (width, height) {
  73035. var textureSize = this.getSize();
  73036. textureSize.width = width;
  73037. textureSize.height = height;
  73038. this._recreate(textureSize);
  73039. };
  73040. /**
  73041. * Gets the context of the canvas used by the texture
  73042. * @returns the canvas context of the dynamic texture
  73043. */
  73044. DynamicTexture.prototype.getContext = function () {
  73045. return this._context;
  73046. };
  73047. /**
  73048. * Clears the texture
  73049. */
  73050. DynamicTexture.prototype.clear = function () {
  73051. var size = this.getSize();
  73052. this._context.fillRect(0, 0, size.width, size.height);
  73053. };
  73054. /**
  73055. * Updates the texture
  73056. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73057. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  73058. */
  73059. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  73060. if (premulAlpha === void 0) { premulAlpha = false; }
  73061. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  73062. };
  73063. /**
  73064. * Draws text onto the texture
  73065. * @param text defines the text to be drawn
  73066. * @param x defines the placement of the text from the left
  73067. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  73068. * @param font defines the font to be used with font-style, font-size, font-name
  73069. * @param color defines the color used for the text
  73070. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  73071. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  73072. * @param update defines whether texture is immediately update (default is true)
  73073. */
  73074. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  73075. if (update === void 0) { update = true; }
  73076. var size = this.getSize();
  73077. if (clearColor) {
  73078. this._context.fillStyle = clearColor;
  73079. this._context.fillRect(0, 0, size.width, size.height);
  73080. }
  73081. this._context.font = font;
  73082. if (x === null || x === undefined) {
  73083. var textSize = this._context.measureText(text);
  73084. x = (size.width - textSize.width) / 2;
  73085. }
  73086. if (y === null || y === undefined) {
  73087. var fontSize = parseInt((font.replace(/\D/g, '')));
  73088. y = (size.height / 2) + (fontSize / 3.65);
  73089. }
  73090. this._context.fillStyle = color;
  73091. this._context.fillText(text, x, y);
  73092. if (update) {
  73093. this.update(invertY);
  73094. }
  73095. };
  73096. /**
  73097. * Clones the texture
  73098. * @returns the clone of the texture.
  73099. */
  73100. DynamicTexture.prototype.clone = function () {
  73101. var scene = this.getScene();
  73102. if (!scene) {
  73103. return this;
  73104. }
  73105. var textureSize = this.getSize();
  73106. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  73107. // Base texture
  73108. newTexture.hasAlpha = this.hasAlpha;
  73109. newTexture.level = this.level;
  73110. // Dynamic Texture
  73111. newTexture.wrapU = this.wrapU;
  73112. newTexture.wrapV = this.wrapV;
  73113. return newTexture;
  73114. };
  73115. /**
  73116. * Serializes the dynamic texture. The scene should be ready before the dynamic texture is serialized
  73117. * @returns a serialized dynamic texture object
  73118. */
  73119. DynamicTexture.prototype.serialize = function () {
  73120. var scene = this.getScene();
  73121. if (scene && !scene.isReady()) {
  73122. BABYLON.Tools.Warn("The scene must be ready before serializing the dynamic texture");
  73123. }
  73124. var serializationObject = _super.prototype.serialize.call(this);
  73125. serializationObject.base64String = this._canvas.toDataURL();
  73126. serializationObject.invertY = this._invertY;
  73127. serializationObject.samplingMode = this.samplingMode;
  73128. return serializationObject;
  73129. };
  73130. /** @hidden */
  73131. DynamicTexture.prototype._rebuild = function () {
  73132. this.update();
  73133. };
  73134. return DynamicTexture;
  73135. }(BABYLON.Texture));
  73136. BABYLON.DynamicTexture = DynamicTexture;
  73137. })(BABYLON || (BABYLON = {}));
  73138. //# sourceMappingURL=babylon.dynamicTexture.js.map
  73139. var BABYLON;
  73140. (function (BABYLON) {
  73141. /**
  73142. * If you want to display a video in your scene, this is the special texture for that.
  73143. * This special texture works similar to other textures, with the exception of a few parameters.
  73144. * @see https://doc.babylonjs.com/how_to/video_texture
  73145. */
  73146. var VideoTexture = /** @class */ (function (_super) {
  73147. __extends(VideoTexture, _super);
  73148. /**
  73149. * Creates a video texture.
  73150. * If you want to display a video in your scene, this is the special texture for that.
  73151. * This special texture works similar to other textures, with the exception of a few parameters.
  73152. * @see https://doc.babylonjs.com/how_to/video_texture
  73153. * @param name optional name, will detect from video source, if not defined
  73154. * @param src can be used to provide an url, array of urls or an already setup HTML video element.
  73155. * @param scene is obviously the current scene.
  73156. * @param generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  73157. * @param invertY is false by default but can be used to invert video on Y axis
  73158. * @param samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  73159. * @param settings allows finer control over video usage
  73160. */
  73161. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  73162. if (generateMipMaps === void 0) { generateMipMaps = false; }
  73163. if (invertY === void 0) { invertY = false; }
  73164. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73165. if (settings === void 0) { settings = {
  73166. autoPlay: true,
  73167. loop: true,
  73168. autoUpdateTexture: true,
  73169. }; }
  73170. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73171. _this._onUserActionRequestedObservable = null;
  73172. _this._stillImageCaptured = false;
  73173. _this._poster = false;
  73174. _this._createInternalTexture = function () {
  73175. if (_this._texture != null) {
  73176. if (_this._poster) {
  73177. _this._texture.dispose();
  73178. _this._poster = false;
  73179. }
  73180. else {
  73181. return;
  73182. }
  73183. }
  73184. if (!_this._engine.needPOTTextures ||
  73185. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  73186. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73187. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73188. }
  73189. else {
  73190. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73191. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73192. _this._generateMipMaps = false;
  73193. }
  73194. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  73195. if (!_this.video.autoplay) {
  73196. var oldHandler_1 = _this.video.onplaying;
  73197. var error_1 = false;
  73198. _this.video.onplaying = function () {
  73199. _this.video.onplaying = oldHandler_1;
  73200. _this._texture.isReady = true;
  73201. _this._updateInternalTexture();
  73202. if (!error_1) {
  73203. _this.video.pause();
  73204. }
  73205. if (_this.onLoadObservable.hasObservers()) {
  73206. _this.onLoadObservable.notifyObservers(_this);
  73207. }
  73208. };
  73209. var playing = _this.video.play();
  73210. if (playing) {
  73211. playing.then(function () {
  73212. // Everything is good.
  73213. })
  73214. .catch(function () {
  73215. error_1 = true;
  73216. // On Chrome for instance, new policies might prevent playing without user interaction.
  73217. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  73218. _this._onUserActionRequestedObservable.notifyObservers(_this);
  73219. }
  73220. });
  73221. }
  73222. else {
  73223. _this.video.onplaying = oldHandler_1;
  73224. _this._texture.isReady = true;
  73225. _this._updateInternalTexture();
  73226. if (_this.onLoadObservable.hasObservers()) {
  73227. _this.onLoadObservable.notifyObservers(_this);
  73228. }
  73229. }
  73230. }
  73231. else {
  73232. _this._texture.isReady = true;
  73233. _this._updateInternalTexture();
  73234. if (_this.onLoadObservable.hasObservers()) {
  73235. _this.onLoadObservable.notifyObservers(_this);
  73236. }
  73237. }
  73238. };
  73239. _this.reset = function () {
  73240. if (_this._texture == null) {
  73241. return;
  73242. }
  73243. if (!_this._poster) {
  73244. _this._texture.dispose();
  73245. _this._texture = null;
  73246. }
  73247. };
  73248. _this._updateInternalTexture = function (e) {
  73249. if (_this._texture == null || !_this._texture.isReady) {
  73250. return;
  73251. }
  73252. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  73253. return;
  73254. }
  73255. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  73256. };
  73257. _this._engine = _this.getScene().getEngine();
  73258. _this._generateMipMaps = generateMipMaps;
  73259. _this._samplingMode = samplingMode;
  73260. _this.autoUpdateTexture = settings.autoUpdateTexture;
  73261. _this.name = name || _this._getName(src);
  73262. _this.video = _this._getVideo(src);
  73263. if (settings.poster) {
  73264. _this.video.poster = settings.poster;
  73265. }
  73266. if (settings.autoPlay !== undefined) {
  73267. _this.video.autoplay = settings.autoPlay;
  73268. }
  73269. if (settings.loop !== undefined) {
  73270. _this.video.loop = settings.loop;
  73271. }
  73272. _this.video.setAttribute("playsinline", "");
  73273. _this.video.addEventListener("canplay", _this._createInternalTexture);
  73274. _this.video.addEventListener("paused", _this._updateInternalTexture);
  73275. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  73276. _this.video.addEventListener("emptied", _this.reset);
  73277. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  73278. _this._createInternalTexture();
  73279. }
  73280. if (settings.poster) {
  73281. _this._texture = _this._engine.createTexture(settings.poster, false, true, scene);
  73282. _this._poster = true;
  73283. }
  73284. return _this;
  73285. }
  73286. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  73287. /**
  73288. * Event triggerd when a dom action is required by the user to play the video.
  73289. * This happens due to recent changes in browser policies preventing video to auto start.
  73290. */
  73291. get: function () {
  73292. if (!this._onUserActionRequestedObservable) {
  73293. this._onUserActionRequestedObservable = new BABYLON.Observable();
  73294. }
  73295. return this._onUserActionRequestedObservable;
  73296. },
  73297. enumerable: true,
  73298. configurable: true
  73299. });
  73300. VideoTexture.prototype._getName = function (src) {
  73301. if (src instanceof HTMLVideoElement) {
  73302. return src.currentSrc;
  73303. }
  73304. if (typeof src === "object") {
  73305. return src.toString();
  73306. }
  73307. return src;
  73308. };
  73309. ;
  73310. VideoTexture.prototype._getVideo = function (src) {
  73311. if (src instanceof HTMLVideoElement) {
  73312. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  73313. return src;
  73314. }
  73315. var video = document.createElement("video");
  73316. if (typeof src === "string") {
  73317. BABYLON.Tools.SetCorsBehavior(src, video);
  73318. video.src = src;
  73319. }
  73320. else {
  73321. BABYLON.Tools.SetCorsBehavior(src[0], video);
  73322. src.forEach(function (url) {
  73323. var source = document.createElement("source");
  73324. source.src = url;
  73325. video.appendChild(source);
  73326. });
  73327. }
  73328. return video;
  73329. };
  73330. ;
  73331. /**
  73332. * @hidden Internal method to initiate `update`.
  73333. */
  73334. VideoTexture.prototype._rebuild = function () {
  73335. this.update();
  73336. };
  73337. /**
  73338. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  73339. */
  73340. VideoTexture.prototype.update = function () {
  73341. if (!this.autoUpdateTexture) {
  73342. // Expecting user to call `updateTexture` manually
  73343. return;
  73344. }
  73345. this.updateTexture(true);
  73346. };
  73347. /**
  73348. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  73349. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  73350. */
  73351. VideoTexture.prototype.updateTexture = function (isVisible) {
  73352. if (!isVisible) {
  73353. return;
  73354. }
  73355. if (this.video.paused && this._stillImageCaptured) {
  73356. return;
  73357. }
  73358. this._stillImageCaptured = true;
  73359. this._updateInternalTexture();
  73360. };
  73361. /**
  73362. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  73363. * @param url New url.
  73364. */
  73365. VideoTexture.prototype.updateURL = function (url) {
  73366. this.video.src = url;
  73367. };
  73368. /**
  73369. * Dispose the texture and release its associated resources.
  73370. */
  73371. VideoTexture.prototype.dispose = function () {
  73372. _super.prototype.dispose.call(this);
  73373. if (this._onUserActionRequestedObservable) {
  73374. this._onUserActionRequestedObservable.clear();
  73375. this._onUserActionRequestedObservable = null;
  73376. }
  73377. this.video.removeEventListener("canplay", this._createInternalTexture);
  73378. this.video.removeEventListener("paused", this._updateInternalTexture);
  73379. this.video.removeEventListener("seeked", this._updateInternalTexture);
  73380. this.video.removeEventListener("emptied", this.reset);
  73381. this.video.pause();
  73382. };
  73383. /**
  73384. * Creates a video texture straight from your WebCam video feed.
  73385. * @param scene Define the scene the texture should be created in
  73386. * @param onReady Define a callback to triggered once the texture will be ready
  73387. * @param constraints Define the constraints to use to create the web cam feed from WebRTC
  73388. */
  73389. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  73390. var video = document.createElement("video");
  73391. video.setAttribute('autoplay', '');
  73392. video.setAttribute('muted', '');
  73393. video.setAttribute('playsinline', '');
  73394. var constraintsDeviceId;
  73395. if (constraints && constraints.deviceId) {
  73396. constraintsDeviceId = {
  73397. exact: constraints.deviceId,
  73398. };
  73399. }
  73400. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  73401. if (navigator.mediaDevices) {
  73402. navigator.mediaDevices.getUserMedia({ video: constraints })
  73403. .then(function (stream) {
  73404. if (video.mozSrcObject !== undefined) {
  73405. // hack for Firefox < 19
  73406. video.mozSrcObject = stream;
  73407. }
  73408. else {
  73409. video.srcObject = stream;
  73410. }
  73411. var onPlaying = function () {
  73412. if (onReady) {
  73413. onReady(new VideoTexture("video", video, scene, true, true));
  73414. }
  73415. video.removeEventListener("playing", onPlaying);
  73416. };
  73417. video.addEventListener("playing", onPlaying);
  73418. video.play();
  73419. })
  73420. .catch(function (err) {
  73421. BABYLON.Tools.Error(err.name);
  73422. });
  73423. }
  73424. else {
  73425. navigator.getUserMedia =
  73426. navigator.getUserMedia ||
  73427. navigator.webkitGetUserMedia ||
  73428. navigator.mozGetUserMedia ||
  73429. navigator.msGetUserMedia;
  73430. if (navigator.getUserMedia) {
  73431. navigator.getUserMedia({
  73432. video: {
  73433. deviceId: constraintsDeviceId,
  73434. width: {
  73435. min: (constraints && constraints.minWidth) || 256,
  73436. max: (constraints && constraints.maxWidth) || 640,
  73437. },
  73438. height: {
  73439. min: (constraints && constraints.minHeight) || 256,
  73440. max: (constraints && constraints.maxHeight) || 480,
  73441. },
  73442. },
  73443. }, function (stream) {
  73444. if (video.mozSrcObject !== undefined) {
  73445. // hack for Firefox < 19
  73446. video.mozSrcObject = stream;
  73447. }
  73448. else {
  73449. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  73450. }
  73451. video.play();
  73452. if (onReady) {
  73453. onReady(new VideoTexture("video", video, scene, true, true));
  73454. }
  73455. }, function (e) {
  73456. BABYLON.Tools.Error(e.name);
  73457. });
  73458. }
  73459. }
  73460. };
  73461. return VideoTexture;
  73462. }(BABYLON.Texture));
  73463. BABYLON.VideoTexture = VideoTexture;
  73464. })(BABYLON || (BABYLON = {}));
  73465. //# sourceMappingURL=babylon.videoTexture.js.map
  73466. var BABYLON;
  73467. (function (BABYLON) {
  73468. /**
  73469. * Raw texture can help creating a texture directly from an array of data.
  73470. * This can be super useful if you either get the data from an uncompressed source or
  73471. * if you wish to create your texture pixel by pixel.
  73472. */
  73473. var RawTexture = /** @class */ (function (_super) {
  73474. __extends(RawTexture, _super);
  73475. /**
  73476. * Instantiates a new RawTexture.
  73477. * Raw texture can help creating a texture directly from an array of data.
  73478. * This can be super useful if you either get the data from an uncompressed source or
  73479. * if you wish to create your texture pixel by pixel.
  73480. * @param data define the array of data to use to create the texture
  73481. * @param width define the width of the texture
  73482. * @param height define the height of the texture
  73483. * @param format define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73484. * @param scene define the scene the texture belongs to
  73485. * @param generateMipMaps define whether mip maps should be generated or not
  73486. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73487. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73488. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73489. */
  73490. function RawTexture(data, width, height,
  73491. /**
  73492. * Define the format of the data (RGB, RGBA... Engine.TEXTUREFORMAT_xxx)
  73493. */
  73494. format, scene, generateMipMaps, invertY, samplingMode, type) {
  73495. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73496. if (invertY === void 0) { invertY = false; }
  73497. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73498. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73499. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73500. _this.format = format;
  73501. _this._engine = scene.getEngine();
  73502. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  73503. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73504. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73505. return _this;
  73506. }
  73507. /**
  73508. * Updates the texture underlying data.
  73509. * @param data Define the new data of the texture
  73510. */
  73511. RawTexture.prototype.update = function (data) {
  73512. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73513. };
  73514. /**
  73515. * Creates a luminance texture from some data.
  73516. * @param data Define the texture data
  73517. * @param width Define the width of the texture
  73518. * @param height Define the height of the texture
  73519. * @param scene Define the scene the texture belongs to
  73520. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73521. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73522. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73523. * @returns the luminance texture
  73524. */
  73525. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73526. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73527. if (invertY === void 0) { invertY = false; }
  73528. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73529. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  73530. };
  73531. /**
  73532. * Creates a luminance alpha texture from some data.
  73533. * @param data Define the texture data
  73534. * @param width Define the width of the texture
  73535. * @param height Define the height of the texture
  73536. * @param scene Define the scene the texture belongs to
  73537. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73538. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73539. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73540. * @returns the luminance alpha texture
  73541. */
  73542. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73543. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73544. if (invertY === void 0) { invertY = false; }
  73545. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73546. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73547. };
  73548. /**
  73549. * Creates an alpha texture from some data.
  73550. * @param data Define the texture data
  73551. * @param width Define the width of the texture
  73552. * @param height Define the height of the texture
  73553. * @param scene Define the scene the texture belongs to
  73554. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73555. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73556. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73557. * @returns the alpha texture
  73558. */
  73559. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  73560. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73561. if (invertY === void 0) { invertY = false; }
  73562. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73563. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  73564. };
  73565. /**
  73566. * Creates a RGB texture from some data.
  73567. * @param data Define the texture data
  73568. * @param width Define the width of the texture
  73569. * @param height Define the height of the texture
  73570. * @param scene Define the scene the texture belongs to
  73571. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73572. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73573. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73574. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73575. * @returns the RGB alpha texture
  73576. */
  73577. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73578. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73579. if (invertY === void 0) { invertY = false; }
  73580. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73581. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73582. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  73583. };
  73584. /**
  73585. * Creates a RGBA texture from some data.
  73586. * @param data Define the texture data
  73587. * @param width Define the width of the texture
  73588. * @param height Define the height of the texture
  73589. * @param scene Define the scene the texture belongs to
  73590. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73591. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73592. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73593. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73594. * @returns the RGBA texture
  73595. */
  73596. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73597. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73598. if (invertY === void 0) { invertY = false; }
  73599. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73600. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73601. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  73602. };
  73603. /**
  73604. * Creates a R texture from some data.
  73605. * @param data Define the texture data
  73606. * @param width Define the width of the texture
  73607. * @param height Define the height of the texture
  73608. * @param scene Define the scene the texture belongs to
  73609. * @param generateMipMaps Define whether or not to create mip maps for the texture
  73610. * @param invertY define if the data should be flipped on Y when uploaded to the GPU
  73611. * @param samplingMode define the texture sampling mode (Texture.xxx_SAMPLINGMODE)
  73612. * @param type define the format of the data (int, float... Engine.TEXTURETYPE_xxx)
  73613. * @returns the R texture
  73614. */
  73615. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  73616. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73617. if (invertY === void 0) { invertY = false; }
  73618. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73619. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73620. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  73621. };
  73622. return RawTexture;
  73623. }(BABYLON.Texture));
  73624. BABYLON.RawTexture = RawTexture;
  73625. })(BABYLON || (BABYLON = {}));
  73626. //# sourceMappingURL=babylon.rawTexture.js.map
  73627. var BABYLON;
  73628. (function (BABYLON) {
  73629. /**
  73630. * Class used to store 3D textures containing user data
  73631. */
  73632. var RawTexture3D = /** @class */ (function (_super) {
  73633. __extends(RawTexture3D, _super);
  73634. /**
  73635. * Create a new RawTexture3D
  73636. * @param data defines the data of the texture
  73637. * @param width defines the width of the texture
  73638. * @param height defines the height of the texture
  73639. * @param depth defines the depth of the texture
  73640. * @param format defines the texture format to use
  73641. * @param scene defines the hosting scene
  73642. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  73643. * @param invertY defines if texture must be stored with Y axis inverted
  73644. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  73645. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  73646. */
  73647. function RawTexture3D(data, width, height, depth,
  73648. /** Gets or sets the texture format to use */
  73649. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  73650. if (generateMipMaps === void 0) { generateMipMaps = true; }
  73651. if (invertY === void 0) { invertY = false; }
  73652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  73653. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73654. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  73655. _this.format = format;
  73656. _this._engine = scene.getEngine();
  73657. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  73658. _this.is3D = true;
  73659. return _this;
  73660. }
  73661. /**
  73662. * Update the texture with new data
  73663. * @param data defines the data to store in the texture
  73664. */
  73665. RawTexture3D.prototype.update = function (data) {
  73666. if (!this._texture) {
  73667. return;
  73668. }
  73669. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  73670. };
  73671. return RawTexture3D;
  73672. }(BABYLON.Texture));
  73673. BABYLON.RawTexture3D = RawTexture3D;
  73674. })(BABYLON || (BABYLON = {}));
  73675. //# sourceMappingURL=babylon.rawTexture3D.js.map
  73676. var BABYLON;
  73677. (function (BABYLON) {
  73678. /**
  73679. * PostProcessManager is used to manage one or more post processes or post process pipelines
  73680. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73681. */
  73682. var PostProcessManager = /** @class */ (function () {
  73683. /**
  73684. * Creates a new instance PostProcess
  73685. * @param scene The scene that the post process is associated with.
  73686. */
  73687. function PostProcessManager(scene) {
  73688. this._vertexBuffers = {};
  73689. this._scene = scene;
  73690. }
  73691. PostProcessManager.prototype._prepareBuffers = function () {
  73692. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  73693. return;
  73694. }
  73695. // VBO
  73696. var vertices = [];
  73697. vertices.push(1, 1);
  73698. vertices.push(-1, 1);
  73699. vertices.push(-1, -1);
  73700. vertices.push(1, -1);
  73701. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  73702. this._buildIndexBuffer();
  73703. };
  73704. PostProcessManager.prototype._buildIndexBuffer = function () {
  73705. // Indices
  73706. var indices = [];
  73707. indices.push(0);
  73708. indices.push(1);
  73709. indices.push(2);
  73710. indices.push(0);
  73711. indices.push(2);
  73712. indices.push(3);
  73713. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  73714. };
  73715. /**
  73716. * Rebuilds the vertex buffers of the manager.
  73717. * @hidden
  73718. */
  73719. PostProcessManager.prototype._rebuild = function () {
  73720. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73721. if (!vb) {
  73722. return;
  73723. }
  73724. vb._rebuild();
  73725. this._buildIndexBuffer();
  73726. };
  73727. // Methods
  73728. /**
  73729. * Prepares a frame to be run through a post process.
  73730. * @param sourceTexture The input texture to the post procesess. (default: null)
  73731. * @param postProcesses An array of post processes to be run. (default: null)
  73732. * @returns True if the post processes were able to be run.
  73733. * @hidden
  73734. */
  73735. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  73736. if (sourceTexture === void 0) { sourceTexture = null; }
  73737. if (postProcesses === void 0) { postProcesses = null; }
  73738. var camera = this._scene.activeCamera;
  73739. if (!camera) {
  73740. return false;
  73741. }
  73742. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73743. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73744. return false;
  73745. }
  73746. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  73747. return true;
  73748. };
  73749. /**
  73750. * Manually render a set of post processes to a texture.
  73751. * @param postProcesses An array of post processes to be run.
  73752. * @param targetTexture The target texture to render to.
  73753. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  73754. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  73755. * @param lodLevel defines which lod of the texture to render to
  73756. */
  73757. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  73758. if (targetTexture === void 0) { targetTexture = null; }
  73759. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73760. if (faceIndex === void 0) { faceIndex = 0; }
  73761. if (lodLevel === void 0) { lodLevel = 0; }
  73762. var engine = this._scene.getEngine();
  73763. for (var index = 0; index < postProcesses.length; index++) {
  73764. if (index < postProcesses.length - 1) {
  73765. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  73766. }
  73767. else {
  73768. if (targetTexture) {
  73769. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  73770. }
  73771. else {
  73772. engine.restoreDefaultFramebuffer();
  73773. }
  73774. }
  73775. var pp = postProcesses[index];
  73776. var effect = pp.apply();
  73777. if (effect) {
  73778. pp.onBeforeRenderObservable.notifyObservers(effect);
  73779. // VBOs
  73780. this._prepareBuffers();
  73781. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73782. // Draw order
  73783. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73784. pp.onAfterRenderObservable.notifyObservers(effect);
  73785. }
  73786. }
  73787. // Restore depth buffer
  73788. engine.setDepthBuffer(true);
  73789. engine.setDepthWrite(true);
  73790. };
  73791. /**
  73792. * Finalize the result of the output of the postprocesses.
  73793. * @param doNotPresent If true the result will not be displayed to the screen.
  73794. * @param targetTexture The target texture to render to.
  73795. * @param faceIndex The index of the face to bind the target texture to.
  73796. * @param postProcesses The array of post processes to render.
  73797. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  73798. * @hidden
  73799. */
  73800. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  73801. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  73802. var camera = this._scene.activeCamera;
  73803. if (!camera) {
  73804. return;
  73805. }
  73806. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  73807. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  73808. return;
  73809. }
  73810. var engine = this._scene.getEngine();
  73811. for (var index = 0, len = postProcesses.length; index < len; index++) {
  73812. var pp = postProcesses[index];
  73813. if (index < len - 1) {
  73814. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  73815. }
  73816. else {
  73817. if (targetTexture) {
  73818. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  73819. pp._outputTexture = targetTexture;
  73820. }
  73821. else {
  73822. engine.restoreDefaultFramebuffer();
  73823. pp._outputTexture = null;
  73824. }
  73825. }
  73826. if (doNotPresent) {
  73827. break;
  73828. }
  73829. var effect = pp.apply();
  73830. if (effect) {
  73831. pp.onBeforeRenderObservable.notifyObservers(effect);
  73832. // VBOs
  73833. this._prepareBuffers();
  73834. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  73835. // Draw order
  73836. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  73837. pp.onAfterRenderObservable.notifyObservers(effect);
  73838. }
  73839. }
  73840. // Restore states
  73841. engine.setDepthBuffer(true);
  73842. engine.setDepthWrite(true);
  73843. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  73844. };
  73845. /**
  73846. * Disposes of the post process manager.
  73847. */
  73848. PostProcessManager.prototype.dispose = function () {
  73849. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  73850. if (buffer) {
  73851. buffer.dispose();
  73852. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  73853. }
  73854. if (this._indexBuffer) {
  73855. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  73856. this._indexBuffer = null;
  73857. }
  73858. };
  73859. return PostProcessManager;
  73860. }());
  73861. BABYLON.PostProcessManager = PostProcessManager;
  73862. })(BABYLON || (BABYLON = {}));
  73863. //# sourceMappingURL=babylon.postProcessManager.js.map
  73864. var BABYLON;
  73865. (function (BABYLON) {
  73866. /**
  73867. * PostProcess can be used to apply a shader to a texture after it has been rendered
  73868. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  73869. */
  73870. var PostProcess = /** @class */ (function () {
  73871. /**
  73872. * Creates a new instance PostProcess
  73873. * @param name The name of the PostProcess.
  73874. * @param fragmentUrl The url of the fragment shader to be used.
  73875. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  73876. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  73877. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  73878. * @param camera The camera to apply the render pass to.
  73879. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  73880. * @param engine The engine which the post process will be applied. (default: current engine)
  73881. * @param reusable If the post process can be reused on the same frame. (default: false)
  73882. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  73883. * @param textureType Type of textures used when performing the post process. (default: 0)
  73884. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  73885. * @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
  73886. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  73887. */
  73888. function PostProcess(
  73889. /** Name of the PostProcess. */
  73890. name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  73891. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  73892. if (defines === void 0) { defines = null; }
  73893. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  73894. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  73895. if (blockCompilation === void 0) { blockCompilation = false; }
  73896. this.name = name;
  73897. /**
  73898. * Width of the texture to apply the post process on
  73899. */
  73900. this.width = -1;
  73901. /**
  73902. * Height of the texture to apply the post process on
  73903. */
  73904. this.height = -1;
  73905. /**
  73906. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  73907. * @hidden
  73908. */
  73909. this._outputTexture = null;
  73910. /**
  73911. * If the buffer needs to be cleared before applying the post process. (default: true)
  73912. * Should be set to false if shader will overwrite all previous pixels.
  73913. */
  73914. this.autoClear = true;
  73915. /**
  73916. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  73917. */
  73918. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  73919. /**
  73920. * Animations to be used for the post processing
  73921. */
  73922. this.animations = new Array();
  73923. /**
  73924. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  73925. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  73926. */
  73927. this.enablePixelPerfectMode = false;
  73928. /**
  73929. * Force the postprocess to be applied without taking in account viewport
  73930. */
  73931. this.forceFullscreenViewport = true;
  73932. /**
  73933. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  73934. *
  73935. * | Value | Type | Description |
  73936. * | ----- | ----------------------------------- | ----------- |
  73937. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  73938. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  73939. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  73940. *
  73941. */
  73942. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  73943. /**
  73944. * Force textures to be a power of two (default: false)
  73945. */
  73946. this.alwaysForcePOT = false;
  73947. this._samples = 1;
  73948. /**
  73949. * Modify the scale of the post process to be the same as the viewport (default: false)
  73950. */
  73951. this.adaptScaleToCurrentViewport = false;
  73952. this._reusable = false;
  73953. /**
  73954. * Smart array of input and output textures for the post process.
  73955. * @hidden
  73956. */
  73957. this._textures = new BABYLON.SmartArray(2);
  73958. /**
  73959. * The index in _textures that corresponds to the output texture.
  73960. * @hidden
  73961. */
  73962. this._currentRenderTextureInd = 0;
  73963. this._scaleRatio = new BABYLON.Vector2(1, 1);
  73964. this._texelSize = BABYLON.Vector2.Zero();
  73965. // Events
  73966. /**
  73967. * An event triggered when the postprocess is activated.
  73968. */
  73969. this.onActivateObservable = new BABYLON.Observable();
  73970. /**
  73971. * An event triggered when the postprocess changes its size.
  73972. */
  73973. this.onSizeChangedObservable = new BABYLON.Observable();
  73974. /**
  73975. * An event triggered when the postprocess applies its effect.
  73976. */
  73977. this.onApplyObservable = new BABYLON.Observable();
  73978. /**
  73979. * An event triggered before rendering the postprocess
  73980. */
  73981. this.onBeforeRenderObservable = new BABYLON.Observable();
  73982. /**
  73983. * An event triggered after rendering the postprocess
  73984. */
  73985. this.onAfterRenderObservable = new BABYLON.Observable();
  73986. if (camera != null) {
  73987. this._camera = camera;
  73988. this._scene = camera.getScene();
  73989. camera.attachPostProcess(this);
  73990. this._engine = this._scene.getEngine();
  73991. this._scene.postProcesses.push(this);
  73992. }
  73993. else if (engine) {
  73994. this._engine = engine;
  73995. this._engine.postProcesses.push(this);
  73996. }
  73997. this._options = options;
  73998. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  73999. this._reusable = reusable || false;
  74000. this._textureType = textureType;
  74001. this._samplers = samplers || [];
  74002. this._samplers.push("textureSampler");
  74003. this._fragmentUrl = fragmentUrl;
  74004. this._vertexUrl = vertexUrl;
  74005. this._parameters = parameters || [];
  74006. this._parameters.push("scale");
  74007. this._indexParameters = indexParameters;
  74008. if (!blockCompilation) {
  74009. this.updateEffect(defines);
  74010. }
  74011. }
  74012. Object.defineProperty(PostProcess.prototype, "samples", {
  74013. /**
  74014. * Number of sample textures (default: 1)
  74015. */
  74016. get: function () {
  74017. return this._samples;
  74018. },
  74019. set: function (n) {
  74020. var _this = this;
  74021. this._samples = n;
  74022. this._textures.forEach(function (texture) {
  74023. if (texture.samples !== _this._samples) {
  74024. _this._engine.updateRenderTargetTextureSampleCount(texture, _this._samples);
  74025. }
  74026. });
  74027. },
  74028. enumerable: true,
  74029. configurable: true
  74030. });
  74031. Object.defineProperty(PostProcess.prototype, "onActivate", {
  74032. /**
  74033. * A function that is added to the onActivateObservable
  74034. */
  74035. set: function (callback) {
  74036. if (this._onActivateObserver) {
  74037. this.onActivateObservable.remove(this._onActivateObserver);
  74038. }
  74039. if (callback) {
  74040. this._onActivateObserver = this.onActivateObservable.add(callback);
  74041. }
  74042. },
  74043. enumerable: true,
  74044. configurable: true
  74045. });
  74046. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  74047. /**
  74048. * A function that is added to the onSizeChangedObservable
  74049. */
  74050. set: function (callback) {
  74051. if (this._onSizeChangedObserver) {
  74052. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  74053. }
  74054. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  74055. },
  74056. enumerable: true,
  74057. configurable: true
  74058. });
  74059. Object.defineProperty(PostProcess.prototype, "onApply", {
  74060. /**
  74061. * A function that is added to the onApplyObservable
  74062. */
  74063. set: function (callback) {
  74064. if (this._onApplyObserver) {
  74065. this.onApplyObservable.remove(this._onApplyObserver);
  74066. }
  74067. this._onApplyObserver = this.onApplyObservable.add(callback);
  74068. },
  74069. enumerable: true,
  74070. configurable: true
  74071. });
  74072. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  74073. /**
  74074. * A function that is added to the onBeforeRenderObservable
  74075. */
  74076. set: function (callback) {
  74077. if (this._onBeforeRenderObserver) {
  74078. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  74079. }
  74080. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  74081. },
  74082. enumerable: true,
  74083. configurable: true
  74084. });
  74085. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  74086. /**
  74087. * A function that is added to the onAfterRenderObservable
  74088. */
  74089. set: function (callback) {
  74090. if (this._onAfterRenderObserver) {
  74091. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  74092. }
  74093. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  74094. },
  74095. enumerable: true,
  74096. configurable: true
  74097. });
  74098. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  74099. /**
  74100. * 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
  74101. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  74102. */
  74103. get: function () {
  74104. return this._textures.data[this._currentRenderTextureInd];
  74105. },
  74106. set: function (value) {
  74107. this._forcedOutputTexture = value;
  74108. },
  74109. enumerable: true,
  74110. configurable: true
  74111. });
  74112. /**
  74113. * Gets the camera which post process is applied to.
  74114. * @returns The camera the post process is applied to.
  74115. */
  74116. PostProcess.prototype.getCamera = function () {
  74117. return this._camera;
  74118. };
  74119. Object.defineProperty(PostProcess.prototype, "texelSize", {
  74120. /**
  74121. * Gets the texel size of the postprocess.
  74122. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  74123. */
  74124. get: function () {
  74125. if (this._shareOutputWithPostProcess) {
  74126. return this._shareOutputWithPostProcess.texelSize;
  74127. }
  74128. if (this._forcedOutputTexture) {
  74129. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  74130. }
  74131. return this._texelSize;
  74132. },
  74133. enumerable: true,
  74134. configurable: true
  74135. });
  74136. /**
  74137. * Gets the engine which this post process belongs to.
  74138. * @returns The engine the post process was enabled with.
  74139. */
  74140. PostProcess.prototype.getEngine = function () {
  74141. return this._engine;
  74142. };
  74143. /**
  74144. * The effect that is created when initializing the post process.
  74145. * @returns The created effect corrisponding the the postprocess.
  74146. */
  74147. PostProcess.prototype.getEffect = function () {
  74148. return this._effect;
  74149. };
  74150. /**
  74151. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  74152. * @param postProcess The post process to share the output with.
  74153. * @returns This post process.
  74154. */
  74155. PostProcess.prototype.shareOutputWith = function (postProcess) {
  74156. this._disposeTextures();
  74157. this._shareOutputWithPostProcess = postProcess;
  74158. return this;
  74159. };
  74160. /**
  74161. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  74162. * This should be called if the post process that shares output with this post process is disabled/disposed.
  74163. */
  74164. PostProcess.prototype.useOwnOutput = function () {
  74165. if (this._textures.length == 0) {
  74166. this._textures = new BABYLON.SmartArray(2);
  74167. }
  74168. this._shareOutputWithPostProcess = null;
  74169. };
  74170. /**
  74171. * Updates the effect with the current post process compile time values and recompiles the shader.
  74172. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74173. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74174. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74175. * @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
  74176. * @param onCompiled Called when the shader has been compiled.
  74177. * @param onError Called if there is an error when compiling a shader.
  74178. */
  74179. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74180. if (defines === void 0) { defines = null; }
  74181. if (uniforms === void 0) { uniforms = null; }
  74182. if (samplers === void 0) { samplers = null; }
  74183. 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);
  74184. };
  74185. /**
  74186. * The post process is reusable if it can be used multiple times within one frame.
  74187. * @returns If the post process is reusable
  74188. */
  74189. PostProcess.prototype.isReusable = function () {
  74190. return this._reusable;
  74191. };
  74192. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  74193. PostProcess.prototype.markTextureDirty = function () {
  74194. this.width = -1;
  74195. };
  74196. /**
  74197. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  74198. * 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.
  74199. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  74200. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  74201. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  74202. * @returns The target texture that was bound to be written to.
  74203. */
  74204. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  74205. var _this = this;
  74206. if (sourceTexture === void 0) { sourceTexture = null; }
  74207. camera = camera || this._camera;
  74208. var scene = camera.getScene();
  74209. var engine = scene.getEngine();
  74210. var maxSize = engine.getCaps().maxTextureSize;
  74211. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  74212. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  74213. // 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
  74214. var webVRCamera = camera.parent;
  74215. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  74216. requiredWidth /= 2;
  74217. }
  74218. var desiredWidth = (this._options.width || requiredWidth);
  74219. var desiredHeight = this._options.height || requiredHeight;
  74220. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  74221. if (this.adaptScaleToCurrentViewport) {
  74222. var currentViewport = engine.currentViewport;
  74223. if (currentViewport) {
  74224. desiredWidth *= currentViewport.width;
  74225. desiredHeight *= currentViewport.height;
  74226. }
  74227. }
  74228. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  74229. if (!this._options.width) {
  74230. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  74231. }
  74232. if (!this._options.height) {
  74233. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  74234. }
  74235. }
  74236. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  74237. if (this._textures.length > 0) {
  74238. for (var i = 0; i < this._textures.length; i++) {
  74239. this._engine._releaseTexture(this._textures.data[i]);
  74240. }
  74241. this._textures.reset();
  74242. }
  74243. this.width = desiredWidth;
  74244. this.height = desiredHeight;
  74245. var textureSize = { width: this.width, height: this.height };
  74246. var textureOptions = {
  74247. generateMipMaps: false,
  74248. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  74249. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  74250. samplingMode: this.renderTargetSamplingMode,
  74251. type: this._textureType
  74252. };
  74253. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74254. if (this._reusable) {
  74255. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  74256. }
  74257. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  74258. this.onSizeChangedObservable.notifyObservers(this);
  74259. }
  74260. this._textures.forEach(function (texture) {
  74261. if (texture.samples !== _this.samples) {
  74262. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  74263. }
  74264. });
  74265. }
  74266. var target;
  74267. if (this._shareOutputWithPostProcess) {
  74268. target = this._shareOutputWithPostProcess.inputTexture;
  74269. }
  74270. else if (this._forcedOutputTexture) {
  74271. target = this._forcedOutputTexture;
  74272. this.width = this._forcedOutputTexture.width;
  74273. this.height = this._forcedOutputTexture.height;
  74274. }
  74275. else {
  74276. target = this.inputTexture;
  74277. }
  74278. // Bind the input of this post process to be used as the output of the previous post process.
  74279. if (this.enablePixelPerfectMode) {
  74280. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  74281. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  74282. }
  74283. else {
  74284. this._scaleRatio.copyFromFloats(1, 1);
  74285. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  74286. }
  74287. this.onActivateObservable.notifyObservers(camera);
  74288. // Clear
  74289. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  74290. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, scene._allowPostProcessClearColor, true, true);
  74291. }
  74292. if (this._reusable) {
  74293. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  74294. }
  74295. return target;
  74296. };
  74297. Object.defineProperty(PostProcess.prototype, "isSupported", {
  74298. /**
  74299. * If the post process is supported.
  74300. */
  74301. get: function () {
  74302. return this._effect.isSupported;
  74303. },
  74304. enumerable: true,
  74305. configurable: true
  74306. });
  74307. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  74308. /**
  74309. * The aspect ratio of the output texture.
  74310. */
  74311. get: function () {
  74312. if (this._shareOutputWithPostProcess) {
  74313. return this._shareOutputWithPostProcess.aspectRatio;
  74314. }
  74315. if (this._forcedOutputTexture) {
  74316. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  74317. }
  74318. return this.width / this.height;
  74319. },
  74320. enumerable: true,
  74321. configurable: true
  74322. });
  74323. /**
  74324. * Get a value indicating if the post-process is ready to be used
  74325. * @returns true if the post-process is ready (shader is compiled)
  74326. */
  74327. PostProcess.prototype.isReady = function () {
  74328. return this._effect && this._effect.isReady();
  74329. };
  74330. /**
  74331. * Binds all textures and uniforms to the shader, this will be run on every pass.
  74332. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  74333. */
  74334. PostProcess.prototype.apply = function () {
  74335. // Check
  74336. if (!this._effect || !this._effect.isReady())
  74337. return null;
  74338. // States
  74339. this._engine.enableEffect(this._effect);
  74340. this._engine.setState(false);
  74341. this._engine.setDepthBuffer(false);
  74342. this._engine.setDepthWrite(false);
  74343. // Alpha
  74344. this._engine.setAlphaMode(this.alphaMode);
  74345. if (this.alphaConstants) {
  74346. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  74347. }
  74348. // Bind the output texture of the preivous post process as the input to this post process.
  74349. var source;
  74350. if (this._shareOutputWithPostProcess) {
  74351. source = this._shareOutputWithPostProcess.inputTexture;
  74352. }
  74353. else if (this._forcedOutputTexture) {
  74354. source = this._forcedOutputTexture;
  74355. }
  74356. else {
  74357. source = this.inputTexture;
  74358. }
  74359. this._effect._bindTexture("textureSampler", source);
  74360. // Parameters
  74361. this._effect.setVector2("scale", this._scaleRatio);
  74362. this.onApplyObservable.notifyObservers(this._effect);
  74363. return this._effect;
  74364. };
  74365. PostProcess.prototype._disposeTextures = function () {
  74366. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  74367. return;
  74368. }
  74369. if (this._textures.length > 0) {
  74370. for (var i = 0; i < this._textures.length; i++) {
  74371. this._engine._releaseTexture(this._textures.data[i]);
  74372. }
  74373. }
  74374. this._textures.dispose();
  74375. };
  74376. /**
  74377. * Disposes the post process.
  74378. * @param camera The camera to dispose the post process on.
  74379. */
  74380. PostProcess.prototype.dispose = function (camera) {
  74381. camera = camera || this._camera;
  74382. this._disposeTextures();
  74383. if (this._scene) {
  74384. var index_1 = this._scene.postProcesses.indexOf(this);
  74385. if (index_1 !== -1) {
  74386. this._scene.postProcesses.splice(index_1, 1);
  74387. }
  74388. }
  74389. else {
  74390. var index_2 = this._engine.postProcesses.indexOf(this);
  74391. if (index_2 !== -1) {
  74392. this._engine.postProcesses.splice(index_2, 1);
  74393. }
  74394. }
  74395. if (!camera) {
  74396. return;
  74397. }
  74398. camera.detachPostProcess(this);
  74399. var index = camera._postProcesses.indexOf(this);
  74400. if (index === 0 && camera._postProcesses.length > 0) {
  74401. var firstPostProcess = this._camera._getFirstPostProcess();
  74402. if (firstPostProcess) {
  74403. firstPostProcess.markTextureDirty();
  74404. }
  74405. }
  74406. this.onActivateObservable.clear();
  74407. this.onAfterRenderObservable.clear();
  74408. this.onApplyObservable.clear();
  74409. this.onBeforeRenderObservable.clear();
  74410. this.onSizeChangedObservable.clear();
  74411. };
  74412. return PostProcess;
  74413. }());
  74414. BABYLON.PostProcess = PostProcess;
  74415. })(BABYLON || (BABYLON = {}));
  74416. //# sourceMappingURL=babylon.postProcess.js.map
  74417. var BABYLON;
  74418. (function (BABYLON) {
  74419. /**
  74420. * PassPostProcess which produces an output the same as it's input
  74421. */
  74422. var PassPostProcess = /** @class */ (function (_super) {
  74423. __extends(PassPostProcess, _super);
  74424. /**
  74425. * Creates the PassPostProcess
  74426. * @param name The name of the effect.
  74427. * @param options The required width/height ratio to downsize to before computing the render pass.
  74428. * @param camera The camera to apply the render pass to.
  74429. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74430. * @param engine The engine which the post process will be applied. (default: current engine)
  74431. * @param reusable If the post process can be reused on the same frame. (default: false)
  74432. * @param textureType The type of texture to be used when performing the post processing.
  74433. * @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)
  74434. */
  74435. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74436. if (camera === void 0) { camera = null; }
  74437. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74438. if (blockCompilation === void 0) { blockCompilation = false; }
  74439. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  74440. }
  74441. return PassPostProcess;
  74442. }(BABYLON.PostProcess));
  74443. BABYLON.PassPostProcess = PassPostProcess;
  74444. })(BABYLON || (BABYLON = {}));
  74445. //# sourceMappingURL=babylon.passPostProcess.js.map
  74446. var __assign = (this && this.__assign) || function () {
  74447. __assign = Object.assign || function(t) {
  74448. for (var s, i = 1, n = arguments.length; i < n; i++) {
  74449. s = arguments[i];
  74450. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  74451. t[p] = s[p];
  74452. }
  74453. return t;
  74454. };
  74455. return __assign.apply(this, arguments);
  74456. };
  74457. var BABYLON;
  74458. (function (BABYLON) {
  74459. /**
  74460. * Default implementation IShadowGenerator.
  74461. * This is the main object responsible of generating shadows in the framework.
  74462. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  74463. */
  74464. var ShadowGenerator = /** @class */ (function () {
  74465. /**
  74466. * Creates a ShadowGenerator object.
  74467. * A ShadowGenerator is the required tool to use the shadows.
  74468. * Each light casting shadows needs to use its own ShadowGenerator.
  74469. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  74470. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  74471. * @param light The light object generating the shadows.
  74472. * @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.
  74473. */
  74474. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  74475. this._bias = 0.00005;
  74476. this._normalBias = 0;
  74477. this._blurBoxOffset = 1;
  74478. this._blurScale = 2;
  74479. this._blurKernel = 1;
  74480. this._useKernelBlur = false;
  74481. this._filter = ShadowGenerator.FILTER_NONE;
  74482. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  74483. this._contactHardeningLightSizeUVRatio = 0.1;
  74484. this._darkness = 0;
  74485. this._transparencyShadow = false;
  74486. /**
  74487. * Controls the extent to which the shadows fade out at the edge of the frustum
  74488. * Used only by directionals and spots
  74489. */
  74490. this.frustumEdgeFalloff = 0;
  74491. /**
  74492. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  74493. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  74494. * It might on the other hand introduce peter panning.
  74495. */
  74496. this.forceBackFacesOnly = false;
  74497. this._lightDirection = BABYLON.Vector3.Zero();
  74498. this._viewMatrix = BABYLON.Matrix.Zero();
  74499. this._projectionMatrix = BABYLON.Matrix.Zero();
  74500. this._transformMatrix = BABYLON.Matrix.Zero();
  74501. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74502. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  74503. this._currentFaceIndex = 0;
  74504. this._currentFaceIndexCache = 0;
  74505. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  74506. this._mapSize = mapSize;
  74507. this._light = light;
  74508. this._scene = light.getScene();
  74509. light._shadowGenerator = this;
  74510. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR);
  74511. if (!component) {
  74512. component = new BABYLON.ShadowGeneratorSceneComponent(this._scene);
  74513. this._scene._addComponent(component);
  74514. }
  74515. // Texture type fallback from float to int if not supported.
  74516. var caps = this._scene.getEngine().getCaps();
  74517. if (!useFullFloatFirst) {
  74518. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74519. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74520. }
  74521. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74522. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74523. }
  74524. else {
  74525. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74526. }
  74527. }
  74528. else {
  74529. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  74530. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  74531. }
  74532. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  74533. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74534. }
  74535. else {
  74536. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  74537. }
  74538. }
  74539. this._initializeGenerator();
  74540. this._applyFilterValues();
  74541. }
  74542. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  74543. /**
  74544. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  74545. */
  74546. get: function () {
  74547. return this._bias;
  74548. },
  74549. /**
  74550. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  74551. */
  74552. set: function (bias) {
  74553. this._bias = bias;
  74554. },
  74555. enumerable: true,
  74556. configurable: true
  74557. });
  74558. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  74559. /**
  74560. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74561. */
  74562. get: function () {
  74563. return this._normalBias;
  74564. },
  74565. /**
  74566. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  74567. */
  74568. set: function (normalBias) {
  74569. this._normalBias = normalBias;
  74570. },
  74571. enumerable: true,
  74572. configurable: true
  74573. });
  74574. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  74575. /**
  74576. * Gets the blur box offset: offset applied during the blur pass.
  74577. * Only usefull if useKernelBlur = false
  74578. */
  74579. get: function () {
  74580. return this._blurBoxOffset;
  74581. },
  74582. /**
  74583. * Sets the blur box offset: offset applied during the blur pass.
  74584. * Only usefull if useKernelBlur = false
  74585. */
  74586. set: function (value) {
  74587. if (this._blurBoxOffset === value) {
  74588. return;
  74589. }
  74590. this._blurBoxOffset = value;
  74591. this._disposeBlurPostProcesses();
  74592. },
  74593. enumerable: true,
  74594. configurable: true
  74595. });
  74596. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  74597. /**
  74598. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  74599. * 2 means half of the size.
  74600. */
  74601. get: function () {
  74602. return this._blurScale;
  74603. },
  74604. /**
  74605. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  74606. * 2 means half of the size.
  74607. */
  74608. set: function (value) {
  74609. if (this._blurScale === value) {
  74610. return;
  74611. }
  74612. this._blurScale = value;
  74613. this._disposeBlurPostProcesses();
  74614. },
  74615. enumerable: true,
  74616. configurable: true
  74617. });
  74618. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  74619. /**
  74620. * Gets the blur kernel: kernel size of the blur pass.
  74621. * Only usefull if useKernelBlur = true
  74622. */
  74623. get: function () {
  74624. return this._blurKernel;
  74625. },
  74626. /**
  74627. * Sets the blur kernel: kernel size of the blur pass.
  74628. * Only usefull if useKernelBlur = true
  74629. */
  74630. set: function (value) {
  74631. if (this._blurKernel === value) {
  74632. return;
  74633. }
  74634. this._blurKernel = value;
  74635. this._disposeBlurPostProcesses();
  74636. },
  74637. enumerable: true,
  74638. configurable: true
  74639. });
  74640. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  74641. /**
  74642. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  74643. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74644. */
  74645. get: function () {
  74646. return this._useKernelBlur;
  74647. },
  74648. /**
  74649. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  74650. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  74651. */
  74652. set: function (value) {
  74653. if (this._useKernelBlur === value) {
  74654. return;
  74655. }
  74656. this._useKernelBlur = value;
  74657. this._disposeBlurPostProcesses();
  74658. },
  74659. enumerable: true,
  74660. configurable: true
  74661. });
  74662. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  74663. /**
  74664. * Gets the depth scale used in ESM mode.
  74665. */
  74666. get: function () {
  74667. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  74668. },
  74669. /**
  74670. * Sets the depth scale used in ESM mode.
  74671. * This can override the scale stored on the light.
  74672. */
  74673. set: function (value) {
  74674. this._depthScale = value;
  74675. },
  74676. enumerable: true,
  74677. configurable: true
  74678. });
  74679. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  74680. /**
  74681. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  74682. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74683. */
  74684. get: function () {
  74685. return this._filter;
  74686. },
  74687. /**
  74688. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  74689. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  74690. */
  74691. set: function (value) {
  74692. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  74693. if (this._light.needCube()) {
  74694. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74695. this.useExponentialShadowMap = true;
  74696. return;
  74697. }
  74698. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74699. this.useCloseExponentialShadowMap = true;
  74700. return;
  74701. }
  74702. // PCF on cubemap would also be expensive
  74703. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74704. this.usePoissonSampling = true;
  74705. return;
  74706. }
  74707. }
  74708. // Weblg1 fallback for PCF.
  74709. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  74710. if (this._scene.getEngine().webGLVersion === 1) {
  74711. this.usePoissonSampling = true;
  74712. return;
  74713. }
  74714. }
  74715. if (this._filter === value) {
  74716. return;
  74717. }
  74718. this._filter = value;
  74719. this._disposeBlurPostProcesses();
  74720. this._applyFilterValues();
  74721. this._light._markMeshesAsLightDirty();
  74722. },
  74723. enumerable: true,
  74724. configurable: true
  74725. });
  74726. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  74727. /**
  74728. * Gets if the current filter is set to Poisson Sampling.
  74729. */
  74730. get: function () {
  74731. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  74732. },
  74733. /**
  74734. * Sets the current filter to Poisson Sampling.
  74735. */
  74736. set: function (value) {
  74737. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  74738. return;
  74739. }
  74740. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  74741. },
  74742. enumerable: true,
  74743. configurable: true
  74744. });
  74745. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  74746. /**
  74747. * Gets if the current filter is set to VSM.
  74748. * DEPRECATED. Should use useExponentialShadowMap instead.
  74749. */
  74750. get: function () {
  74751. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74752. return this.useExponentialShadowMap;
  74753. },
  74754. /**
  74755. * Sets the current filter is to VSM.
  74756. * DEPRECATED. Should use useExponentialShadowMap instead.
  74757. */
  74758. set: function (value) {
  74759. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  74760. this.useExponentialShadowMap = value;
  74761. },
  74762. enumerable: true,
  74763. configurable: true
  74764. });
  74765. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  74766. /**
  74767. * Gets if the current filter is set to blurred VSM.
  74768. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74769. */
  74770. get: function () {
  74771. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74772. return this.useBlurExponentialShadowMap;
  74773. },
  74774. /**
  74775. * Sets the current filter is to blurred VSM.
  74776. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  74777. */
  74778. set: function (value) {
  74779. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  74780. this.useBlurExponentialShadowMap = value;
  74781. },
  74782. enumerable: true,
  74783. configurable: true
  74784. });
  74785. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  74786. /**
  74787. * Gets if the current filter is set to ESM.
  74788. */
  74789. get: function () {
  74790. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  74791. },
  74792. /**
  74793. * Sets the current filter is to ESM.
  74794. */
  74795. set: function (value) {
  74796. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  74797. return;
  74798. }
  74799. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74800. },
  74801. enumerable: true,
  74802. configurable: true
  74803. });
  74804. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  74805. /**
  74806. * Gets if the current filter is set to filtered ESM.
  74807. */
  74808. get: function () {
  74809. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  74810. },
  74811. /**
  74812. * Gets if the current filter is set to filtered ESM.
  74813. */
  74814. set: function (value) {
  74815. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  74816. return;
  74817. }
  74818. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74819. },
  74820. enumerable: true,
  74821. configurable: true
  74822. });
  74823. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  74824. /**
  74825. * Gets if the current filter is set to "close ESM" (using the inverse of the
  74826. * exponential to prevent steep falloff artifacts).
  74827. */
  74828. get: function () {
  74829. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  74830. },
  74831. /**
  74832. * Sets the current filter to "close ESM" (using the inverse of the
  74833. * exponential to prevent steep falloff artifacts).
  74834. */
  74835. set: function (value) {
  74836. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  74837. return;
  74838. }
  74839. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74840. },
  74841. enumerable: true,
  74842. configurable: true
  74843. });
  74844. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  74845. /**
  74846. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  74847. * exponential to prevent steep falloff artifacts).
  74848. */
  74849. get: function () {
  74850. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  74851. },
  74852. /**
  74853. * Sets the current filter to filtered "close ESM" (using the inverse of the
  74854. * exponential to prevent steep falloff artifacts).
  74855. */
  74856. set: function (value) {
  74857. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  74858. return;
  74859. }
  74860. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  74861. },
  74862. enumerable: true,
  74863. configurable: true
  74864. });
  74865. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  74866. /**
  74867. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  74868. */
  74869. get: function () {
  74870. return this.filter === ShadowGenerator.FILTER_PCF;
  74871. },
  74872. /**
  74873. * Sets the current filter to "PCF" (percentage closer filtering).
  74874. */
  74875. set: function (value) {
  74876. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  74877. return;
  74878. }
  74879. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  74880. },
  74881. enumerable: true,
  74882. configurable: true
  74883. });
  74884. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  74885. /**
  74886. * Gets the PCF or PCSS Quality.
  74887. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74888. */
  74889. get: function () {
  74890. return this._filteringQuality;
  74891. },
  74892. /**
  74893. * Sets the PCF or PCSS Quality.
  74894. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  74895. */
  74896. set: function (filteringQuality) {
  74897. this._filteringQuality = filteringQuality;
  74898. },
  74899. enumerable: true,
  74900. configurable: true
  74901. });
  74902. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  74903. /**
  74904. * Gets if the current filter is set to "PCSS" (contact hardening).
  74905. */
  74906. get: function () {
  74907. return this.filter === ShadowGenerator.FILTER_PCSS;
  74908. },
  74909. /**
  74910. * Sets the current filter to "PCSS" (contact hardening).
  74911. */
  74912. set: function (value) {
  74913. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  74914. return;
  74915. }
  74916. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  74917. },
  74918. enumerable: true,
  74919. configurable: true
  74920. });
  74921. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  74922. /**
  74923. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74924. * Using a ratio helps keeping shape stability independently of the map size.
  74925. *
  74926. * It does not account for the light projection as it was having too much
  74927. * instability during the light setup or during light position changes.
  74928. *
  74929. * Only valid if useContactHardeningShadow is true.
  74930. */
  74931. get: function () {
  74932. return this._contactHardeningLightSizeUVRatio;
  74933. },
  74934. /**
  74935. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  74936. * Using a ratio helps keeping shape stability independently of the map size.
  74937. *
  74938. * It does not account for the light projection as it was having too much
  74939. * instability during the light setup or during light position changes.
  74940. *
  74941. * Only valid if useContactHardeningShadow is true.
  74942. */
  74943. set: function (contactHardeningLightSizeUVRatio) {
  74944. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  74945. },
  74946. enumerable: true,
  74947. configurable: true
  74948. });
  74949. /**
  74950. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  74951. * 0 means strongest and 1 would means no shadow.
  74952. * @returns the darkness.
  74953. */
  74954. ShadowGenerator.prototype.getDarkness = function () {
  74955. return this._darkness;
  74956. };
  74957. /**
  74958. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  74959. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  74960. * @returns the shadow generator allowing fluent coding.
  74961. */
  74962. ShadowGenerator.prototype.setDarkness = function (darkness) {
  74963. if (darkness >= 1.0)
  74964. this._darkness = 1.0;
  74965. else if (darkness <= 0.0)
  74966. this._darkness = 0.0;
  74967. else
  74968. this._darkness = darkness;
  74969. return this;
  74970. };
  74971. /**
  74972. * Sets the ability to have transparent shadow (boolean).
  74973. * @param transparent True if transparent else False
  74974. * @returns the shadow generator allowing fluent coding
  74975. */
  74976. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  74977. this._transparencyShadow = transparent;
  74978. return this;
  74979. };
  74980. /**
  74981. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  74982. * @returns The render target texture if present otherwise, null
  74983. */
  74984. ShadowGenerator.prototype.getShadowMap = function () {
  74985. return this._shadowMap;
  74986. };
  74987. /**
  74988. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  74989. * @returns The render target texture if the shadow map is present otherwise, null
  74990. */
  74991. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  74992. if (this._shadowMap2) {
  74993. return this._shadowMap2;
  74994. }
  74995. return this._shadowMap;
  74996. };
  74997. /**
  74998. * Helper function to add a mesh and its descendants to the list of shadow casters.
  74999. * @param mesh Mesh to add
  75000. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  75001. * @returns the Shadow Generator itself
  75002. */
  75003. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  75004. if (includeDescendants === void 0) { includeDescendants = true; }
  75005. var _a;
  75006. if (!this._shadowMap) {
  75007. return this;
  75008. }
  75009. if (!this._shadowMap.renderList) {
  75010. this._shadowMap.renderList = [];
  75011. }
  75012. this._shadowMap.renderList.push(mesh);
  75013. if (includeDescendants) {
  75014. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  75015. }
  75016. return this;
  75017. };
  75018. /**
  75019. * Helper function to remove a mesh and its descendants from the list of shadow casters
  75020. * @param mesh Mesh to remove
  75021. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  75022. * @returns the Shadow Generator itself
  75023. */
  75024. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  75025. if (includeDescendants === void 0) { includeDescendants = true; }
  75026. if (!this._shadowMap || !this._shadowMap.renderList) {
  75027. return this;
  75028. }
  75029. var index = this._shadowMap.renderList.indexOf(mesh);
  75030. if (index !== -1) {
  75031. this._shadowMap.renderList.splice(index, 1);
  75032. }
  75033. if (includeDescendants) {
  75034. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  75035. var child = _a[_i];
  75036. this.removeShadowCaster(child);
  75037. }
  75038. }
  75039. return this;
  75040. };
  75041. /**
  75042. * Returns the associated light object.
  75043. * @returns the light generating the shadow
  75044. */
  75045. ShadowGenerator.prototype.getLight = function () {
  75046. return this._light;
  75047. };
  75048. ShadowGenerator.prototype._initializeGenerator = function () {
  75049. this._light._markMeshesAsLightDirty();
  75050. this._initializeShadowMap();
  75051. };
  75052. ShadowGenerator.prototype._initializeShadowMap = function () {
  75053. var _this = this;
  75054. // Render target
  75055. var engine = this._scene.getEngine();
  75056. if (engine.webGLVersion > 1) {
  75057. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  75058. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  75059. }
  75060. else {
  75061. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  75062. }
  75063. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75064. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75065. this._shadowMap.anisotropicFilteringLevel = 1;
  75066. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75067. this._shadowMap.renderParticles = false;
  75068. this._shadowMap.ignoreCameraViewport = true;
  75069. // Record Face Index before render.
  75070. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  75071. _this._currentFaceIndex = faceIndex;
  75072. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75073. engine.setColorWrite(false);
  75074. }
  75075. });
  75076. // Custom render function.
  75077. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  75078. // Blur if required afer render.
  75079. this._shadowMap.onAfterUnbindObservable.add(function () {
  75080. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75081. engine.setColorWrite(true);
  75082. }
  75083. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  75084. return;
  75085. }
  75086. var shadowMap = _this.getShadowMapForRendering();
  75087. if (shadowMap) {
  75088. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  75089. }
  75090. });
  75091. // Clear according to the chosen filter.
  75092. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  75093. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  75094. this._shadowMap.onClearObservable.add(function (engine) {
  75095. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  75096. engine.clear(clearOne, false, true, false);
  75097. }
  75098. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  75099. engine.clear(clearZero, true, true, false);
  75100. }
  75101. else {
  75102. engine.clear(clearOne, true, true, false);
  75103. }
  75104. });
  75105. };
  75106. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  75107. var _this = this;
  75108. var engine = this._scene.getEngine();
  75109. var targetSize = this._mapSize / this.blurScale;
  75110. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  75111. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  75112. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75113. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  75114. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75115. }
  75116. if (this.useKernelBlur) {
  75117. 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);
  75118. this._kernelBlurXPostprocess.width = targetSize;
  75119. this._kernelBlurXPostprocess.height = targetSize;
  75120. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  75121. effect.setTexture("textureSampler", _this._shadowMap);
  75122. });
  75123. 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);
  75124. this._kernelBlurXPostprocess.autoClear = false;
  75125. this._kernelBlurYPostprocess.autoClear = false;
  75126. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75127. this._kernelBlurXPostprocess.packedFloat = true;
  75128. this._kernelBlurYPostprocess.packedFloat = true;
  75129. }
  75130. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  75131. }
  75132. else {
  75133. 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);
  75134. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  75135. effect.setFloat2("screenSize", targetSize, targetSize);
  75136. effect.setTexture("textureSampler", _this._shadowMap);
  75137. });
  75138. this._boxBlurPostprocess.autoClear = false;
  75139. this._blurPostProcesses = [this._boxBlurPostprocess];
  75140. }
  75141. };
  75142. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  75143. var index;
  75144. var engine = this._scene.getEngine();
  75145. if (depthOnlySubMeshes.length) {
  75146. engine.setColorWrite(false);
  75147. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  75148. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  75149. }
  75150. engine.setColorWrite(true);
  75151. }
  75152. for (index = 0; index < opaqueSubMeshes.length; index++) {
  75153. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  75154. }
  75155. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  75156. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  75157. }
  75158. if (this._transparencyShadow) {
  75159. for (index = 0; index < transparentSubMeshes.length; index++) {
  75160. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  75161. }
  75162. }
  75163. };
  75164. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  75165. var _this = this;
  75166. var mesh = subMesh.getRenderingMesh();
  75167. var scene = this._scene;
  75168. var engine = scene.getEngine();
  75169. var material = subMesh.getMaterial();
  75170. if (!material) {
  75171. return;
  75172. }
  75173. // Culling
  75174. engine.setState(material.backFaceCulling);
  75175. // Managing instances
  75176. var batch = mesh._getInstancesRenderList(subMesh._id);
  75177. if (batch.mustReturn) {
  75178. return;
  75179. }
  75180. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  75181. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  75182. engine.enableEffect(this._effect);
  75183. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  75184. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  75185. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  75186. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75187. this._effect.setVector3("lightData", this._cachedDirection);
  75188. }
  75189. else {
  75190. this._effect.setVector3("lightData", this._cachedPosition);
  75191. }
  75192. if (scene.activeCamera) {
  75193. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  75194. }
  75195. // Alpha test
  75196. if (material && material.needAlphaTesting()) {
  75197. var alphaTexture = material.getAlphaTestTexture();
  75198. if (alphaTexture) {
  75199. this._effect.setTexture("diffuseSampler", alphaTexture);
  75200. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  75201. }
  75202. }
  75203. // Bones
  75204. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75205. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  75206. }
  75207. // Morph targets
  75208. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  75209. if (this.forceBackFacesOnly) {
  75210. engine.setState(true, 0, false, true);
  75211. }
  75212. // Draw
  75213. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  75214. if (this.forceBackFacesOnly) {
  75215. engine.setState(true, 0, false, false);
  75216. }
  75217. }
  75218. else {
  75219. // Need to reset refresh rate of the shadowMap
  75220. if (this._shadowMap) {
  75221. this._shadowMap.resetRefreshCounter();
  75222. }
  75223. }
  75224. };
  75225. ShadowGenerator.prototype._applyFilterValues = function () {
  75226. if (!this._shadowMap) {
  75227. return;
  75228. }
  75229. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  75230. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  75231. }
  75232. else {
  75233. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  75234. }
  75235. };
  75236. /**
  75237. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75238. * @param onCompiled Callback triggered at the and of the effects compilation
  75239. * @param options Sets of optional options forcing the compilation with different modes
  75240. */
  75241. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  75242. var _this = this;
  75243. var localOptions = __assign({ useInstances: false }, options);
  75244. var shadowMap = this.getShadowMap();
  75245. if (!shadowMap) {
  75246. if (onCompiled) {
  75247. onCompiled(this);
  75248. }
  75249. return;
  75250. }
  75251. var renderList = shadowMap.renderList;
  75252. if (!renderList) {
  75253. if (onCompiled) {
  75254. onCompiled(this);
  75255. }
  75256. return;
  75257. }
  75258. var subMeshes = new Array();
  75259. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  75260. var mesh = renderList_1[_i];
  75261. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  75262. }
  75263. if (subMeshes.length === 0) {
  75264. if (onCompiled) {
  75265. onCompiled(this);
  75266. }
  75267. return;
  75268. }
  75269. var currentIndex = 0;
  75270. var checkReady = function () {
  75271. if (!_this._scene || !_this._scene.getEngine()) {
  75272. return;
  75273. }
  75274. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  75275. currentIndex++;
  75276. if (currentIndex >= subMeshes.length) {
  75277. if (onCompiled) {
  75278. onCompiled(_this);
  75279. }
  75280. return;
  75281. }
  75282. }
  75283. setTimeout(checkReady, 16);
  75284. };
  75285. checkReady();
  75286. };
  75287. /**
  75288. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  75289. * @param options Sets of optional options forcing the compilation with different modes
  75290. * @returns A promise that resolves when the compilation completes
  75291. */
  75292. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  75293. var _this = this;
  75294. return new Promise(function (resolve) {
  75295. _this.forceCompilation(function () {
  75296. resolve();
  75297. }, options);
  75298. });
  75299. };
  75300. /**
  75301. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  75302. * @param subMesh The submesh we want to render in the shadow map
  75303. * @param useInstances Defines wether will draw in the map using instances
  75304. * @returns true if ready otherwise, false
  75305. */
  75306. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  75307. var defines = [];
  75308. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  75309. defines.push("#define FLOAT");
  75310. }
  75311. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75312. defines.push("#define ESM");
  75313. }
  75314. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  75315. defines.push("#define DEPTHTEXTURE");
  75316. }
  75317. var attribs = [BABYLON.VertexBuffer.PositionKind];
  75318. var mesh = subMesh.getMesh();
  75319. var material = subMesh.getMaterial();
  75320. // Normal bias.
  75321. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  75322. attribs.push(BABYLON.VertexBuffer.NormalKind);
  75323. defines.push("#define NORMAL");
  75324. if (mesh.nonUniformScaling) {
  75325. defines.push("#define NONUNIFORMSCALING");
  75326. }
  75327. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  75328. defines.push("#define DIRECTIONINLIGHTDATA");
  75329. }
  75330. }
  75331. // Alpha test
  75332. if (material && material.needAlphaTesting()) {
  75333. var alphaTexture = material.getAlphaTestTexture();
  75334. if (alphaTexture) {
  75335. defines.push("#define ALPHATEST");
  75336. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  75337. attribs.push(BABYLON.VertexBuffer.UVKind);
  75338. defines.push("#define UV1");
  75339. }
  75340. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  75341. if (alphaTexture.coordinatesIndex === 1) {
  75342. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  75343. defines.push("#define UV2");
  75344. }
  75345. }
  75346. }
  75347. }
  75348. // Bones
  75349. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  75350. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  75351. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  75352. if (mesh.numBoneInfluencers > 4) {
  75353. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  75354. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  75355. }
  75356. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  75357. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  75358. }
  75359. else {
  75360. defines.push("#define NUM_BONE_INFLUENCERS 0");
  75361. }
  75362. // Morph targets
  75363. var manager = mesh.morphTargetManager;
  75364. var morphInfluencers = 0;
  75365. if (manager) {
  75366. if (manager.numInfluencers > 0) {
  75367. defines.push("#define MORPHTARGETS");
  75368. morphInfluencers = manager.numInfluencers;
  75369. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  75370. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  75371. }
  75372. }
  75373. // Instances
  75374. if (useInstances) {
  75375. defines.push("#define INSTANCES");
  75376. attribs.push("world0");
  75377. attribs.push("world1");
  75378. attribs.push("world2");
  75379. attribs.push("world3");
  75380. }
  75381. // Get correct effect
  75382. var join = defines.join("\n");
  75383. if (this._cachedDefines !== join) {
  75384. this._cachedDefines = join;
  75385. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  75386. }
  75387. if (!this._effect.isReady()) {
  75388. return false;
  75389. }
  75390. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75391. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  75392. this._initializeBlurRTTAndPostProcesses();
  75393. }
  75394. }
  75395. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  75396. return false;
  75397. }
  75398. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  75399. return false;
  75400. }
  75401. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  75402. return false;
  75403. }
  75404. return true;
  75405. };
  75406. /**
  75407. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  75408. * @param defines Defines of the material we want to update
  75409. * @param lightIndex Index of the light in the enabled light list of the material
  75410. */
  75411. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  75412. var scene = this._scene;
  75413. var light = this._light;
  75414. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75415. return;
  75416. }
  75417. defines["SHADOW" + lightIndex] = true;
  75418. if (this.useContactHardeningShadow) {
  75419. defines["SHADOWPCSS" + lightIndex] = true;
  75420. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75421. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75422. }
  75423. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75424. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75425. }
  75426. // else default to high.
  75427. }
  75428. if (this.usePercentageCloserFiltering) {
  75429. defines["SHADOWPCF" + lightIndex] = true;
  75430. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  75431. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  75432. }
  75433. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  75434. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  75435. }
  75436. // else default to high.
  75437. }
  75438. else if (this.usePoissonSampling) {
  75439. defines["SHADOWPOISSON" + lightIndex] = true;
  75440. }
  75441. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  75442. defines["SHADOWESM" + lightIndex] = true;
  75443. }
  75444. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  75445. defines["SHADOWCLOSEESM" + lightIndex] = true;
  75446. }
  75447. if (light.needCube()) {
  75448. defines["SHADOWCUBE" + lightIndex] = true;
  75449. }
  75450. };
  75451. /**
  75452. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  75453. * defined in the generator but impacting the effect).
  75454. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  75455. * @param effect The effect we are binfing the information for
  75456. */
  75457. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  75458. var light = this._light;
  75459. var scene = this._scene;
  75460. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  75461. return;
  75462. }
  75463. var camera = scene.activeCamera;
  75464. if (!camera) {
  75465. return;
  75466. }
  75467. var shadowMap = this.getShadowMap();
  75468. if (!shadowMap) {
  75469. return;
  75470. }
  75471. if (!light.needCube()) {
  75472. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  75473. }
  75474. // Only PCF uses depth stencil texture.
  75475. if (this._filter === ShadowGenerator.FILTER_PCF) {
  75476. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75477. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75478. }
  75479. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  75480. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75481. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  75482. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  75483. }
  75484. else {
  75485. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  75486. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  75487. }
  75488. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  75489. };
  75490. /**
  75491. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  75492. * (eq to shadow prjection matrix * light transform matrix)
  75493. * @returns The transform matrix used to create the shadow map
  75494. */
  75495. ShadowGenerator.prototype.getTransformMatrix = function () {
  75496. var scene = this._scene;
  75497. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  75498. return this._transformMatrix;
  75499. }
  75500. this._currentRenderID = scene.getRenderId();
  75501. this._currentFaceIndexCache = this._currentFaceIndex;
  75502. var lightPosition = this._light.position;
  75503. if (this._light.computeTransformedInformation()) {
  75504. lightPosition = this._light.transformedPosition;
  75505. }
  75506. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  75507. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  75508. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  75509. }
  75510. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  75511. this._cachedPosition.copyFrom(lightPosition);
  75512. this._cachedDirection.copyFrom(this._lightDirection);
  75513. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  75514. var shadowMap = this.getShadowMap();
  75515. if (shadowMap) {
  75516. var renderList = shadowMap.renderList;
  75517. if (renderList) {
  75518. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  75519. }
  75520. }
  75521. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  75522. }
  75523. return this._transformMatrix;
  75524. };
  75525. /**
  75526. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  75527. * Cube and 2D textures for instance.
  75528. */
  75529. ShadowGenerator.prototype.recreateShadowMap = function () {
  75530. var shadowMap = this._shadowMap;
  75531. if (!shadowMap) {
  75532. return;
  75533. }
  75534. // Track render list.
  75535. var renderList = shadowMap.renderList;
  75536. // Clean up existing data.
  75537. this._disposeRTTandPostProcesses();
  75538. // Reinitializes.
  75539. this._initializeGenerator();
  75540. // Reaffect the filter to ensure a correct fallback if necessary.
  75541. this.filter = this.filter;
  75542. // Reaffect the filter.
  75543. this._applyFilterValues();
  75544. // Reaffect Render List.
  75545. this._shadowMap.renderList = renderList;
  75546. };
  75547. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  75548. if (this._shadowMap2) {
  75549. this._shadowMap2.dispose();
  75550. this._shadowMap2 = null;
  75551. }
  75552. if (this._boxBlurPostprocess) {
  75553. this._boxBlurPostprocess.dispose();
  75554. this._boxBlurPostprocess = null;
  75555. }
  75556. if (this._kernelBlurXPostprocess) {
  75557. this._kernelBlurXPostprocess.dispose();
  75558. this._kernelBlurXPostprocess = null;
  75559. }
  75560. if (this._kernelBlurYPostprocess) {
  75561. this._kernelBlurYPostprocess.dispose();
  75562. this._kernelBlurYPostprocess = null;
  75563. }
  75564. this._blurPostProcesses = [];
  75565. };
  75566. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  75567. if (this._shadowMap) {
  75568. this._shadowMap.dispose();
  75569. this._shadowMap = null;
  75570. }
  75571. this._disposeBlurPostProcesses();
  75572. };
  75573. /**
  75574. * Disposes the ShadowGenerator.
  75575. * Returns nothing.
  75576. */
  75577. ShadowGenerator.prototype.dispose = function () {
  75578. this._disposeRTTandPostProcesses();
  75579. if (this._light) {
  75580. this._light._shadowGenerator = null;
  75581. this._light._markMeshesAsLightDirty();
  75582. }
  75583. };
  75584. /**
  75585. * Serializes the shadow generator setup to a json object.
  75586. * @returns The serialized JSON object
  75587. */
  75588. ShadowGenerator.prototype.serialize = function () {
  75589. var serializationObject = {};
  75590. var shadowMap = this.getShadowMap();
  75591. if (!shadowMap) {
  75592. return serializationObject;
  75593. }
  75594. serializationObject.lightId = this._light.id;
  75595. serializationObject.mapSize = shadowMap.getRenderSize();
  75596. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  75597. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  75598. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75599. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  75600. serializationObject.usePoissonSampling = this.usePoissonSampling;
  75601. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  75602. serializationObject.depthScale = this.depthScale;
  75603. serializationObject.darkness = this.getDarkness();
  75604. serializationObject.blurBoxOffset = this.blurBoxOffset;
  75605. serializationObject.blurKernel = this.blurKernel;
  75606. serializationObject.blurScale = this.blurScale;
  75607. serializationObject.useKernelBlur = this.useKernelBlur;
  75608. serializationObject.transparencyShadow = this._transparencyShadow;
  75609. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  75610. serializationObject.bias = this.bias;
  75611. serializationObject.normalBias = this.normalBias;
  75612. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  75613. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  75614. serializationObject.filteringQuality = this.filteringQuality;
  75615. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  75616. serializationObject.renderList = [];
  75617. if (shadowMap.renderList) {
  75618. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  75619. var mesh = shadowMap.renderList[meshIndex];
  75620. serializationObject.renderList.push(mesh.id);
  75621. }
  75622. }
  75623. return serializationObject;
  75624. };
  75625. /**
  75626. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  75627. * @param parsedShadowGenerator The JSON object to parse
  75628. * @param scene The scene to create the shadow map for
  75629. * @returns The parsed shadow generator
  75630. */
  75631. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  75632. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  75633. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  75634. var shadowMap = shadowGenerator.getShadowMap();
  75635. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  75636. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  75637. meshes.forEach(function (mesh) {
  75638. if (!shadowMap) {
  75639. return;
  75640. }
  75641. if (!shadowMap.renderList) {
  75642. shadowMap.renderList = [];
  75643. }
  75644. shadowMap.renderList.push(mesh);
  75645. });
  75646. }
  75647. if (parsedShadowGenerator.usePoissonSampling) {
  75648. shadowGenerator.usePoissonSampling = true;
  75649. }
  75650. else if (parsedShadowGenerator.useExponentialShadowMap) {
  75651. shadowGenerator.useExponentialShadowMap = true;
  75652. }
  75653. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  75654. shadowGenerator.useBlurExponentialShadowMap = true;
  75655. }
  75656. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  75657. shadowGenerator.useCloseExponentialShadowMap = true;
  75658. }
  75659. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  75660. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  75661. }
  75662. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  75663. shadowGenerator.usePercentageCloserFiltering = true;
  75664. }
  75665. else if (parsedShadowGenerator.useContactHardeningShadow) {
  75666. shadowGenerator.useContactHardeningShadow = true;
  75667. }
  75668. if (parsedShadowGenerator.filteringQuality) {
  75669. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  75670. }
  75671. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  75672. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  75673. }
  75674. // Backward compat
  75675. else if (parsedShadowGenerator.useVarianceShadowMap) {
  75676. shadowGenerator.useExponentialShadowMap = true;
  75677. }
  75678. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  75679. shadowGenerator.useBlurExponentialShadowMap = true;
  75680. }
  75681. if (parsedShadowGenerator.depthScale) {
  75682. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  75683. }
  75684. if (parsedShadowGenerator.blurScale) {
  75685. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  75686. }
  75687. if (parsedShadowGenerator.blurBoxOffset) {
  75688. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  75689. }
  75690. if (parsedShadowGenerator.useKernelBlur) {
  75691. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  75692. }
  75693. if (parsedShadowGenerator.blurKernel) {
  75694. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  75695. }
  75696. if (parsedShadowGenerator.bias !== undefined) {
  75697. shadowGenerator.bias = parsedShadowGenerator.bias;
  75698. }
  75699. if (parsedShadowGenerator.normalBias !== undefined) {
  75700. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  75701. }
  75702. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  75703. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  75704. }
  75705. if (parsedShadowGenerator.darkness) {
  75706. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  75707. }
  75708. if (parsedShadowGenerator.transparencyShadow) {
  75709. shadowGenerator.setTransparencyShadow(true);
  75710. }
  75711. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  75712. return shadowGenerator;
  75713. };
  75714. /**
  75715. * Shadow generator mode None: no filtering applied.
  75716. */
  75717. ShadowGenerator.FILTER_NONE = 0;
  75718. /**
  75719. * Shadow generator mode ESM: Exponential Shadow Mapping.
  75720. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75721. */
  75722. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  75723. /**
  75724. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  75725. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  75726. */
  75727. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  75728. /**
  75729. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  75730. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75731. */
  75732. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  75733. /**
  75734. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  75735. * edge artifacts on steep falloff.
  75736. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75737. */
  75738. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  75739. /**
  75740. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  75741. * edge artifacts on steep falloff.
  75742. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  75743. */
  75744. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  75745. /**
  75746. * Shadow generator mode PCF: Percentage Closer Filtering
  75747. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75748. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  75749. */
  75750. ShadowGenerator.FILTER_PCF = 6;
  75751. /**
  75752. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  75753. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  75754. * Contact Hardening
  75755. */
  75756. ShadowGenerator.FILTER_PCSS = 7;
  75757. /**
  75758. * Reserved for PCF and PCSS
  75759. * Highest Quality.
  75760. *
  75761. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  75762. *
  75763. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  75764. */
  75765. ShadowGenerator.QUALITY_HIGH = 0;
  75766. /**
  75767. * Reserved for PCF and PCSS
  75768. * Good tradeoff for quality/perf cross devices
  75769. *
  75770. * Execute PCF on a 3*3 kernel.
  75771. *
  75772. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  75773. */
  75774. ShadowGenerator.QUALITY_MEDIUM = 1;
  75775. /**
  75776. * Reserved for PCF and PCSS
  75777. * The lowest quality but the fastest.
  75778. *
  75779. * Execute PCF on a 1*1 kernel.
  75780. *
  75781. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  75782. */
  75783. ShadowGenerator.QUALITY_LOW = 2;
  75784. return ShadowGenerator;
  75785. }());
  75786. BABYLON.ShadowGenerator = ShadowGenerator;
  75787. })(BABYLON || (BABYLON = {}));
  75788. //# sourceMappingURL=babylon.shadowGenerator.js.map
  75789. var BABYLON;
  75790. (function (BABYLON) {
  75791. // Adds the parser to the scene parsers.
  75792. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR, function (parsedData, scene, container, rootUrl) {
  75793. // Shadows
  75794. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  75795. for (var index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  75796. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  75797. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  75798. // SG would be available on their associated lights
  75799. }
  75800. }
  75801. });
  75802. /**
  75803. * Defines the shadow generator component responsible to manage any shadow generators
  75804. * in a given scene.
  75805. */
  75806. var ShadowGeneratorSceneComponent = /** @class */ (function () {
  75807. /**
  75808. * Creates a new instance of the component for the given scene
  75809. * @param scene Defines the scene to register the component in
  75810. */
  75811. function ShadowGeneratorSceneComponent(scene) {
  75812. /**
  75813. * The component name helpfull to identify the component in the list of scene components.
  75814. */
  75815. this.name = BABYLON.SceneComponentConstants.NAME_SHADOWGENERATOR;
  75816. this.scene = scene;
  75817. }
  75818. /**
  75819. * Registers the component in a given scene
  75820. */
  75821. ShadowGeneratorSceneComponent.prototype.register = function () {
  75822. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_SHADOWGENERATOR, this, this._gatherRenderTargets);
  75823. };
  75824. /**
  75825. * Rebuilds the elements related to this component in case of
  75826. * context lost for instance.
  75827. */
  75828. ShadowGeneratorSceneComponent.prototype.rebuild = function () {
  75829. // Nothing To Do Here.
  75830. };
  75831. /**
  75832. * Serializes the component data to the specified json object
  75833. * @param serializationObject The object to serialize to
  75834. */
  75835. ShadowGeneratorSceneComponent.prototype.serialize = function (serializationObject) {
  75836. // Shadows
  75837. serializationObject.shadowGenerators = [];
  75838. var lights = this.scene.lights;
  75839. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  75840. var light = lights_1[_i];
  75841. var shadowGenerator = light.getShadowGenerator();
  75842. if (shadowGenerator) {
  75843. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  75844. }
  75845. }
  75846. };
  75847. /**
  75848. * Adds all the element from the container to the scene
  75849. * @param container the container holding the elements
  75850. */
  75851. ShadowGeneratorSceneComponent.prototype.addFromContainer = function (container) {
  75852. // Nothing To Do Here. (directly attached to a light)
  75853. };
  75854. /**
  75855. * Removes all the elements in the container from the scene
  75856. * @param container contains the elements to remove
  75857. */
  75858. ShadowGeneratorSceneComponent.prototype.removeFromContainer = function (container) {
  75859. // Nothing To Do Here. (directly attached to a light)
  75860. };
  75861. /**
  75862. * Rebuilds the elements related to this component in case of
  75863. * context lost for instance.
  75864. */
  75865. ShadowGeneratorSceneComponent.prototype.dispose = function () {
  75866. // Nothing To Do Here.
  75867. };
  75868. ShadowGeneratorSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  75869. // Shadows
  75870. var scene = this.scene;
  75871. if (this.scene.shadowsEnabled) {
  75872. for (var lightIndex = 0; lightIndex < scene.lights.length; lightIndex++) {
  75873. var light = scene.lights[lightIndex];
  75874. var shadowGenerator = light.getShadowGenerator();
  75875. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  75876. var shadowMap = (shadowGenerator.getShadowMap());
  75877. if (scene.textures.indexOf(shadowMap) !== -1) {
  75878. renderTargets.push(shadowMap);
  75879. }
  75880. }
  75881. }
  75882. }
  75883. };
  75884. return ShadowGeneratorSceneComponent;
  75885. }());
  75886. BABYLON.ShadowGeneratorSceneComponent = ShadowGeneratorSceneComponent;
  75887. })(BABYLON || (BABYLON = {}));
  75888. //# sourceMappingURL=babylon.shadowGeneratorSceneComponent.js.map
  75889. var BABYLON;
  75890. (function (BABYLON) {
  75891. /**
  75892. * Class used for the default loading screen
  75893. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  75894. */
  75895. var DefaultLoadingScreen = /** @class */ (function () {
  75896. /**
  75897. * Creates a new default loading screen
  75898. * @param _renderingCanvas defines the canvas used to render the scene
  75899. * @param _loadingText defines the default text to display
  75900. * @param _loadingDivBackgroundColor defines the default background color
  75901. */
  75902. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  75903. if (_loadingText === void 0) { _loadingText = ""; }
  75904. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  75905. var _this = this;
  75906. this._renderingCanvas = _renderingCanvas;
  75907. this._loadingText = _loadingText;
  75908. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  75909. // Resize
  75910. this._resizeLoadingUI = function () {
  75911. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  75912. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  75913. if (!_this._loadingDiv) {
  75914. return;
  75915. }
  75916. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  75917. _this._loadingDiv.style.left = canvasRect.left + "px";
  75918. _this._loadingDiv.style.top = canvasRect.top + "px";
  75919. _this._loadingDiv.style.width = canvasRect.width + "px";
  75920. _this._loadingDiv.style.height = canvasRect.height + "px";
  75921. };
  75922. }
  75923. /**
  75924. * Function called to display the loading screen
  75925. */
  75926. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  75927. if (this._loadingDiv) {
  75928. // Do not add a loading screen if there is already one
  75929. return;
  75930. }
  75931. this._loadingDiv = document.createElement("div");
  75932. this._loadingDiv.id = "babylonjsLoadingDiv";
  75933. this._loadingDiv.style.opacity = "0";
  75934. this._loadingDiv.style.transition = "opacity 1.5s ease";
  75935. this._loadingDiv.style.pointerEvents = "none";
  75936. // Loading text
  75937. this._loadingTextDiv = document.createElement("div");
  75938. this._loadingTextDiv.style.position = "absolute";
  75939. this._loadingTextDiv.style.left = "0";
  75940. this._loadingTextDiv.style.top = "50%";
  75941. this._loadingTextDiv.style.marginTop = "80px";
  75942. this._loadingTextDiv.style.width = "100%";
  75943. this._loadingTextDiv.style.height = "20px";
  75944. this._loadingTextDiv.style.fontFamily = "Arial";
  75945. this._loadingTextDiv.style.fontSize = "14px";
  75946. this._loadingTextDiv.style.color = "white";
  75947. this._loadingTextDiv.style.textAlign = "center";
  75948. this._loadingTextDiv.innerHTML = "Loading";
  75949. this._loadingDiv.appendChild(this._loadingTextDiv);
  75950. //set the predefined text
  75951. this._loadingTextDiv.innerHTML = this._loadingText;
  75952. // Generating keyframes
  75953. var style = document.createElement('style');
  75954. style.type = 'text/css';
  75955. 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 }";
  75956. style.innerHTML = keyFrames;
  75957. document.getElementsByTagName('head')[0].appendChild(style);
  75958. // Loading img
  75959. var imgBack = new Image();
  75960. 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";
  75961. imgBack.style.position = "absolute";
  75962. imgBack.style.left = "50%";
  75963. imgBack.style.top = "50%";
  75964. imgBack.style.marginLeft = "-60px";
  75965. imgBack.style.marginTop = "-60px";
  75966. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  75967. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  75968. imgBack.style.transformOrigin = "50% 50%";
  75969. imgBack.style.webkitTransformOrigin = "50% 50%";
  75970. this._loadingDiv.appendChild(imgBack);
  75971. this._resizeLoadingUI();
  75972. window.addEventListener("resize", this._resizeLoadingUI);
  75973. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  75974. document.body.appendChild(this._loadingDiv);
  75975. this._loadingDiv.style.opacity = "1";
  75976. };
  75977. /**
  75978. * Function called to hide the loading screen
  75979. */
  75980. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  75981. var _this = this;
  75982. if (!this._loadingDiv) {
  75983. return;
  75984. }
  75985. var onTransitionEnd = function () {
  75986. if (!_this._loadingDiv) {
  75987. return;
  75988. }
  75989. document.body.removeChild(_this._loadingDiv);
  75990. window.removeEventListener("resize", _this._resizeLoadingUI);
  75991. _this._loadingDiv = null;
  75992. };
  75993. this._loadingDiv.style.opacity = "0";
  75994. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  75995. };
  75996. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  75997. get: function () {
  75998. return this._loadingText;
  75999. },
  76000. /**
  76001. * Gets or sets the text to display while loading
  76002. */
  76003. set: function (text) {
  76004. this._loadingText = text;
  76005. if (this._loadingTextDiv) {
  76006. this._loadingTextDiv.innerHTML = this._loadingText;
  76007. }
  76008. },
  76009. enumerable: true,
  76010. configurable: true
  76011. });
  76012. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  76013. /**
  76014. * Gets or sets the color to use for the background
  76015. */
  76016. get: function () {
  76017. return this._loadingDivBackgroundColor;
  76018. },
  76019. set: function (color) {
  76020. this._loadingDivBackgroundColor = color;
  76021. if (!this._loadingDiv) {
  76022. return;
  76023. }
  76024. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  76025. },
  76026. enumerable: true,
  76027. configurable: true
  76028. });
  76029. return DefaultLoadingScreen;
  76030. }());
  76031. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  76032. })(BABYLON || (BABYLON = {}));
  76033. //# sourceMappingURL=babylon.loadingScreen.js.map
  76034. var BABYLON;
  76035. (function (BABYLON) {
  76036. /**
  76037. * Class used to represent data loading progression
  76038. */
  76039. var SceneLoaderProgressEvent = /** @class */ (function () {
  76040. /**
  76041. * Create a new progress event
  76042. * @param lengthComputable defines if data length to load can be evaluated
  76043. * @param loaded defines the loaded data length
  76044. * @param total defines the data length to load
  76045. */
  76046. function SceneLoaderProgressEvent(
  76047. /** defines if data length to load can be evaluated */
  76048. lengthComputable,
  76049. /** defines the loaded data length */
  76050. loaded,
  76051. /** defines the data length to load */
  76052. total) {
  76053. this.lengthComputable = lengthComputable;
  76054. this.loaded = loaded;
  76055. this.total = total;
  76056. }
  76057. /**
  76058. * Creates a new SceneLoaderProgressEvent from a ProgressEvent
  76059. * @param event defines the source event
  76060. * @returns a new SceneLoaderProgressEvent
  76061. */
  76062. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  76063. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  76064. };
  76065. return SceneLoaderProgressEvent;
  76066. }());
  76067. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  76068. /**
  76069. * Class used to load scene from various file formats using registered plugins
  76070. * @see http://doc.babylonjs.com/how_to/load_from_any_file_type
  76071. */
  76072. var SceneLoader = /** @class */ (function () {
  76073. function SceneLoader() {
  76074. }
  76075. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  76076. /**
  76077. * Gets or sets a boolean indicating if entire scene must be loaded even if scene contains incremental data
  76078. */
  76079. get: function () {
  76080. return SceneLoader._ForceFullSceneLoadingForIncremental;
  76081. },
  76082. set: function (value) {
  76083. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  76084. },
  76085. enumerable: true,
  76086. configurable: true
  76087. });
  76088. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  76089. /**
  76090. * Gets or sets a boolean indicating if loading screen must be displayed while loading a scene
  76091. */
  76092. get: function () {
  76093. return SceneLoader._ShowLoadingScreen;
  76094. },
  76095. set: function (value) {
  76096. SceneLoader._ShowLoadingScreen = value;
  76097. },
  76098. enumerable: true,
  76099. configurable: true
  76100. });
  76101. Object.defineProperty(SceneLoader, "loggingLevel", {
  76102. /**
  76103. * Defines the current logging level (while loading the scene)
  76104. * @ignorenaming
  76105. */
  76106. get: function () {
  76107. return SceneLoader._loggingLevel;
  76108. },
  76109. set: function (value) {
  76110. SceneLoader._loggingLevel = value;
  76111. },
  76112. enumerable: true,
  76113. configurable: true
  76114. });
  76115. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  76116. /**
  76117. * Gets or set a boolean indicating if matrix weights must be cleaned upon loading
  76118. */
  76119. get: function () {
  76120. return SceneLoader._CleanBoneMatrixWeights;
  76121. },
  76122. set: function (value) {
  76123. SceneLoader._CleanBoneMatrixWeights = value;
  76124. },
  76125. enumerable: true,
  76126. configurable: true
  76127. });
  76128. SceneLoader._getDefaultPlugin = function () {
  76129. return SceneLoader._registeredPlugins[".babylon"];
  76130. };
  76131. SceneLoader._getPluginForExtension = function (extension) {
  76132. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  76133. if (registeredPlugin) {
  76134. return registeredPlugin;
  76135. }
  76136. 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");
  76137. return SceneLoader._getDefaultPlugin();
  76138. };
  76139. SceneLoader._getPluginForDirectLoad = function (data) {
  76140. for (var extension in SceneLoader._registeredPlugins) {
  76141. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  76142. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  76143. return SceneLoader._registeredPlugins[extension];
  76144. }
  76145. }
  76146. return SceneLoader._getDefaultPlugin();
  76147. };
  76148. SceneLoader._getPluginForFilename = function (sceneFilename) {
  76149. var queryStringPosition = sceneFilename.indexOf("?");
  76150. if (queryStringPosition !== -1) {
  76151. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  76152. }
  76153. var dotPosition = sceneFilename.lastIndexOf(".");
  76154. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  76155. return SceneLoader._getPluginForExtension(extension);
  76156. };
  76157. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  76158. SceneLoader._getDirectLoad = function (sceneFilename) {
  76159. if (sceneFilename.substr(0, 5) === "data:") {
  76160. return sceneFilename.substr(5);
  76161. }
  76162. return null;
  76163. };
  76164. SceneLoader._loadData = function (fileInfo, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  76165. var directLoad = SceneLoader._getDirectLoad(fileInfo.name);
  76166. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(fileInfo.name) : SceneLoader._getPluginForFilename(fileInfo.name));
  76167. var plugin;
  76168. if (registeredPlugin.plugin.createPlugin) {
  76169. plugin = registeredPlugin.plugin.createPlugin();
  76170. }
  76171. else {
  76172. plugin = registeredPlugin.plugin;
  76173. }
  76174. var useArrayBuffer = registeredPlugin.isBinary;
  76175. var database;
  76176. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  76177. var dataCallback = function (data, responseURL) {
  76178. if (scene.isDisposed) {
  76179. onError("Scene has been disposed");
  76180. return;
  76181. }
  76182. scene.database = database;
  76183. onSuccess(plugin, data, responseURL);
  76184. };
  76185. var request = null;
  76186. var pluginDisposed = false;
  76187. var onDisposeObservable = plugin.onDisposeObservable;
  76188. if (onDisposeObservable) {
  76189. onDisposeObservable.add(function () {
  76190. pluginDisposed = true;
  76191. if (request) {
  76192. request.abort();
  76193. request = null;
  76194. }
  76195. onDispose();
  76196. });
  76197. }
  76198. var manifestChecked = function () {
  76199. if (pluginDisposed) {
  76200. return;
  76201. }
  76202. request = BABYLON.Tools.LoadFile(fileInfo.url, dataCallback, onProgress ? function (event) {
  76203. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  76204. } : undefined, database, useArrayBuffer, function (request, exception) {
  76205. onError("Failed to load scene." + (exception ? " " + exception.message : ""), exception);
  76206. });
  76207. };
  76208. if (directLoad) {
  76209. dataCallback(directLoad);
  76210. return plugin;
  76211. }
  76212. if (fileInfo.rootUrl.indexOf("file:") === -1) {
  76213. var engine = scene.getEngine();
  76214. var canUseOfflineSupport = engine.enableOfflineSupport;
  76215. if (canUseOfflineSupport) {
  76216. // Also check for exceptions
  76217. var exceptionFound = false;
  76218. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  76219. var regex = _a[_i];
  76220. if (regex.test(fileInfo.url)) {
  76221. exceptionFound = true;
  76222. break;
  76223. }
  76224. }
  76225. canUseOfflineSupport = !exceptionFound;
  76226. }
  76227. if (canUseOfflineSupport) {
  76228. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  76229. database = new BABYLON.Database(fileInfo.url, manifestChecked, engine.disableManifestCheck);
  76230. }
  76231. else {
  76232. manifestChecked();
  76233. }
  76234. }
  76235. // Loading file from disk via input file or drag'n'drop
  76236. else {
  76237. var file = BABYLON.FilesInput.FilesToLoad[fileInfo.name.toLowerCase()];
  76238. if (file) {
  76239. request = BABYLON.Tools.ReadFile(file, dataCallback, onProgress, useArrayBuffer);
  76240. }
  76241. else {
  76242. onError("Unable to find file named " + fileInfo.name);
  76243. }
  76244. }
  76245. return plugin;
  76246. };
  76247. SceneLoader._getFileInfo = function (rootUrl, sceneFilename) {
  76248. var url;
  76249. var name;
  76250. if (!sceneFilename) {
  76251. url = rootUrl;
  76252. name = BABYLON.Tools.GetFilename(rootUrl);
  76253. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  76254. }
  76255. else {
  76256. if (sceneFilename.substr(0, 1) === "/") {
  76257. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  76258. return null;
  76259. }
  76260. url = rootUrl + sceneFilename;
  76261. name = sceneFilename;
  76262. }
  76263. ;
  76264. return {
  76265. url: url,
  76266. rootUrl: rootUrl,
  76267. name: name
  76268. };
  76269. };
  76270. // Public functions
  76271. /**
  76272. * Gets a plugin that can load the given extension
  76273. * @param extension defines the extension to load
  76274. * @returns a plugin or null if none works
  76275. */
  76276. SceneLoader.GetPluginForExtension = function (extension) {
  76277. return SceneLoader._getPluginForExtension(extension).plugin;
  76278. };
  76279. /**
  76280. * Gets a boolean indicating that the given extension can be loaded
  76281. * @param extension defines the extension to load
  76282. * @returns true if the extension is supported
  76283. */
  76284. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  76285. return !!SceneLoader._registeredPlugins[extension];
  76286. };
  76287. /**
  76288. * Adds a new plugin to the list of registered plugins
  76289. * @param plugin defines the plugin to add
  76290. */
  76291. SceneLoader.RegisterPlugin = function (plugin) {
  76292. if (typeof plugin.extensions === "string") {
  76293. var extension = plugin.extensions;
  76294. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76295. plugin: plugin,
  76296. isBinary: false
  76297. };
  76298. }
  76299. else {
  76300. var extensions = plugin.extensions;
  76301. Object.keys(extensions).forEach(function (extension) {
  76302. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  76303. plugin: plugin,
  76304. isBinary: extensions[extension].isBinary
  76305. };
  76306. });
  76307. }
  76308. };
  76309. /**
  76310. * Import meshes into a scene
  76311. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76312. * @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)
  76313. * @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)
  76314. * @param scene the instance of BABYLON.Scene to append to
  76315. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  76316. * @param onProgress a callback with a progress event for each file being loaded
  76317. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76318. * @param pluginExtension the extension used to determine the plugin
  76319. * @returns The loaded plugin
  76320. */
  76321. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76322. if (sceneFilename === void 0) { sceneFilename = ""; }
  76323. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76324. if (onSuccess === void 0) { onSuccess = null; }
  76325. if (onProgress === void 0) { onProgress = null; }
  76326. if (onError === void 0) { onError = null; }
  76327. if (pluginExtension === void 0) { pluginExtension = null; }
  76328. if (!scene) {
  76329. BABYLON.Tools.Error("No scene available to import mesh to");
  76330. return null;
  76331. }
  76332. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76333. if (!fileInfo) {
  76334. return null;
  76335. }
  76336. var loadingToken = {};
  76337. scene._addPendingData(loadingToken);
  76338. var disposeHandler = function () {
  76339. scene._removePendingData(loadingToken);
  76340. };
  76341. var errorHandler = function (message, exception) {
  76342. var errorMessage = "Unable to import meshes from " + fileInfo.url + ": " + message;
  76343. if (onError) {
  76344. onError(scene, errorMessage, exception);
  76345. }
  76346. else {
  76347. BABYLON.Tools.Error(errorMessage);
  76348. // should the exception be thrown?
  76349. }
  76350. disposeHandler();
  76351. };
  76352. var progressHandler = onProgress ? function (event) {
  76353. try {
  76354. onProgress(event);
  76355. }
  76356. catch (e) {
  76357. errorHandler("Error in onProgress callback", e);
  76358. }
  76359. } : undefined;
  76360. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  76361. scene.importedMeshesFiles.push(fileInfo.url);
  76362. if (onSuccess) {
  76363. try {
  76364. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  76365. }
  76366. catch (e) {
  76367. errorHandler("Error in onSuccess callback", e);
  76368. }
  76369. }
  76370. scene._removePendingData(loadingToken);
  76371. };
  76372. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76373. if (plugin.rewriteRootURL) {
  76374. fileInfo.rootUrl = plugin.rewriteRootURL(fileInfo.rootUrl, responseURL);
  76375. }
  76376. if (plugin.importMesh) {
  76377. var syncedPlugin = plugin;
  76378. var meshes = new Array();
  76379. var particleSystems = new Array();
  76380. var skeletons = new Array();
  76381. if (!syncedPlugin.importMesh(meshNames, scene, data, fileInfo.rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  76382. return;
  76383. }
  76384. scene.loadingPluginName = plugin.name;
  76385. successHandler(meshes, particleSystems, skeletons, []);
  76386. }
  76387. else {
  76388. var asyncedPlugin = plugin;
  76389. asyncedPlugin.importMeshAsync(meshNames, scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (result) {
  76390. scene.loadingPluginName = plugin.name;
  76391. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  76392. }).catch(function (error) {
  76393. errorHandler(error.message, error);
  76394. });
  76395. }
  76396. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76397. };
  76398. /**
  76399. * Import meshes into a scene
  76400. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  76401. * @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)
  76402. * @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)
  76403. * @param scene the instance of BABYLON.Scene to append to
  76404. * @param onProgress a callback with a progress event for each file being loaded
  76405. * @param pluginExtension the extension used to determine the plugin
  76406. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  76407. */
  76408. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76409. if (sceneFilename === void 0) { sceneFilename = ""; }
  76410. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76411. if (onProgress === void 0) { onProgress = null; }
  76412. if (pluginExtension === void 0) { pluginExtension = null; }
  76413. return new Promise(function (resolve, reject) {
  76414. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  76415. resolve({
  76416. meshes: meshes,
  76417. particleSystems: particleSystems,
  76418. skeletons: skeletons,
  76419. animationGroups: animationGroups
  76420. });
  76421. }, onProgress, function (scene, message, exception) {
  76422. reject(exception || new Error(message));
  76423. }, pluginExtension);
  76424. });
  76425. };
  76426. /**
  76427. * Load a scene
  76428. * @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)
  76429. * @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)
  76430. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76431. * @param onSuccess a callback with the scene when import succeeds
  76432. * @param onProgress a callback with a progress event for each file being loaded
  76433. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76434. * @param pluginExtension the extension used to determine the plugin
  76435. * @returns The loaded plugin
  76436. */
  76437. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  76438. if (onSuccess === void 0) { onSuccess = null; }
  76439. if (onProgress === void 0) { onProgress = null; }
  76440. if (onError === void 0) { onError = null; }
  76441. if (pluginExtension === void 0) { pluginExtension = null; }
  76442. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  76443. };
  76444. /**
  76445. * Load a scene
  76446. * @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)
  76447. * @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)
  76448. * @param engine is the instance of BABYLON.Engine to use to create the scene
  76449. * @param onProgress a callback with a progress event for each file being loaded
  76450. * @param pluginExtension the extension used to determine the plugin
  76451. * @returns The loaded scene
  76452. */
  76453. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  76454. if (onProgress === void 0) { onProgress = null; }
  76455. if (pluginExtension === void 0) { pluginExtension = null; }
  76456. return new Promise(function (resolve, reject) {
  76457. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  76458. resolve(scene);
  76459. }, onProgress, function (scene, message, exception) {
  76460. reject(exception || new Error(message));
  76461. }, pluginExtension);
  76462. });
  76463. };
  76464. /**
  76465. * Append a scene
  76466. * @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)
  76467. * @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)
  76468. * @param scene is the instance of BABYLON.Scene to append to
  76469. * @param onSuccess a callback with the scene when import succeeds
  76470. * @param onProgress a callback with a progress event for each file being loaded
  76471. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76472. * @param pluginExtension the extension used to determine the plugin
  76473. * @returns The loaded plugin
  76474. */
  76475. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76476. if (sceneFilename === void 0) { sceneFilename = ""; }
  76477. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76478. if (onSuccess === void 0) { onSuccess = null; }
  76479. if (onProgress === void 0) { onProgress = null; }
  76480. if (onError === void 0) { onError = null; }
  76481. if (pluginExtension === void 0) { pluginExtension = null; }
  76482. if (!scene) {
  76483. BABYLON.Tools.Error("No scene available to append to");
  76484. return null;
  76485. }
  76486. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76487. if (!fileInfo) {
  76488. return null;
  76489. }
  76490. if (SceneLoader.ShowLoadingScreen) {
  76491. scene.getEngine().displayLoadingUI();
  76492. }
  76493. var loadingToken = {};
  76494. scene._addPendingData(loadingToken);
  76495. var disposeHandler = function () {
  76496. scene._removePendingData(loadingToken);
  76497. scene.getEngine().hideLoadingUI();
  76498. };
  76499. var errorHandler = function (message, exception) {
  76500. var errorMessage = "Unable to load from " + fileInfo.url + (message ? ": " + message : "");
  76501. if (onError) {
  76502. onError(scene, errorMessage, exception);
  76503. }
  76504. else {
  76505. BABYLON.Tools.Error(errorMessage);
  76506. // should the exception be thrown?
  76507. }
  76508. disposeHandler();
  76509. };
  76510. var progressHandler = onProgress ? function (event) {
  76511. try {
  76512. onProgress(event);
  76513. }
  76514. catch (e) {
  76515. errorHandler("Error in onProgress callback", e);
  76516. }
  76517. } : undefined;
  76518. var successHandler = function () {
  76519. if (onSuccess) {
  76520. try {
  76521. onSuccess(scene);
  76522. }
  76523. catch (e) {
  76524. errorHandler("Error in onSuccess callback", e);
  76525. }
  76526. }
  76527. scene._removePendingData(loadingToken);
  76528. };
  76529. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76530. if (plugin.load) {
  76531. var syncedPlugin = plugin;
  76532. if (!syncedPlugin.load(scene, data, fileInfo.rootUrl, errorHandler)) {
  76533. return;
  76534. }
  76535. scene.loadingPluginName = plugin.name;
  76536. successHandler();
  76537. }
  76538. else {
  76539. var asyncedPlugin = plugin;
  76540. asyncedPlugin.loadAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function () {
  76541. scene.loadingPluginName = plugin.name;
  76542. successHandler();
  76543. }).catch(function (error) {
  76544. errorHandler(error.message, error);
  76545. });
  76546. }
  76547. if (SceneLoader.ShowLoadingScreen) {
  76548. scene.executeWhenReady(function () {
  76549. scene.getEngine().hideLoadingUI();
  76550. });
  76551. }
  76552. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76553. };
  76554. /**
  76555. * Append a scene
  76556. * @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)
  76557. * @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)
  76558. * @param scene is the instance of BABYLON.Scene to append to
  76559. * @param onProgress a callback with a progress event for each file being loaded
  76560. * @param pluginExtension the extension used to determine the plugin
  76561. * @returns The given scene
  76562. */
  76563. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76564. if (sceneFilename === void 0) { sceneFilename = ""; }
  76565. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76566. if (onProgress === void 0) { onProgress = null; }
  76567. if (pluginExtension === void 0) { pluginExtension = null; }
  76568. return new Promise(function (resolve, reject) {
  76569. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  76570. resolve(scene);
  76571. }, onProgress, function (scene, message, exception) {
  76572. reject(exception || new Error(message));
  76573. }, pluginExtension);
  76574. });
  76575. };
  76576. /**
  76577. * Load a scene into an asset container
  76578. * @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)
  76579. * @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)
  76580. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  76581. * @param onSuccess a callback with the scene when import succeeds
  76582. * @param onProgress a callback with a progress event for each file being loaded
  76583. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  76584. * @param pluginExtension the extension used to determine the plugin
  76585. * @returns The loaded plugin
  76586. */
  76587. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  76588. if (sceneFilename === void 0) { sceneFilename = ""; }
  76589. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76590. if (onSuccess === void 0) { onSuccess = null; }
  76591. if (onProgress === void 0) { onProgress = null; }
  76592. if (onError === void 0) { onError = null; }
  76593. if (pluginExtension === void 0) { pluginExtension = null; }
  76594. if (!scene) {
  76595. BABYLON.Tools.Error("No scene available to load asset container to");
  76596. return null;
  76597. }
  76598. var fileInfo = SceneLoader._getFileInfo(rootUrl, sceneFilename);
  76599. if (!fileInfo) {
  76600. return null;
  76601. }
  76602. var loadingToken = {};
  76603. scene._addPendingData(loadingToken);
  76604. var disposeHandler = function () {
  76605. scene._removePendingData(loadingToken);
  76606. };
  76607. var errorHandler = function (message, exception) {
  76608. var errorMessage = "Unable to load assets from " + fileInfo.url + (message ? ": " + message : "");
  76609. if (onError) {
  76610. onError(scene, errorMessage, exception);
  76611. }
  76612. else {
  76613. BABYLON.Tools.Error(errorMessage);
  76614. // should the exception be thrown?
  76615. }
  76616. disposeHandler();
  76617. };
  76618. var progressHandler = onProgress ? function (event) {
  76619. try {
  76620. onProgress(event);
  76621. }
  76622. catch (e) {
  76623. errorHandler("Error in onProgress callback", e);
  76624. }
  76625. } : undefined;
  76626. var successHandler = function (assets) {
  76627. if (onSuccess) {
  76628. try {
  76629. onSuccess(assets);
  76630. }
  76631. catch (e) {
  76632. errorHandler("Error in onSuccess callback", e);
  76633. }
  76634. }
  76635. scene._removePendingData(loadingToken);
  76636. };
  76637. return SceneLoader._loadData(fileInfo, scene, function (plugin, data, responseURL) {
  76638. if (plugin.loadAssetContainer) {
  76639. var syncedPlugin = plugin;
  76640. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, fileInfo.rootUrl, errorHandler);
  76641. if (!assetContainer) {
  76642. return;
  76643. }
  76644. scene.loadingPluginName = plugin.name;
  76645. successHandler(assetContainer);
  76646. }
  76647. else if (plugin.loadAssetContainerAsync) {
  76648. var asyncedPlugin = plugin;
  76649. asyncedPlugin.loadAssetContainerAsync(scene, data, fileInfo.rootUrl, progressHandler, fileInfo.name).then(function (assetContainer) {
  76650. scene.loadingPluginName = plugin.name;
  76651. successHandler(assetContainer);
  76652. }).catch(function (error) {
  76653. errorHandler(error.message, error);
  76654. });
  76655. }
  76656. else {
  76657. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  76658. }
  76659. if (SceneLoader.ShowLoadingScreen) {
  76660. scene.executeWhenReady(function () {
  76661. scene.getEngine().hideLoadingUI();
  76662. });
  76663. }
  76664. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  76665. };
  76666. /**
  76667. * Load a scene into an asset container
  76668. * @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)
  76669. * @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)
  76670. * @param scene is the instance of BABYLON.Scene to append to
  76671. * @param onProgress a callback with a progress event for each file being loaded
  76672. * @param pluginExtension the extension used to determine the plugin
  76673. * @returns The loaded asset container
  76674. */
  76675. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  76676. if (sceneFilename === void 0) { sceneFilename = ""; }
  76677. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76678. if (onProgress === void 0) { onProgress = null; }
  76679. if (pluginExtension === void 0) { pluginExtension = null; }
  76680. return new Promise(function (resolve, reject) {
  76681. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  76682. resolve(assetContainer);
  76683. }, onProgress, function (scene, message, exception) {
  76684. reject(exception || new Error(message));
  76685. }, pluginExtension);
  76686. });
  76687. };
  76688. // Flags
  76689. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  76690. SceneLoader._ShowLoadingScreen = true;
  76691. SceneLoader._CleanBoneMatrixWeights = false;
  76692. /**
  76693. * No logging while loading
  76694. */
  76695. SceneLoader.NO_LOGGING = 0;
  76696. /**
  76697. * Minimal logging while loading
  76698. */
  76699. SceneLoader.MINIMAL_LOGGING = 1;
  76700. /**
  76701. * Summary logging while loading
  76702. */
  76703. SceneLoader.SUMMARY_LOGGING = 2;
  76704. /**
  76705. * Detailled logging while loading
  76706. */
  76707. SceneLoader.DETAILED_LOGGING = 3;
  76708. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  76709. // Members
  76710. /**
  76711. * Event raised when a plugin is used to load a scene
  76712. */
  76713. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  76714. SceneLoader._registeredPlugins = {};
  76715. return SceneLoader;
  76716. }());
  76717. BABYLON.SceneLoader = SceneLoader;
  76718. ;
  76719. })(BABYLON || (BABYLON = {}));
  76720. //# sourceMappingURL=babylon.sceneLoader.js.map
  76721. var BABYLON;
  76722. (function (BABYLON) {
  76723. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  76724. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76725. var parsedMaterial = parsedData.materials[index];
  76726. if (parsedMaterial.id === id) {
  76727. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76728. }
  76729. }
  76730. return null;
  76731. };
  76732. var isDescendantOf = function (mesh, names, hierarchyIds) {
  76733. for (var i in names) {
  76734. if (mesh.name === names[i]) {
  76735. hierarchyIds.push(mesh.id);
  76736. return true;
  76737. }
  76738. }
  76739. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  76740. hierarchyIds.push(mesh.id);
  76741. return true;
  76742. }
  76743. return false;
  76744. };
  76745. var logOperation = function (operation, producer) {
  76746. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  76747. };
  76748. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  76749. if (addToScene === void 0) { addToScene = false; }
  76750. var container = new BABYLON.AssetContainer(scene);
  76751. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  76752. // when SceneLoader.debugLogging = true (default), or exception encountered.
  76753. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  76754. // and avoid problems with multiple concurrent .babylon loads.
  76755. var log = "importScene has failed JSON parse";
  76756. try {
  76757. var parsedData = JSON.parse(data);
  76758. log = "";
  76759. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  76760. var index;
  76761. var cache;
  76762. // Lights
  76763. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  76764. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  76765. var parsedLight = parsedData.lights[index];
  76766. var light = BABYLON.Light.Parse(parsedLight, scene);
  76767. if (light) {
  76768. container.lights.push(light);
  76769. log += (index === 0 ? "\n\tLights:" : "");
  76770. log += "\n\t\t" + light.toString(fullDetails);
  76771. }
  76772. }
  76773. }
  76774. // Animations
  76775. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  76776. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  76777. var parsedAnimation = parsedData.animations[index];
  76778. var animation = BABYLON.Animation.Parse(parsedAnimation);
  76779. scene.animations.push(animation);
  76780. container.animations.push(animation);
  76781. log += (index === 0 ? "\n\tAnimations:" : "");
  76782. log += "\n\t\t" + animation.toString(fullDetails);
  76783. }
  76784. }
  76785. // Materials
  76786. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  76787. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  76788. var parsedMaterial = parsedData.materials[index];
  76789. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  76790. container.materials.push(mat);
  76791. log += (index === 0 ? "\n\tMaterials:" : "");
  76792. log += "\n\t\t" + mat.toString(fullDetails);
  76793. }
  76794. }
  76795. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  76796. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  76797. var parsedMultiMaterial = parsedData.multiMaterials[index];
  76798. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  76799. container.multiMaterials.push(mmat);
  76800. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  76801. log += "\n\t\t" + mmat.toString(fullDetails);
  76802. }
  76803. }
  76804. // Morph targets
  76805. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  76806. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  76807. var managerData = _a[_i];
  76808. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  76809. }
  76810. }
  76811. // Skeletons
  76812. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  76813. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  76814. var parsedSkeleton = parsedData.skeletons[index];
  76815. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  76816. container.skeletons.push(skeleton);
  76817. log += (index === 0 ? "\n\tSkeletons:" : "");
  76818. log += "\n\t\t" + skeleton.toString(fullDetails);
  76819. }
  76820. }
  76821. // Geometries
  76822. var geometries = parsedData.geometries;
  76823. if (geometries !== undefined && geometries !== null) {
  76824. var addedGeometry = new Array();
  76825. // Boxes
  76826. var boxes = geometries.boxes;
  76827. if (boxes !== undefined && boxes !== null) {
  76828. for (index = 0, cache = boxes.length; index < cache; index++) {
  76829. var parsedBox = boxes[index];
  76830. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  76831. }
  76832. }
  76833. // Spheres
  76834. var spheres = geometries.spheres;
  76835. if (spheres !== undefined && spheres !== null) {
  76836. for (index = 0, cache = spheres.length; index < cache; index++) {
  76837. var parsedSphere = spheres[index];
  76838. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  76839. }
  76840. }
  76841. // Cylinders
  76842. var cylinders = geometries.cylinders;
  76843. if (cylinders !== undefined && cylinders !== null) {
  76844. for (index = 0, cache = cylinders.length; index < cache; index++) {
  76845. var parsedCylinder = cylinders[index];
  76846. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  76847. }
  76848. }
  76849. // Toruses
  76850. var toruses = geometries.toruses;
  76851. if (toruses !== undefined && toruses !== null) {
  76852. for (index = 0, cache = toruses.length; index < cache; index++) {
  76853. var parsedTorus = toruses[index];
  76854. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  76855. }
  76856. }
  76857. // Grounds
  76858. var grounds = geometries.grounds;
  76859. if (grounds !== undefined && grounds !== null) {
  76860. for (index = 0, cache = grounds.length; index < cache; index++) {
  76861. var parsedGround = grounds[index];
  76862. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  76863. }
  76864. }
  76865. // Planes
  76866. var planes = geometries.planes;
  76867. if (planes !== undefined && planes !== null) {
  76868. for (index = 0, cache = planes.length; index < cache; index++) {
  76869. var parsedPlane = planes[index];
  76870. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  76871. }
  76872. }
  76873. // TorusKnots
  76874. var torusKnots = geometries.torusKnots;
  76875. if (torusKnots !== undefined && torusKnots !== null) {
  76876. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  76877. var parsedTorusKnot = torusKnots[index];
  76878. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  76879. }
  76880. }
  76881. // VertexData
  76882. var vertexData = geometries.vertexData;
  76883. if (vertexData !== undefined && vertexData !== null) {
  76884. for (index = 0, cache = vertexData.length; index < cache; index++) {
  76885. var parsedVertexData = vertexData[index];
  76886. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  76887. }
  76888. }
  76889. addedGeometry.forEach(function (g) {
  76890. if (g) {
  76891. container.geometries.push(g);
  76892. }
  76893. });
  76894. }
  76895. // Transform nodes
  76896. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  76897. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  76898. var parsedTransformNode = parsedData.transformNodes[index];
  76899. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  76900. container.transformNodes.push(node);
  76901. }
  76902. }
  76903. // Meshes
  76904. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  76905. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  76906. var parsedMesh = parsedData.meshes[index];
  76907. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  76908. container.meshes.push(mesh);
  76909. log += (index === 0 ? "\n\tMeshes:" : "");
  76910. log += "\n\t\t" + mesh.toString(fullDetails);
  76911. }
  76912. }
  76913. // Cameras
  76914. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  76915. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  76916. var parsedCamera = parsedData.cameras[index];
  76917. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  76918. container.cameras.push(camera);
  76919. log += (index === 0 ? "\n\tCameras:" : "");
  76920. log += "\n\t\t" + camera.toString(fullDetails);
  76921. }
  76922. }
  76923. // Animation Groups
  76924. if (parsedData.animationGroups !== undefined && parsedData.animationGroups !== null) {
  76925. for (index = 0, cache = parsedData.animationGroups.length; index < cache; index++) {
  76926. var parsedAnimationGroup = parsedData.animationGroups[index];
  76927. var animationGroup = BABYLON.AnimationGroup.Parse(parsedAnimationGroup, scene);
  76928. container.animationGroups.push(animationGroup);
  76929. log += (index === 0 ? "\n\tAnimationGroups:" : "");
  76930. log += "\n\t\t" + animationGroup.toString(fullDetails);
  76931. }
  76932. }
  76933. // Browsing all the graph to connect the dots
  76934. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  76935. var camera = scene.cameras[index];
  76936. if (camera._waitingParentId) {
  76937. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  76938. camera._waitingParentId = null;
  76939. }
  76940. }
  76941. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76942. var light_1 = scene.lights[index];
  76943. if (light_1 && light_1._waitingParentId) {
  76944. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  76945. light_1._waitingParentId = null;
  76946. }
  76947. }
  76948. // Connect parents & children and parse actions
  76949. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  76950. var transformNode = scene.transformNodes[index];
  76951. if (transformNode._waitingParentId) {
  76952. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  76953. transformNode._waitingParentId = null;
  76954. }
  76955. }
  76956. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76957. var mesh = scene.meshes[index];
  76958. if (mesh._waitingParentId) {
  76959. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  76960. mesh._waitingParentId = null;
  76961. }
  76962. }
  76963. // freeze world matrix application
  76964. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  76965. var currentMesh = scene.meshes[index];
  76966. if (currentMesh._waitingFreezeWorldMatrix) {
  76967. currentMesh.freezeWorldMatrix();
  76968. currentMesh._waitingFreezeWorldMatrix = null;
  76969. }
  76970. else {
  76971. currentMesh.computeWorldMatrix(true);
  76972. }
  76973. }
  76974. // Lights exclusions / inclusions
  76975. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  76976. var light_2 = scene.lights[index];
  76977. // Excluded check
  76978. if (light_2._excludedMeshesIds.length > 0) {
  76979. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  76980. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  76981. if (excludedMesh) {
  76982. light_2.excludedMeshes.push(excludedMesh);
  76983. }
  76984. }
  76985. light_2._excludedMeshesIds = [];
  76986. }
  76987. // Included check
  76988. if (light_2._includedOnlyMeshesIds.length > 0) {
  76989. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  76990. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  76991. if (includedOnlyMesh) {
  76992. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  76993. }
  76994. }
  76995. light_2._includedOnlyMeshesIds = [];
  76996. }
  76997. }
  76998. BABYLON.AbstractScene.Parse(parsedData, scene, container, rootUrl);
  76999. // Actions (scene) Done last as it can access other objects.
  77000. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77001. var mesh = scene.meshes[index];
  77002. if (mesh._waitingActions) {
  77003. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  77004. mesh._waitingActions = null;
  77005. }
  77006. }
  77007. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  77008. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  77009. }
  77010. if (!addToScene) {
  77011. container.removeAllFromScene();
  77012. }
  77013. }
  77014. catch (err) {
  77015. var msg = logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + log;
  77016. if (onError) {
  77017. onError(msg, err);
  77018. }
  77019. else {
  77020. BABYLON.Tools.Log(msg);
  77021. throw err;
  77022. }
  77023. }
  77024. finally {
  77025. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77026. BABYLON.Tools.Log(logOperation("loadAssets", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77027. }
  77028. }
  77029. return container;
  77030. };
  77031. BABYLON.SceneLoader.RegisterPlugin({
  77032. name: "babylon.js",
  77033. extensions: ".babylon",
  77034. canDirectLoad: function (data) {
  77035. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  77036. return true;
  77037. }
  77038. return false;
  77039. },
  77040. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  77041. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77042. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77043. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77044. // and avoid problems with multiple concurrent .babylon loads.
  77045. var log = "importMesh has failed JSON parse";
  77046. try {
  77047. var parsedData = JSON.parse(data);
  77048. log = "";
  77049. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  77050. if (!meshesNames) {
  77051. meshesNames = null;
  77052. }
  77053. else if (!Array.isArray(meshesNames)) {
  77054. meshesNames = [meshesNames];
  77055. }
  77056. var hierarchyIds = new Array();
  77057. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  77058. var loadedSkeletonsIds = [];
  77059. var loadedMaterialsIds = [];
  77060. var index;
  77061. var cache;
  77062. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  77063. var parsedMesh = parsedData.meshes[index];
  77064. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  77065. if (meshesNames !== null) {
  77066. // Remove found mesh name from list.
  77067. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  77068. }
  77069. //Geometry?
  77070. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  77071. //does the file contain geometries?
  77072. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  77073. //find the correct geometry and add it to the scene
  77074. var found = false;
  77075. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  77076. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  77077. return;
  77078. }
  77079. else {
  77080. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  77081. if (parsedGeometryData.id === parsedMesh.geometryId) {
  77082. switch (geometryType) {
  77083. case "boxes":
  77084. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  77085. break;
  77086. case "spheres":
  77087. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  77088. break;
  77089. case "cylinders":
  77090. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  77091. break;
  77092. case "toruses":
  77093. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  77094. break;
  77095. case "grounds":
  77096. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  77097. break;
  77098. case "planes":
  77099. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  77100. break;
  77101. case "torusKnots":
  77102. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  77103. break;
  77104. case "vertexData":
  77105. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  77106. break;
  77107. }
  77108. found = true;
  77109. }
  77110. });
  77111. }
  77112. });
  77113. if (found === false) {
  77114. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  77115. }
  77116. }
  77117. }
  77118. // Material ?
  77119. if (parsedMesh.materialId) {
  77120. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  77121. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  77122. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  77123. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  77124. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  77125. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  77126. var subMatId = parsedMultiMaterial.materials[matIndex];
  77127. loadedMaterialsIds.push(subMatId);
  77128. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  77129. if (mat) {
  77130. log += "\n\tMaterial " + mat.toString(fullDetails);
  77131. }
  77132. }
  77133. loadedMaterialsIds.push(parsedMultiMaterial.id);
  77134. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  77135. if (mmat) {
  77136. materialFound = true;
  77137. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  77138. }
  77139. break;
  77140. }
  77141. }
  77142. }
  77143. if (materialFound === false) {
  77144. loadedMaterialsIds.push(parsedMesh.materialId);
  77145. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  77146. if (!mat) {
  77147. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  77148. }
  77149. else {
  77150. log += "\n\tMaterial " + mat.toString(fullDetails);
  77151. }
  77152. }
  77153. }
  77154. // Skeleton ?
  77155. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  77156. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  77157. if (skeletonAlreadyLoaded === false) {
  77158. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  77159. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  77160. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  77161. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  77162. skeletons.push(skeleton);
  77163. loadedSkeletonsIds.push(parsedSkeleton.id);
  77164. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  77165. }
  77166. }
  77167. }
  77168. }
  77169. // Morph targets ?
  77170. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  77171. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  77172. var managerData = _a[_i];
  77173. BABYLON.MorphTargetManager.Parse(managerData, scene);
  77174. }
  77175. }
  77176. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  77177. meshes.push(mesh);
  77178. log += "\n\tMesh " + mesh.toString(fullDetails);
  77179. }
  77180. }
  77181. // Connecting parents
  77182. var currentMesh;
  77183. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77184. currentMesh = scene.meshes[index];
  77185. if (currentMesh._waitingParentId) {
  77186. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  77187. currentMesh._waitingParentId = null;
  77188. }
  77189. }
  77190. // freeze and compute world matrix application
  77191. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  77192. currentMesh = scene.meshes[index];
  77193. if (currentMesh._waitingFreezeWorldMatrix) {
  77194. currentMesh.freezeWorldMatrix();
  77195. currentMesh._waitingFreezeWorldMatrix = null;
  77196. }
  77197. else {
  77198. currentMesh.computeWorldMatrix(true);
  77199. }
  77200. }
  77201. }
  77202. // Particles
  77203. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  77204. var parser = BABYLON.AbstractScene.GetIndividualParser(BABYLON.SceneComponentConstants.NAME_PARTICLESYSTEM);
  77205. if (parser) {
  77206. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  77207. var parsedParticleSystem = parsedData.particleSystems[index];
  77208. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  77209. particleSystems.push(parser(parsedParticleSystem, scene, rootUrl));
  77210. }
  77211. }
  77212. }
  77213. }
  77214. return true;
  77215. }
  77216. catch (err) {
  77217. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  77218. if (onError) {
  77219. onError(msg, err);
  77220. }
  77221. else {
  77222. BABYLON.Tools.Log(msg);
  77223. throw err;
  77224. }
  77225. }
  77226. finally {
  77227. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77228. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77229. }
  77230. }
  77231. return false;
  77232. },
  77233. load: function (scene, data, rootUrl, onError) {
  77234. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  77235. // when SceneLoader.debugLogging = true (default), or exception encountered.
  77236. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  77237. // and avoid problems with multiple concurrent .babylon loads.
  77238. var log = "importScene has failed JSON parse";
  77239. try {
  77240. var parsedData = JSON.parse(data);
  77241. log = "";
  77242. // Scene
  77243. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  77244. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  77245. }
  77246. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  77247. scene.autoClear = parsedData.autoClear;
  77248. }
  77249. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  77250. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  77251. }
  77252. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  77253. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  77254. }
  77255. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  77256. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  77257. }
  77258. // Fog
  77259. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  77260. scene.fogMode = parsedData.fogMode;
  77261. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  77262. scene.fogStart = parsedData.fogStart;
  77263. scene.fogEnd = parsedData.fogEnd;
  77264. scene.fogDensity = parsedData.fogDensity;
  77265. log += "\tFog mode for scene: ";
  77266. switch (scene.fogMode) {
  77267. // getters not compiling, so using hardcoded
  77268. case 1:
  77269. log += "exp\n";
  77270. break;
  77271. case 2:
  77272. log += "exp2\n";
  77273. break;
  77274. case 3:
  77275. log += "linear\n";
  77276. break;
  77277. }
  77278. }
  77279. //Physics
  77280. if (parsedData.physicsEnabled) {
  77281. var physicsPlugin;
  77282. if (parsedData.physicsEngine === "cannon") {
  77283. physicsPlugin = new BABYLON.CannonJSPlugin();
  77284. }
  77285. else if (parsedData.physicsEngine === "oimo") {
  77286. physicsPlugin = new BABYLON.OimoJSPlugin();
  77287. }
  77288. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  77289. //else - default engine, which is currently oimo
  77290. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  77291. scene.enablePhysics(physicsGravity, physicsPlugin);
  77292. }
  77293. // Metadata
  77294. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  77295. scene.metadata = parsedData.metadata;
  77296. }
  77297. //collisions, if defined. otherwise, default is true
  77298. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  77299. scene.collisionsEnabled = parsedData.collisionsEnabled;
  77300. }
  77301. scene.workerCollisions = !!parsedData.workerCollisions;
  77302. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  77303. if (!container) {
  77304. return false;
  77305. }
  77306. if (parsedData.autoAnimate) {
  77307. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  77308. }
  77309. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  77310. scene.setActiveCameraByID(parsedData.activeCameraID);
  77311. }
  77312. // Environment texture
  77313. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  77314. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  77315. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  77316. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  77317. if (parsedData.environmentTextureRotationY) {
  77318. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  77319. }
  77320. scene.environmentTexture = hdrTexture;
  77321. }
  77322. else {
  77323. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  77324. if (parsedData.environmentTextureRotationY) {
  77325. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  77326. }
  77327. scene.environmentTexture = cubeTexture;
  77328. }
  77329. if (parsedData.createDefaultSkybox === true) {
  77330. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  77331. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  77332. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  77333. }
  77334. }
  77335. // Finish
  77336. return true;
  77337. }
  77338. catch (err) {
  77339. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  77340. if (onError) {
  77341. onError(msg, err);
  77342. }
  77343. else {
  77344. BABYLON.Tools.Log(msg);
  77345. throw err;
  77346. }
  77347. }
  77348. finally {
  77349. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  77350. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  77351. }
  77352. }
  77353. return false;
  77354. },
  77355. loadAssetContainer: function (scene, data, rootUrl, onError) {
  77356. var container = loadAssetContainer(scene, data, rootUrl, onError);
  77357. return container;
  77358. }
  77359. });
  77360. })(BABYLON || (BABYLON = {}));
  77361. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  77362. var BABYLON;
  77363. (function (BABYLON) {
  77364. /**
  77365. * Class used to help managing file picking and drag'n'drop
  77366. */
  77367. var FilesInput = /** @class */ (function () {
  77368. /**
  77369. * Creates a new FilesInput
  77370. * @param engine defines the rendering engine
  77371. * @param scene defines the hosting scene
  77372. * @param sceneLoadedCallback callback called when scene is loaded
  77373. * @param progressCallback callback called to track progress
  77374. * @param additionalRenderLoopLogicCallback callback called to add user logic to the rendering loop
  77375. * @param textureLoadingCallback callback called when a texture is loading
  77376. * @param startingProcessingFilesCallback callback called when the system is about to process all files
  77377. * @param onReloadCallback callback called when a reload is requested
  77378. * @param errorCallback callback call if an error occurs
  77379. */
  77380. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  77381. /**
  77382. * Callback called when a file is processed
  77383. */
  77384. this.onProcessFileCallback = function () { return true; };
  77385. this._engine = engine;
  77386. this._currentScene = scene;
  77387. this._sceneLoadedCallback = sceneLoadedCallback;
  77388. this._progressCallback = progressCallback;
  77389. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  77390. this._textureLoadingCallback = textureLoadingCallback;
  77391. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  77392. this._onReloadCallback = onReloadCallback;
  77393. this._errorCallback = errorCallback;
  77394. }
  77395. /**
  77396. * Calls this function to listen to drag'n'drop events on a specific DOM element
  77397. * @param elementToMonitor defines the DOM element to track
  77398. */
  77399. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  77400. var _this = this;
  77401. if (elementToMonitor) {
  77402. this._elementToMonitor = elementToMonitor;
  77403. this._dragEnterHandler = function (e) { _this.drag(e); };
  77404. this._dragOverHandler = function (e) { _this.drag(e); };
  77405. this._dropHandler = function (e) { _this.drop(e); };
  77406. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  77407. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  77408. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  77409. }
  77410. };
  77411. /**
  77412. * Release all associated resources
  77413. */
  77414. FilesInput.prototype.dispose = function () {
  77415. if (!this._elementToMonitor) {
  77416. return;
  77417. }
  77418. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  77419. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  77420. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  77421. };
  77422. FilesInput.prototype.renderFunction = function () {
  77423. if (this._additionalRenderLoopLogicCallback) {
  77424. this._additionalRenderLoopLogicCallback();
  77425. }
  77426. if (this._currentScene) {
  77427. if (this._textureLoadingCallback) {
  77428. var remaining = this._currentScene.getWaitingItemsCount();
  77429. if (remaining > 0) {
  77430. this._textureLoadingCallback(remaining);
  77431. }
  77432. }
  77433. this._currentScene.render();
  77434. }
  77435. };
  77436. FilesInput.prototype.drag = function (e) {
  77437. e.stopPropagation();
  77438. e.preventDefault();
  77439. };
  77440. FilesInput.prototype.drop = function (eventDrop) {
  77441. eventDrop.stopPropagation();
  77442. eventDrop.preventDefault();
  77443. this.loadFiles(eventDrop);
  77444. };
  77445. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  77446. var _this = this;
  77447. var reader = folder.createReader();
  77448. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  77449. reader.readEntries(function (entries) {
  77450. remaining.count += entries.length;
  77451. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  77452. var entry = entries_1[_i];
  77453. if (entry.isFile) {
  77454. entry.file(function (file) {
  77455. file.correctName = relativePath + file.name;
  77456. files.push(file);
  77457. if (--remaining.count === 0) {
  77458. callback();
  77459. }
  77460. });
  77461. }
  77462. else if (entry.isDirectory) {
  77463. _this._traverseFolder(entry, files, remaining, callback);
  77464. }
  77465. }
  77466. if (--remaining.count) {
  77467. callback();
  77468. }
  77469. });
  77470. };
  77471. FilesInput.prototype._processFiles = function (files) {
  77472. for (var i = 0; i < files.length; i++) {
  77473. var name = files[i].correctName.toLowerCase();
  77474. var extension = name.split('.').pop();
  77475. if (!this.onProcessFileCallback(files[i], name, extension)) {
  77476. continue;
  77477. }
  77478. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  77479. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  77480. this._sceneFileToLoad = files[i];
  77481. }
  77482. FilesInput.FilesToLoad[name] = files[i];
  77483. }
  77484. };
  77485. /**
  77486. * Load files from a drop event
  77487. * @param event defines the drop event to use as source
  77488. */
  77489. FilesInput.prototype.loadFiles = function (event) {
  77490. var _this = this;
  77491. // Handling data transfer via drag'n'drop
  77492. if (event && event.dataTransfer && event.dataTransfer.files) {
  77493. this._filesToLoad = event.dataTransfer.files;
  77494. }
  77495. // Handling files from input files
  77496. if (event && event.target && event.target.files) {
  77497. this._filesToLoad = event.target.files;
  77498. }
  77499. if (!this._filesToLoad || this._filesToLoad.length === 0) {
  77500. return;
  77501. }
  77502. if (this._startingProcessingFilesCallback) {
  77503. this._startingProcessingFilesCallback(this._filesToLoad);
  77504. }
  77505. if (this._filesToLoad && this._filesToLoad.length > 0) {
  77506. var files_1 = new Array();
  77507. var folders = [];
  77508. var items = event.dataTransfer ? event.dataTransfer.items : null;
  77509. for (var i = 0; i < this._filesToLoad.length; i++) {
  77510. var fileToLoad = this._filesToLoad[i];
  77511. var name_1 = fileToLoad.name.toLowerCase();
  77512. var entry = void 0;
  77513. fileToLoad.correctName = name_1;
  77514. if (items) {
  77515. var item = items[i];
  77516. if (item.getAsEntry) {
  77517. entry = item.getAsEntry();
  77518. }
  77519. else if (item.webkitGetAsEntry) {
  77520. entry = item.webkitGetAsEntry();
  77521. }
  77522. }
  77523. if (!entry) {
  77524. files_1.push(fileToLoad);
  77525. }
  77526. else {
  77527. if (entry.isDirectory) {
  77528. folders.push(entry);
  77529. }
  77530. else {
  77531. files_1.push(fileToLoad);
  77532. }
  77533. }
  77534. }
  77535. if (folders.length === 0) {
  77536. this._processFiles(files_1);
  77537. this._processReload();
  77538. }
  77539. else {
  77540. var remaining = { count: folders.length };
  77541. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  77542. var folder = folders_1[_i];
  77543. this._traverseFolder(folder, files_1, remaining, function () {
  77544. _this._processFiles(files_1);
  77545. if (remaining.count === 0) {
  77546. _this._processReload();
  77547. }
  77548. });
  77549. }
  77550. }
  77551. }
  77552. };
  77553. FilesInput.prototype._processReload = function () {
  77554. if (this._onReloadCallback) {
  77555. this._onReloadCallback(this._sceneFileToLoad);
  77556. }
  77557. else {
  77558. this.reload();
  77559. }
  77560. };
  77561. /**
  77562. * Reload the current scene from the loaded files
  77563. */
  77564. FilesInput.prototype.reload = function () {
  77565. var _this = this;
  77566. // If a scene file has been provided
  77567. if (this._sceneFileToLoad) {
  77568. if (this._currentScene) {
  77569. if (BABYLON.Tools.errorsCount > 0) {
  77570. BABYLON.Tools.ClearLogCache();
  77571. }
  77572. this._engine.stopRenderLoop();
  77573. }
  77574. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad.name, this._engine, function (progress) {
  77575. if (_this._progressCallback) {
  77576. _this._progressCallback(progress);
  77577. }
  77578. }).then(function (scene) {
  77579. if (_this._currentScene) {
  77580. _this._currentScene.dispose();
  77581. }
  77582. _this._currentScene = scene;
  77583. if (_this._sceneLoadedCallback) {
  77584. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  77585. }
  77586. // Wait for textures and shaders to be ready
  77587. _this._currentScene.executeWhenReady(function () {
  77588. _this._engine.runRenderLoop(function () {
  77589. _this.renderFunction();
  77590. });
  77591. });
  77592. }).catch(function (error) {
  77593. if (_this._errorCallback) {
  77594. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  77595. }
  77596. });
  77597. }
  77598. else {
  77599. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  77600. }
  77601. };
  77602. /**
  77603. * List of files ready to be loaded
  77604. */
  77605. FilesInput.FilesToLoad = {};
  77606. return FilesInput;
  77607. }());
  77608. BABYLON.FilesInput = FilesInput;
  77609. })(BABYLON || (BABYLON = {}));
  77610. //# sourceMappingURL=babylon.filesInput.js.map
  77611. var BABYLON;
  77612. (function (BABYLON) {
  77613. /**
  77614. * Class used to store custom tags
  77615. */
  77616. var Tags = /** @class */ (function () {
  77617. function Tags() {
  77618. }
  77619. /**
  77620. * Adds support for tags on the given object
  77621. * @param obj defines the object to use
  77622. */
  77623. Tags.EnableFor = function (obj) {
  77624. obj._tags = obj._tags || {};
  77625. obj.hasTags = function () {
  77626. return Tags.HasTags(obj);
  77627. };
  77628. obj.addTags = function (tagsString) {
  77629. return Tags.AddTagsTo(obj, tagsString);
  77630. };
  77631. obj.removeTags = function (tagsString) {
  77632. return Tags.RemoveTagsFrom(obj, tagsString);
  77633. };
  77634. obj.matchesTagsQuery = function (tagsQuery) {
  77635. return Tags.MatchesQuery(obj, tagsQuery);
  77636. };
  77637. };
  77638. /**
  77639. * Removes tags support
  77640. * @param obj defines the object to use
  77641. */
  77642. Tags.DisableFor = function (obj) {
  77643. delete obj._tags;
  77644. delete obj.hasTags;
  77645. delete obj.addTags;
  77646. delete obj.removeTags;
  77647. delete obj.matchesTagsQuery;
  77648. };
  77649. /**
  77650. * Gets a boolean indicating if the given object has tags
  77651. * @param obj defines the object to use
  77652. * @returns a boolean
  77653. */
  77654. Tags.HasTags = function (obj) {
  77655. if (!obj._tags) {
  77656. return false;
  77657. }
  77658. return !BABYLON.Tools.IsEmpty(obj._tags);
  77659. };
  77660. /**
  77661. * Gets the tags available on a given object
  77662. * @param obj defines the object to use
  77663. * @param asString defines if the tags must be returned as a string instead of an array of strings
  77664. * @returns the tags
  77665. */
  77666. Tags.GetTags = function (obj, asString) {
  77667. if (asString === void 0) { asString = true; }
  77668. if (!obj._tags) {
  77669. return null;
  77670. }
  77671. if (asString) {
  77672. var tagsArray = [];
  77673. for (var tag in obj._tags) {
  77674. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  77675. tagsArray.push(tag);
  77676. }
  77677. }
  77678. return tagsArray.join(" ");
  77679. }
  77680. else {
  77681. return obj._tags;
  77682. }
  77683. };
  77684. /**
  77685. * Adds tags to an object
  77686. * @param obj defines the object to use
  77687. * @param tagsString defines the tag string. The tags 'true' and 'false' are reserved and cannot be used as tags.
  77688. * A tag cannot start with '||', '&&', and '!'. It cannot contain whitespaces
  77689. */
  77690. Tags.AddTagsTo = function (obj, tagsString) {
  77691. if (!tagsString) {
  77692. return;
  77693. }
  77694. if (typeof tagsString !== "string") {
  77695. return;
  77696. }
  77697. var tags = tagsString.split(" ");
  77698. tags.forEach(function (tag, index, array) {
  77699. Tags._AddTagTo(obj, tag);
  77700. });
  77701. };
  77702. /**
  77703. * @hidden
  77704. */
  77705. Tags._AddTagTo = function (obj, tag) {
  77706. tag = tag.trim();
  77707. if (tag === "" || tag === "true" || tag === "false") {
  77708. return;
  77709. }
  77710. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  77711. return;
  77712. }
  77713. Tags.EnableFor(obj);
  77714. obj._tags[tag] = true;
  77715. };
  77716. /**
  77717. * Removes specific tags from a specific object
  77718. * @param obj defines the object to use
  77719. * @param tagsString defines the tags to remove
  77720. */
  77721. Tags.RemoveTagsFrom = function (obj, tagsString) {
  77722. if (!Tags.HasTags(obj)) {
  77723. return;
  77724. }
  77725. var tags = tagsString.split(" ");
  77726. for (var t in tags) {
  77727. Tags._RemoveTagFrom(obj, tags[t]);
  77728. }
  77729. };
  77730. /**
  77731. * @hidden
  77732. */
  77733. Tags._RemoveTagFrom = function (obj, tag) {
  77734. delete obj._tags[tag];
  77735. };
  77736. /**
  77737. * Defines if tags hosted on an object match a given query
  77738. * @param obj defines the object to use
  77739. * @param tagsQuery defines the tag query
  77740. * @returns a boolean
  77741. */
  77742. Tags.MatchesQuery = function (obj, tagsQuery) {
  77743. if (tagsQuery === undefined) {
  77744. return true;
  77745. }
  77746. if (tagsQuery === "") {
  77747. return Tags.HasTags(obj);
  77748. }
  77749. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  77750. };
  77751. return Tags;
  77752. }());
  77753. BABYLON.Tags = Tags;
  77754. })(BABYLON || (BABYLON = {}));
  77755. //# sourceMappingURL=babylon.tags.js.map
  77756. var BABYLON;
  77757. (function (BABYLON) {
  77758. /**
  77759. * Class used to evalaute queries containing `and` and `or` operators
  77760. */
  77761. var AndOrNotEvaluator = /** @class */ (function () {
  77762. function AndOrNotEvaluator() {
  77763. }
  77764. /**
  77765. * Evaluate a query
  77766. * @param query defines the query to evaluate
  77767. * @param evaluateCallback defines the callback used to filter result
  77768. * @returns true if the query matches
  77769. */
  77770. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  77771. if (!query.match(/\([^\(\)]*\)/g)) {
  77772. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  77773. }
  77774. else {
  77775. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  77776. // remove parenthesis
  77777. r = r.slice(1, r.length - 1);
  77778. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  77779. });
  77780. }
  77781. if (query === "true") {
  77782. return true;
  77783. }
  77784. if (query === "false") {
  77785. return false;
  77786. }
  77787. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  77788. };
  77789. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  77790. evaluateCallback = evaluateCallback || (function (r) {
  77791. return r === "true" ? true : false;
  77792. });
  77793. var result;
  77794. var or = parenthesisContent.split("||");
  77795. for (var i in or) {
  77796. if (or.hasOwnProperty(i)) {
  77797. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  77798. var and = ori.split("&&");
  77799. if (and.length > 1) {
  77800. for (var j = 0; j < and.length; ++j) {
  77801. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  77802. if (andj !== "true" && andj !== "false") {
  77803. if (andj[0] === "!") {
  77804. result = !evaluateCallback(andj.substring(1));
  77805. }
  77806. else {
  77807. result = evaluateCallback(andj);
  77808. }
  77809. }
  77810. else {
  77811. result = andj === "true" ? true : false;
  77812. }
  77813. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  77814. ori = "false";
  77815. break;
  77816. }
  77817. }
  77818. }
  77819. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  77820. result = true;
  77821. break;
  77822. }
  77823. // result equals false (or undefined)
  77824. if (ori !== "true" && ori !== "false") {
  77825. if (ori[0] === "!") {
  77826. result = !evaluateCallback(ori.substring(1));
  77827. }
  77828. else {
  77829. result = evaluateCallback(ori);
  77830. }
  77831. }
  77832. else {
  77833. result = ori === "true" ? true : false;
  77834. }
  77835. }
  77836. }
  77837. // the whole parenthesis scope is replaced by 'true' or 'false'
  77838. return result ? "true" : "false";
  77839. };
  77840. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  77841. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  77842. // remove whitespaces
  77843. r = r.replace(/[\s]/g, function () { return ""; });
  77844. return r.length % 2 ? "!" : "";
  77845. });
  77846. booleanString = booleanString.trim();
  77847. if (booleanString === "!true") {
  77848. booleanString = "false";
  77849. }
  77850. else if (booleanString === "!false") {
  77851. booleanString = "true";
  77852. }
  77853. return booleanString;
  77854. };
  77855. return AndOrNotEvaluator;
  77856. }());
  77857. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  77858. })(BABYLON || (BABYLON = {}));
  77859. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  77860. var BABYLON;
  77861. (function (BABYLON) {
  77862. /**
  77863. * Class used to enable access to IndexedDB
  77864. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  77865. */
  77866. var Database = /** @class */ (function () {
  77867. /**
  77868. * Creates a new Database
  77869. * @param urlToScene defines the url to load the scene
  77870. * @param callbackManifestChecked defines the callback to use when manifest is checked
  77871. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  77872. */
  77873. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  77874. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  77875. var _this = this;
  77876. // Handling various flavors of prefixed version of IndexedDB
  77877. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  77878. this.callbackManifestChecked = callbackManifestChecked;
  77879. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  77880. this.db = null;
  77881. this._enableSceneOffline = false;
  77882. this._enableTexturesOffline = false;
  77883. this.manifestVersionFound = 0;
  77884. this.mustUpdateRessources = false;
  77885. this.hasReachedQuota = false;
  77886. if (!Database.IDBStorageEnabled) {
  77887. this.callbackManifestChecked(true);
  77888. }
  77889. else {
  77890. if (disableManifestCheck) {
  77891. this._enableSceneOffline = true;
  77892. this._enableTexturesOffline = true;
  77893. this.manifestVersionFound = 1;
  77894. BABYLON.Tools.SetImmediate(function () {
  77895. _this.callbackManifestChecked(true);
  77896. });
  77897. }
  77898. else {
  77899. this._checkManifestFile();
  77900. }
  77901. }
  77902. }
  77903. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  77904. /**
  77905. * Gets a boolean indicating if scene must be saved in the database
  77906. */
  77907. get: function () {
  77908. return this._enableSceneOffline;
  77909. },
  77910. enumerable: true,
  77911. configurable: true
  77912. });
  77913. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  77914. /**
  77915. * Gets a boolean indicating if textures must be saved in the database
  77916. */
  77917. get: function () {
  77918. return this._enableTexturesOffline;
  77919. },
  77920. enumerable: true,
  77921. configurable: true
  77922. });
  77923. Database.prototype._checkManifestFile = function () {
  77924. var _this = this;
  77925. var noManifestFile = function () {
  77926. _this._enableSceneOffline = false;
  77927. _this._enableTexturesOffline = false;
  77928. _this.callbackManifestChecked(false);
  77929. };
  77930. var timeStampUsed = false;
  77931. var manifestURL = this.currentSceneUrl + ".manifest";
  77932. var xhr = new XMLHttpRequest();
  77933. if (navigator.onLine) {
  77934. // Adding a timestamp to by-pass browsers' cache
  77935. timeStampUsed = true;
  77936. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  77937. }
  77938. xhr.open("GET", manifestURL, true);
  77939. xhr.addEventListener("load", function () {
  77940. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  77941. try {
  77942. var manifestFile = JSON.parse(xhr.response);
  77943. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  77944. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  77945. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  77946. _this.manifestVersionFound = manifestFile.version;
  77947. }
  77948. if (_this.callbackManifestChecked) {
  77949. _this.callbackManifestChecked(true);
  77950. }
  77951. }
  77952. catch (ex) {
  77953. noManifestFile();
  77954. }
  77955. }
  77956. else {
  77957. noManifestFile();
  77958. }
  77959. }, false);
  77960. xhr.addEventListener("error", function (event) {
  77961. if (timeStampUsed) {
  77962. timeStampUsed = false;
  77963. // Let's retry without the timeStamp
  77964. // It could fail when coupled with HTML5 Offline API
  77965. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  77966. xhr.open("GET", retryManifestURL, true);
  77967. xhr.send();
  77968. }
  77969. else {
  77970. noManifestFile();
  77971. }
  77972. }, false);
  77973. try {
  77974. xhr.send();
  77975. }
  77976. catch (ex) {
  77977. BABYLON.Tools.Error("Error on XHR send request.");
  77978. this.callbackManifestChecked(false);
  77979. }
  77980. };
  77981. /**
  77982. * Open the database and make it available
  77983. * @param successCallback defines the callback to call on success
  77984. * @param errorCallback defines the callback to call on error
  77985. */
  77986. Database.prototype.openAsync = function (successCallback, errorCallback) {
  77987. var _this = this;
  77988. var handleError = function () {
  77989. _this.isSupported = false;
  77990. if (errorCallback)
  77991. errorCallback();
  77992. };
  77993. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  77994. // Your browser doesn't support IndexedDB
  77995. this.isSupported = false;
  77996. if (errorCallback)
  77997. errorCallback();
  77998. }
  77999. else {
  78000. // If the DB hasn't been opened or created yet
  78001. if (!this.db) {
  78002. this.hasReachedQuota = false;
  78003. this.isSupported = true;
  78004. var request = this.idbFactory.open("babylonjs", 1);
  78005. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  78006. request.onerror = function (event) {
  78007. handleError();
  78008. };
  78009. // executes when a version change transaction cannot complete due to other active transactions
  78010. request.onblocked = function (event) {
  78011. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  78012. handleError();
  78013. };
  78014. // DB has been opened successfully
  78015. request.onsuccess = function (event) {
  78016. _this.db = request.result;
  78017. successCallback();
  78018. };
  78019. // Initialization of the DB. Creating Scenes & Textures stores
  78020. request.onupgradeneeded = function (event) {
  78021. _this.db = (event.target).result;
  78022. if (_this.db) {
  78023. try {
  78024. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  78025. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  78026. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  78027. }
  78028. catch (ex) {
  78029. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  78030. handleError();
  78031. }
  78032. }
  78033. };
  78034. }
  78035. // DB has already been created and opened
  78036. else {
  78037. if (successCallback)
  78038. successCallback();
  78039. }
  78040. }
  78041. };
  78042. /**
  78043. * Loads an image from the database
  78044. * @param url defines the url to load from
  78045. * @param image defines the target DOM image
  78046. */
  78047. Database.prototype.loadImageFromDB = function (url, image) {
  78048. var _this = this;
  78049. var completeURL = Database._ReturnFullUrlLocation(url);
  78050. var saveAndLoadImage = function () {
  78051. if (!_this.hasReachedQuota && _this.db !== null) {
  78052. // the texture is not yet in the DB, let's try to save it
  78053. _this._saveImageIntoDBAsync(completeURL, image);
  78054. }
  78055. // If the texture is not in the DB and we've reached the DB quota limit
  78056. // let's load it directly from the web
  78057. else {
  78058. image.src = url;
  78059. }
  78060. };
  78061. if (!this.mustUpdateRessources) {
  78062. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  78063. }
  78064. // First time we're download the images or update requested in the manifest file by a version change
  78065. else {
  78066. saveAndLoadImage();
  78067. }
  78068. };
  78069. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  78070. if (this.isSupported && this.db !== null) {
  78071. var texture;
  78072. var transaction = this.db.transaction(["textures"]);
  78073. transaction.onabort = function (event) {
  78074. image.src = url;
  78075. };
  78076. transaction.oncomplete = function (event) {
  78077. var blobTextureURL;
  78078. if (texture) {
  78079. var URL = window.URL || window.webkitURL;
  78080. blobTextureURL = URL.createObjectURL(texture.data);
  78081. image.onerror = function () {
  78082. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  78083. image.src = url;
  78084. };
  78085. image.src = blobTextureURL;
  78086. }
  78087. else {
  78088. notInDBCallback();
  78089. }
  78090. };
  78091. var getRequest = transaction.objectStore("textures").get(url);
  78092. getRequest.onsuccess = function (event) {
  78093. texture = (event.target).result;
  78094. };
  78095. getRequest.onerror = function (event) {
  78096. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  78097. image.src = url;
  78098. };
  78099. }
  78100. else {
  78101. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78102. image.src = url;
  78103. }
  78104. };
  78105. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  78106. var _this = this;
  78107. if (this.isSupported) {
  78108. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  78109. var generateBlobUrl = function () {
  78110. var blobTextureURL;
  78111. if (blob) {
  78112. var URL = window.URL || window.webkitURL;
  78113. try {
  78114. blobTextureURL = URL.createObjectURL(blob);
  78115. }
  78116. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  78117. catch (ex) {
  78118. blobTextureURL = URL.createObjectURL(blob);
  78119. }
  78120. }
  78121. if (blobTextureURL) {
  78122. image.src = blobTextureURL;
  78123. }
  78124. };
  78125. if (Database.IsUASupportingBlobStorage) { // Create XHR
  78126. var xhr = new XMLHttpRequest(), blob;
  78127. xhr.open("GET", url, true);
  78128. xhr.responseType = "blob";
  78129. xhr.addEventListener("load", function () {
  78130. if (xhr.status === 200 && _this.db) {
  78131. // Blob as response (XHR2)
  78132. blob = xhr.response;
  78133. var transaction = _this.db.transaction(["textures"], "readwrite");
  78134. // the transaction could abort because of a QuotaExceededError error
  78135. transaction.onabort = function (event) {
  78136. try {
  78137. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78138. var srcElement = (event.srcElement || event.target);
  78139. var error = srcElement.error;
  78140. if (error && error.name === "QuotaExceededError") {
  78141. _this.hasReachedQuota = true;
  78142. }
  78143. }
  78144. catch (ex) { }
  78145. generateBlobUrl();
  78146. };
  78147. transaction.oncomplete = function (event) {
  78148. generateBlobUrl();
  78149. };
  78150. var newTexture = { textureUrl: url, data: blob };
  78151. try {
  78152. // Put the blob into the dabase
  78153. var addRequest = transaction.objectStore("textures").put(newTexture);
  78154. addRequest.onsuccess = function (event) {
  78155. };
  78156. addRequest.onerror = function (event) {
  78157. generateBlobUrl();
  78158. };
  78159. }
  78160. catch (ex) {
  78161. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  78162. if (ex.code === 25) {
  78163. Database.IsUASupportingBlobStorage = false;
  78164. }
  78165. image.src = url;
  78166. }
  78167. }
  78168. else {
  78169. image.src = url;
  78170. }
  78171. }, false);
  78172. xhr.addEventListener("error", function (event) {
  78173. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  78174. image.src = url;
  78175. }, false);
  78176. xhr.send();
  78177. }
  78178. else {
  78179. image.src = url;
  78180. }
  78181. }
  78182. else {
  78183. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78184. image.src = url;
  78185. }
  78186. };
  78187. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  78188. var _this = this;
  78189. var updateVersion = function () {
  78190. // the version is not yet in the DB or we need to update it
  78191. _this._saveVersionIntoDBAsync(url, versionLoaded);
  78192. };
  78193. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  78194. };
  78195. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  78196. var _this = this;
  78197. if (this.isSupported && this.db) {
  78198. var version;
  78199. try {
  78200. var transaction = this.db.transaction(["versions"]);
  78201. transaction.oncomplete = function (event) {
  78202. if (version) {
  78203. // If the version in the JSON file is different from the version in DB
  78204. if (_this.manifestVersionFound !== version.data) {
  78205. _this.mustUpdateRessources = true;
  78206. updateInDBCallback();
  78207. }
  78208. else {
  78209. callback(version.data);
  78210. }
  78211. }
  78212. // version was not found in DB
  78213. else {
  78214. _this.mustUpdateRessources = true;
  78215. updateInDBCallback();
  78216. }
  78217. };
  78218. transaction.onabort = function (event) {
  78219. callback(-1);
  78220. };
  78221. var getRequest = transaction.objectStore("versions").get(url);
  78222. getRequest.onsuccess = function (event) {
  78223. version = (event.target).result;
  78224. };
  78225. getRequest.onerror = function (event) {
  78226. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  78227. callback(-1);
  78228. };
  78229. }
  78230. catch (ex) {
  78231. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  78232. callback(-1);
  78233. }
  78234. }
  78235. else {
  78236. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78237. callback(-1);
  78238. }
  78239. };
  78240. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  78241. var _this = this;
  78242. if (this.isSupported && !this.hasReachedQuota && this.db) {
  78243. try {
  78244. // Open a transaction to the database
  78245. var transaction = this.db.transaction(["versions"], "readwrite");
  78246. // the transaction could abort because of a QuotaExceededError error
  78247. transaction.onabort = function (event) {
  78248. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78249. var error = event.srcElement['error'];
  78250. if (error && error.name === "QuotaExceededError") {
  78251. _this.hasReachedQuota = true;
  78252. }
  78253. }
  78254. catch (ex) { }
  78255. callback(-1);
  78256. };
  78257. transaction.oncomplete = function (event) {
  78258. callback(_this.manifestVersionFound);
  78259. };
  78260. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  78261. // Put the scene into the database
  78262. var addRequest = transaction.objectStore("versions").put(newVersion);
  78263. addRequest.onsuccess = function (event) {
  78264. };
  78265. addRequest.onerror = function (event) {
  78266. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  78267. };
  78268. }
  78269. catch (ex) {
  78270. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  78271. callback(-1);
  78272. }
  78273. }
  78274. else {
  78275. callback(-1);
  78276. }
  78277. };
  78278. /**
  78279. * Loads a file from database
  78280. * @param url defines the URL to load from
  78281. * @param sceneLoaded defines a callback to call on success
  78282. * @param progressCallBack defines a callback to call when progress changed
  78283. * @param errorCallback defines a callback to call on error
  78284. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  78285. */
  78286. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  78287. var _this = this;
  78288. var completeUrl = Database._ReturnFullUrlLocation(url);
  78289. var saveAndLoadFile = function () {
  78290. // the scene is not yet in the DB, let's try to save it
  78291. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78292. };
  78293. this._checkVersionFromDB(completeUrl, function (version) {
  78294. if (version !== -1) {
  78295. if (!_this.mustUpdateRessources) {
  78296. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  78297. }
  78298. else {
  78299. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer, errorCallback);
  78300. }
  78301. }
  78302. else {
  78303. if (errorCallback) {
  78304. errorCallback();
  78305. }
  78306. }
  78307. });
  78308. };
  78309. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  78310. if (this.isSupported && this.db) {
  78311. var targetStore;
  78312. if (url.indexOf(".babylon") !== -1) {
  78313. targetStore = "scenes";
  78314. }
  78315. else {
  78316. targetStore = "textures";
  78317. }
  78318. var file;
  78319. var transaction = this.db.transaction([targetStore]);
  78320. transaction.oncomplete = function (event) {
  78321. if (file) {
  78322. callback(file.data);
  78323. }
  78324. // file was not found in DB
  78325. else {
  78326. notInDBCallback();
  78327. }
  78328. };
  78329. transaction.onabort = function (event) {
  78330. notInDBCallback();
  78331. };
  78332. var getRequest = transaction.objectStore(targetStore).get(url);
  78333. getRequest.onsuccess = function (event) {
  78334. file = (event.target).result;
  78335. };
  78336. getRequest.onerror = function (event) {
  78337. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  78338. notInDBCallback();
  78339. };
  78340. }
  78341. else {
  78342. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78343. callback();
  78344. }
  78345. };
  78346. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer, errorCallback) {
  78347. var _this = this;
  78348. if (this.isSupported) {
  78349. var targetStore;
  78350. if (url.indexOf(".babylon") !== -1) {
  78351. targetStore = "scenes";
  78352. }
  78353. else {
  78354. targetStore = "textures";
  78355. }
  78356. // Create XHR
  78357. var xhr = new XMLHttpRequest();
  78358. var fileData;
  78359. xhr.open("GET", url + "?" + Date.now(), true);
  78360. if (useArrayBuffer) {
  78361. xhr.responseType = "arraybuffer";
  78362. }
  78363. if (progressCallback) {
  78364. xhr.onprogress = progressCallback;
  78365. }
  78366. xhr.addEventListener("load", function () {
  78367. if (xhr.status === 200 || (xhr.status < 400 && BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6))) {
  78368. // Blob as response (XHR2)
  78369. //fileData = xhr.responseText;
  78370. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  78371. if (!_this.hasReachedQuota && _this.db) {
  78372. // Open a transaction to the database
  78373. var transaction = _this.db.transaction([targetStore], "readwrite");
  78374. // the transaction could abort because of a QuotaExceededError error
  78375. transaction.onabort = function (event) {
  78376. try {
  78377. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  78378. var error = event.srcElement['error'];
  78379. if (error && error.name === "QuotaExceededError") {
  78380. _this.hasReachedQuota = true;
  78381. }
  78382. }
  78383. catch (ex) { }
  78384. callback(fileData);
  78385. };
  78386. transaction.oncomplete = function (event) {
  78387. callback(fileData);
  78388. };
  78389. var newFile;
  78390. if (targetStore === "scenes") {
  78391. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  78392. }
  78393. else {
  78394. newFile = { textureUrl: url, data: fileData };
  78395. }
  78396. try {
  78397. // Put the scene into the database
  78398. var addRequest = transaction.objectStore(targetStore).put(newFile);
  78399. addRequest.onsuccess = function (event) {
  78400. };
  78401. addRequest.onerror = function (event) {
  78402. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  78403. };
  78404. }
  78405. catch (ex) {
  78406. callback(fileData);
  78407. }
  78408. }
  78409. else {
  78410. callback(fileData);
  78411. }
  78412. }
  78413. else {
  78414. if (xhr.status >= 400 && errorCallback) {
  78415. errorCallback(xhr);
  78416. }
  78417. else {
  78418. callback();
  78419. }
  78420. }
  78421. }, false);
  78422. xhr.addEventListener("error", function (event) {
  78423. BABYLON.Tools.Error("error on XHR request.");
  78424. callback();
  78425. }, false);
  78426. xhr.send();
  78427. }
  78428. else {
  78429. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  78430. callback();
  78431. }
  78432. };
  78433. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  78434. Database.IsUASupportingBlobStorage = true;
  78435. /** Gets a boolean indicating if Database storate is enabled */
  78436. Database.IDBStorageEnabled = true;
  78437. Database._ParseURL = function (url) {
  78438. var a = document.createElement('a');
  78439. a.href = url;
  78440. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  78441. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  78442. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  78443. return absLocation;
  78444. };
  78445. Database._ReturnFullUrlLocation = function (url) {
  78446. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  78447. return (Database._ParseURL(window.location.href) + url);
  78448. }
  78449. else {
  78450. return url;
  78451. }
  78452. };
  78453. return Database;
  78454. }());
  78455. BABYLON.Database = Database;
  78456. })(BABYLON || (BABYLON = {}));
  78457. //# sourceMappingURL=babylon.database.js.map
  78458. var BABYLON;
  78459. (function (BABYLON) {
  78460. /**
  78461. * This represents all the required information to add a fresnel effect on a material:
  78462. * @see http://doc.babylonjs.com/how_to/how_to_use_fresnelparameters
  78463. */
  78464. var FresnelParameters = /** @class */ (function () {
  78465. function FresnelParameters() {
  78466. this._isEnabled = true;
  78467. /**
  78468. * Define the color used on edges (grazing angle)
  78469. */
  78470. this.leftColor = BABYLON.Color3.White();
  78471. /**
  78472. * Define the color used on center
  78473. */
  78474. this.rightColor = BABYLON.Color3.Black();
  78475. /**
  78476. * Define bias applied to computed fresnel term
  78477. */
  78478. this.bias = 0;
  78479. /**
  78480. * Defined the power exponent applied to fresnel term
  78481. */
  78482. this.power = 1;
  78483. }
  78484. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  78485. /**
  78486. * Define if the fresnel effect is enable or not.
  78487. */
  78488. get: function () {
  78489. return this._isEnabled;
  78490. },
  78491. set: function (value) {
  78492. if (this._isEnabled === value) {
  78493. return;
  78494. }
  78495. this._isEnabled = value;
  78496. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  78497. },
  78498. enumerable: true,
  78499. configurable: true
  78500. });
  78501. /**
  78502. * Clones the current fresnel and its valuues
  78503. * @returns a clone fresnel configuration
  78504. */
  78505. FresnelParameters.prototype.clone = function () {
  78506. var newFresnelParameters = new FresnelParameters();
  78507. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  78508. return newFresnelParameters;
  78509. };
  78510. /**
  78511. * Serializes the current fresnel parameters to a JSON representation.
  78512. * @return the JSON serialization
  78513. */
  78514. FresnelParameters.prototype.serialize = function () {
  78515. var serializationObject = {};
  78516. serializationObject.isEnabled = this.isEnabled;
  78517. serializationObject.leftColor = this.leftColor.asArray();
  78518. serializationObject.rightColor = this.rightColor.asArray();
  78519. serializationObject.bias = this.bias;
  78520. serializationObject.power = this.power;
  78521. return serializationObject;
  78522. };
  78523. /**
  78524. * Parse a JSON object and deserialize it to a new Fresnel parameter object.
  78525. * @param parsedFresnelParameters Define the JSON representation
  78526. * @returns the parsed parameters
  78527. */
  78528. FresnelParameters.Parse = function (parsedFresnelParameters) {
  78529. var fresnelParameters = new FresnelParameters();
  78530. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  78531. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  78532. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  78533. fresnelParameters.bias = parsedFresnelParameters.bias;
  78534. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  78535. return fresnelParameters;
  78536. };
  78537. return FresnelParameters;
  78538. }());
  78539. BABYLON.FresnelParameters = FresnelParameters;
  78540. })(BABYLON || (BABYLON = {}));
  78541. //# sourceMappingURL=babylon.fresnelParameters.js.map
  78542. var BABYLON;
  78543. (function (BABYLON) {
  78544. /**
  78545. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78546. * separate meshes. This can be use to improve performances.
  78547. * @see http://doc.babylonjs.com/how_to/multi_materials
  78548. */
  78549. var MultiMaterial = /** @class */ (function (_super) {
  78550. __extends(MultiMaterial, _super);
  78551. /**
  78552. * Instantiates a new Multi Material
  78553. * A multi-material is used to apply different materials to different parts of the same object without the need of
  78554. * separate meshes. This can be use to improve performances.
  78555. * @see http://doc.babylonjs.com/how_to/multi_materials
  78556. * @param name Define the name in the scene
  78557. * @param scene Define the scene the material belongs to
  78558. */
  78559. function MultiMaterial(name, scene) {
  78560. var _this = _super.call(this, name, scene, true) || this;
  78561. scene.multiMaterials.push(_this);
  78562. _this.subMaterials = new Array();
  78563. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  78564. return _this;
  78565. }
  78566. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  78567. /**
  78568. * Gets or Sets the list of Materials used within the multi material.
  78569. * They need to be ordered according to the submeshes order in the associated mesh
  78570. */
  78571. get: function () {
  78572. return this._subMaterials;
  78573. },
  78574. set: function (value) {
  78575. this._subMaterials = value;
  78576. this._hookArray(value);
  78577. },
  78578. enumerable: true,
  78579. configurable: true
  78580. });
  78581. MultiMaterial.prototype._hookArray = function (array) {
  78582. var _this = this;
  78583. var oldPush = array.push;
  78584. array.push = function () {
  78585. var items = [];
  78586. for (var _i = 0; _i < arguments.length; _i++) {
  78587. items[_i] = arguments[_i];
  78588. }
  78589. var result = oldPush.apply(array, items);
  78590. _this._markAllSubMeshesAsTexturesDirty();
  78591. return result;
  78592. };
  78593. var oldSplice = array.splice;
  78594. array.splice = function (index, deleteCount) {
  78595. var deleted = oldSplice.apply(array, [index, deleteCount]);
  78596. _this._markAllSubMeshesAsTexturesDirty();
  78597. return deleted;
  78598. };
  78599. };
  78600. /**
  78601. * Get one of the submaterial by its index in the submaterials array
  78602. * @param index The index to look the sub material at
  78603. * @returns The Material if the index has been defined
  78604. */
  78605. MultiMaterial.prototype.getSubMaterial = function (index) {
  78606. if (index < 0 || index >= this.subMaterials.length) {
  78607. return this.getScene().defaultMaterial;
  78608. }
  78609. return this.subMaterials[index];
  78610. };
  78611. /**
  78612. * Get the list of active textures for the whole sub materials list.
  78613. * @returns All the textures that will be used during the rendering
  78614. */
  78615. MultiMaterial.prototype.getActiveTextures = function () {
  78616. var _a;
  78617. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  78618. if (subMaterial) {
  78619. return subMaterial.getActiveTextures();
  78620. }
  78621. else {
  78622. return [];
  78623. }
  78624. }));
  78625. };
  78626. /**
  78627. * Gets the current class name of the material e.g. "MultiMaterial"
  78628. * Mainly use in serialization.
  78629. * @returns the class name
  78630. */
  78631. MultiMaterial.prototype.getClassName = function () {
  78632. return "MultiMaterial";
  78633. };
  78634. /**
  78635. * Checks if the material is ready to render the requested sub mesh
  78636. * @param mesh Define the mesh the submesh belongs to
  78637. * @param subMesh Define the sub mesh to look readyness for
  78638. * @param useInstances Define whether or not the material is used with instances
  78639. * @returns true if ready, otherwise false
  78640. */
  78641. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  78642. for (var index = 0; index < this.subMaterials.length; index++) {
  78643. var subMaterial = this.subMaterials[index];
  78644. if (subMaterial) {
  78645. if (subMaterial.storeEffectOnSubMeshes) {
  78646. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  78647. return false;
  78648. }
  78649. continue;
  78650. }
  78651. if (!subMaterial.isReady(mesh)) {
  78652. return false;
  78653. }
  78654. }
  78655. }
  78656. return true;
  78657. };
  78658. /**
  78659. * Clones the current material and its related sub materials
  78660. * @param name Define the name of the newly cloned material
  78661. * @param cloneChildren Define if submaterial will be cloned or shared with the parent instance
  78662. * @returns the cloned material
  78663. */
  78664. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  78665. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  78666. for (var index = 0; index < this.subMaterials.length; index++) {
  78667. var subMaterial = null;
  78668. var current = this.subMaterials[index];
  78669. if (cloneChildren && current) {
  78670. subMaterial = current.clone(name + "-" + current.name);
  78671. }
  78672. else {
  78673. subMaterial = this.subMaterials[index];
  78674. }
  78675. newMultiMaterial.subMaterials.push(subMaterial);
  78676. }
  78677. return newMultiMaterial;
  78678. };
  78679. /**
  78680. * Serializes the materials into a JSON representation.
  78681. * @returns the JSON representation
  78682. */
  78683. MultiMaterial.prototype.serialize = function () {
  78684. var serializationObject = {};
  78685. serializationObject.name = this.name;
  78686. serializationObject.id = this.id;
  78687. if (BABYLON.Tags) {
  78688. serializationObject.tags = BABYLON.Tags.GetTags(this);
  78689. }
  78690. serializationObject.materials = [];
  78691. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  78692. var subMat = this.subMaterials[matIndex];
  78693. if (subMat) {
  78694. serializationObject.materials.push(subMat.id);
  78695. }
  78696. else {
  78697. serializationObject.materials.push(null);
  78698. }
  78699. }
  78700. return serializationObject;
  78701. };
  78702. /**
  78703. * Dispose the material and release its associated resources
  78704. * @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)
  78705. * @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)
  78706. */
  78707. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  78708. var scene = this.getScene();
  78709. if (!scene) {
  78710. return;
  78711. }
  78712. var index = scene.multiMaterials.indexOf(this);
  78713. if (index >= 0) {
  78714. scene.multiMaterials.splice(index, 1);
  78715. }
  78716. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  78717. };
  78718. return MultiMaterial;
  78719. }(BABYLON.Material));
  78720. BABYLON.MultiMaterial = MultiMaterial;
  78721. })(BABYLON || (BABYLON = {}));
  78722. //# sourceMappingURL=babylon.multiMaterial.js.map
  78723. var BABYLON;
  78724. (function (BABYLON) {
  78725. /**
  78726. * Manage the touch inputs to control the movement of a free camera.
  78727. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  78728. */
  78729. var FreeCameraTouchInput = /** @class */ (function () {
  78730. function FreeCameraTouchInput() {
  78731. /**
  78732. * Defines the touch sensibility for rotation.
  78733. * The higher the faster.
  78734. */
  78735. this.touchAngularSensibility = 200000.0;
  78736. /**
  78737. * Defines the touch sensibility for move.
  78738. * The higher the faster.
  78739. */
  78740. this.touchMoveSensibility = 250.0;
  78741. this._offsetX = null;
  78742. this._offsetY = null;
  78743. this._pointerPressed = new Array();
  78744. }
  78745. /**
  78746. * Attach the input controls to a specific dom element to get the input from.
  78747. * @param element Defines the element the controls should be listened from
  78748. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  78749. */
  78750. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  78751. var _this = this;
  78752. var previousPosition = null;
  78753. if (this._pointerInput === undefined) {
  78754. this._onLostFocus = function (evt) {
  78755. _this._offsetX = null;
  78756. _this._offsetY = null;
  78757. };
  78758. this._pointerInput = function (p, s) {
  78759. var evt = p.event;
  78760. if (evt.pointerType === "mouse") {
  78761. return;
  78762. }
  78763. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  78764. if (!noPreventDefault) {
  78765. evt.preventDefault();
  78766. }
  78767. _this._pointerPressed.push(evt.pointerId);
  78768. if (_this._pointerPressed.length !== 1) {
  78769. return;
  78770. }
  78771. previousPosition = {
  78772. x: evt.clientX,
  78773. y: evt.clientY
  78774. };
  78775. }
  78776. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  78777. if (!noPreventDefault) {
  78778. evt.preventDefault();
  78779. }
  78780. var index = _this._pointerPressed.indexOf(evt.pointerId);
  78781. if (index === -1) {
  78782. return;
  78783. }
  78784. _this._pointerPressed.splice(index, 1);
  78785. if (index != 0) {
  78786. return;
  78787. }
  78788. previousPosition = null;
  78789. _this._offsetX = null;
  78790. _this._offsetY = null;
  78791. }
  78792. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  78793. if (!noPreventDefault) {
  78794. evt.preventDefault();
  78795. }
  78796. if (!previousPosition) {
  78797. return;
  78798. }
  78799. var index = _this._pointerPressed.indexOf(evt.pointerId);
  78800. if (index != 0) {
  78801. return;
  78802. }
  78803. _this._offsetX = evt.clientX - previousPosition.x;
  78804. _this._offsetY = -(evt.clientY - previousPosition.y);
  78805. }
  78806. };
  78807. }
  78808. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  78809. if (this._onLostFocus) {
  78810. element.addEventListener("blur", this._onLostFocus);
  78811. }
  78812. };
  78813. /**
  78814. * Detach the current controls from the specified dom element.
  78815. * @param element Defines the element to stop listening the inputs from
  78816. */
  78817. FreeCameraTouchInput.prototype.detachControl = function (element) {
  78818. if (this._pointerInput && element) {
  78819. if (this._observer) {
  78820. this.camera.getScene().onPointerObservable.remove(this._observer);
  78821. this._observer = null;
  78822. }
  78823. if (this._onLostFocus) {
  78824. element.removeEventListener("blur", this._onLostFocus);
  78825. this._onLostFocus = null;
  78826. }
  78827. this._pointerPressed = [];
  78828. this._offsetX = null;
  78829. this._offsetY = null;
  78830. }
  78831. };
  78832. /**
  78833. * Update the current camera state depending on the inputs that have been used this frame.
  78834. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  78835. */
  78836. FreeCameraTouchInput.prototype.checkInputs = function () {
  78837. if (this._offsetX && this._offsetY) {
  78838. var camera = this.camera;
  78839. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  78840. if (this._pointerPressed.length > 1) {
  78841. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  78842. }
  78843. else {
  78844. var speed = camera._computeLocalCameraSpeed();
  78845. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  78846. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  78847. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  78848. }
  78849. }
  78850. };
  78851. /**
  78852. * Gets the class name of the current intput.
  78853. * @returns the class name
  78854. */
  78855. FreeCameraTouchInput.prototype.getClassName = function () {
  78856. return "FreeCameraTouchInput";
  78857. };
  78858. /**
  78859. * Get the friendly name associated with the input class.
  78860. * @returns the input friendly name
  78861. */
  78862. FreeCameraTouchInput.prototype.getSimpleName = function () {
  78863. return "touch";
  78864. };
  78865. __decorate([
  78866. BABYLON.serialize()
  78867. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  78868. __decorate([
  78869. BABYLON.serialize()
  78870. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  78871. return FreeCameraTouchInput;
  78872. }());
  78873. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  78874. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  78875. })(BABYLON || (BABYLON = {}));
  78876. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  78877. var BABYLON;
  78878. (function (BABYLON) {
  78879. BABYLON.Node.AddNodeConstructor("TouchCamera", function (name, scene) {
  78880. return function () { return new TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  78881. });
  78882. /**
  78883. * This represents a FPS type of camera controlled by touch.
  78884. * This is like a universal camera minus the Gamepad controls.
  78885. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78886. */
  78887. var TouchCamera = /** @class */ (function (_super) {
  78888. __extends(TouchCamera, _super);
  78889. /**
  78890. * Instantiates a new touch camera.
  78891. * This represents a FPS type of camera controlled by touch.
  78892. * This is like a universal camera minus the Gamepad controls.
  78893. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  78894. * @param name Define the name of the camera in the scene
  78895. * @param position Define the start position of the camera in the scene
  78896. * @param scene Define the scene the camera belongs to
  78897. */
  78898. function TouchCamera(name, position, scene) {
  78899. var _this = _super.call(this, name, position, scene) || this;
  78900. _this.inputs.addTouch();
  78901. _this._setupInputs();
  78902. return _this;
  78903. }
  78904. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  78905. /**
  78906. * Defines the touch sensibility for rotation.
  78907. * The higher the faster.
  78908. */
  78909. get: function () {
  78910. var touch = this.inputs.attached["touch"];
  78911. if (touch)
  78912. return touch.touchAngularSensibility;
  78913. return 0;
  78914. },
  78915. set: function (value) {
  78916. var touch = this.inputs.attached["touch"];
  78917. if (touch)
  78918. touch.touchAngularSensibility = value;
  78919. },
  78920. enumerable: true,
  78921. configurable: true
  78922. });
  78923. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  78924. /**
  78925. * Defines the touch sensibility for move.
  78926. * The higher the faster.
  78927. */
  78928. get: function () {
  78929. var touch = this.inputs.attached["touch"];
  78930. if (touch)
  78931. return touch.touchMoveSensibility;
  78932. return 0;
  78933. },
  78934. set: function (value) {
  78935. var touch = this.inputs.attached["touch"];
  78936. if (touch)
  78937. touch.touchMoveSensibility = value;
  78938. },
  78939. enumerable: true,
  78940. configurable: true
  78941. });
  78942. /**
  78943. * Gets the current object class name.
  78944. * @return the class name
  78945. */
  78946. TouchCamera.prototype.getClassName = function () {
  78947. return "TouchCamera";
  78948. };
  78949. /** @hidden */
  78950. TouchCamera.prototype._setupInputs = function () {
  78951. var mouse = this.inputs.attached["mouse"];
  78952. if (mouse) {
  78953. mouse.touchEnabled = false;
  78954. }
  78955. };
  78956. return TouchCamera;
  78957. }(BABYLON.FreeCamera));
  78958. BABYLON.TouchCamera = TouchCamera;
  78959. })(BABYLON || (BABYLON = {}));
  78960. //# sourceMappingURL=babylon.touchCamera.js.map
  78961. var BABYLON;
  78962. (function (BABYLON) {
  78963. /**
  78964. * 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.
  78965. * This is the base class of any Procedural texture and contains most of the shareable code.
  78966. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78967. */
  78968. var ProceduralTexture = /** @class */ (function (_super) {
  78969. __extends(ProceduralTexture, _super);
  78970. /**
  78971. * Instantiates a new procedural texture.
  78972. * 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.
  78973. * This is the base class of any Procedural texture and contains most of the shareable code.
  78974. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  78975. * @param name Define the name of the texture
  78976. * @param size Define the size of the texture to create
  78977. * @param fragment Define the fragment shader to use to generate the texture or null if it is defined later
  78978. * @param scene Define the scene the texture belongs to
  78979. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  78980. * @param generateMipMaps Define if the texture should creates mip maps or not
  78981. * @param isCube Define if the texture is a cube texture or not (this will render each faces of the cube)
  78982. */
  78983. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  78984. if (fallbackTexture === void 0) { fallbackTexture = null; }
  78985. if (generateMipMaps === void 0) { generateMipMaps = true; }
  78986. if (isCube === void 0) { isCube = false; }
  78987. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  78988. _this.isCube = isCube;
  78989. /**
  78990. * Define if the texture is enabled or not (disabled texture will not render)
  78991. */
  78992. _this.isEnabled = true;
  78993. /**
  78994. * Event raised when the texture is generated
  78995. */
  78996. _this.onGeneratedObservable = new BABYLON.Observable();
  78997. /** @hidden */
  78998. _this._textures = {};
  78999. _this._currentRefreshId = -1;
  79000. _this._refreshRate = 1;
  79001. _this._vertexBuffers = {};
  79002. _this._uniforms = new Array();
  79003. _this._samplers = new Array();
  79004. _this._floats = {};
  79005. _this._ints = {};
  79006. _this._floatsArrays = {};
  79007. _this._colors3 = {};
  79008. _this._colors4 = {};
  79009. _this._vectors2 = {};
  79010. _this._vectors3 = {};
  79011. _this._matrices = {};
  79012. _this._fallbackTextureUsed = false;
  79013. _this._cachedDefines = "";
  79014. _this._contentUpdateId = -1;
  79015. scene = _this.getScene();
  79016. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE);
  79017. if (!component) {
  79018. component = new BABYLON.ProceduralTextureSceneComponent(scene);
  79019. scene._addComponent(component);
  79020. }
  79021. scene.proceduralTextures.push(_this);
  79022. _this._engine = scene.getEngine();
  79023. _this.name = name;
  79024. _this.isRenderTarget = true;
  79025. _this._size = size;
  79026. _this._generateMipMaps = generateMipMaps;
  79027. _this.setFragment(fragment);
  79028. _this._fallbackTexture = fallbackTexture;
  79029. if (isCube) {
  79030. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  79031. _this.setFloat("face", 0);
  79032. }
  79033. else {
  79034. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  79035. }
  79036. // VBO
  79037. var vertices = [];
  79038. vertices.push(1, 1);
  79039. vertices.push(-1, 1);
  79040. vertices.push(-1, -1);
  79041. vertices.push(1, -1);
  79042. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  79043. _this._createIndexBuffer();
  79044. return _this;
  79045. }
  79046. /**
  79047. * Gets texture content (Use this function wisely as reading from a texture can be slow)
  79048. * @returns an ArrayBufferView (Uint8Array or Float32Array)
  79049. */
  79050. ProceduralTexture.prototype.getContent = function () {
  79051. if (this._contentData && this._currentRefreshId == this._contentUpdateId) {
  79052. return this._contentData;
  79053. }
  79054. this._contentData = this.readPixels(0, 0, this._contentData);
  79055. this._contentUpdateId = this._currentRefreshId;
  79056. return this._contentData;
  79057. };
  79058. ProceduralTexture.prototype._createIndexBuffer = function () {
  79059. var engine = this._engine;
  79060. // Indices
  79061. var indices = [];
  79062. indices.push(0);
  79063. indices.push(1);
  79064. indices.push(2);
  79065. indices.push(0);
  79066. indices.push(2);
  79067. indices.push(3);
  79068. this._indexBuffer = engine.createIndexBuffer(indices);
  79069. };
  79070. /** @hidden */
  79071. ProceduralTexture.prototype._rebuild = function () {
  79072. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79073. if (vb) {
  79074. vb._rebuild();
  79075. }
  79076. this._createIndexBuffer();
  79077. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  79078. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  79079. }
  79080. };
  79081. /**
  79082. * Resets the texture in order to recreate its associated resources.
  79083. * This can be called in case of context loss
  79084. */
  79085. ProceduralTexture.prototype.reset = function () {
  79086. if (this._effect === undefined) {
  79087. return;
  79088. }
  79089. var engine = this._engine;
  79090. engine._releaseEffect(this._effect);
  79091. };
  79092. ProceduralTexture.prototype._getDefines = function () {
  79093. return "";
  79094. };
  79095. /**
  79096. * Is the texture ready to be used ? (rendered at least once)
  79097. * @returns true if ready, otherwise, false.
  79098. */
  79099. ProceduralTexture.prototype.isReady = function () {
  79100. var _this = this;
  79101. var engine = this._engine;
  79102. var shaders;
  79103. if (!this._fragment) {
  79104. return false;
  79105. }
  79106. if (this._fallbackTextureUsed) {
  79107. return true;
  79108. }
  79109. var defines = this._getDefines();
  79110. if (this._effect && defines === this._cachedDefines && this._effect.isReady()) {
  79111. return true;
  79112. }
  79113. if (this._fragment.fragmentElement !== undefined) {
  79114. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  79115. }
  79116. else {
  79117. shaders = { vertex: "procedural", fragment: this._fragment };
  79118. }
  79119. this._cachedDefines = defines;
  79120. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, defines, undefined, undefined, function () {
  79121. _this.releaseInternalTexture();
  79122. if (_this._fallbackTexture) {
  79123. _this._texture = _this._fallbackTexture._texture;
  79124. if (_this._texture) {
  79125. _this._texture.incrementReferences();
  79126. }
  79127. }
  79128. _this._fallbackTextureUsed = true;
  79129. });
  79130. return this._effect.isReady();
  79131. };
  79132. /**
  79133. * Resets the refresh counter of the texture and start bak from scratch.
  79134. * Could be usefull to regenerate the texture if it is setup to render only once.
  79135. */
  79136. ProceduralTexture.prototype.resetRefreshCounter = function () {
  79137. this._currentRefreshId = -1;
  79138. };
  79139. /**
  79140. * Set the fragment shader to use in order to render the texture.
  79141. * @param fragment This can be set to a path (into the shader store) or to a json object containing a fragmentElement property.
  79142. */
  79143. ProceduralTexture.prototype.setFragment = function (fragment) {
  79144. this._fragment = fragment;
  79145. };
  79146. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  79147. /**
  79148. * Define the refresh rate of the texture or the rendering frequency.
  79149. * Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  79150. */
  79151. get: function () {
  79152. return this._refreshRate;
  79153. },
  79154. set: function (value) {
  79155. this._refreshRate = value;
  79156. this.resetRefreshCounter();
  79157. },
  79158. enumerable: true,
  79159. configurable: true
  79160. });
  79161. /** @hidden */
  79162. ProceduralTexture.prototype._shouldRender = function () {
  79163. if (!this.isEnabled || !this.isReady() || !this._texture) {
  79164. if (this._texture) {
  79165. this._texture.isReady = false;
  79166. }
  79167. return false;
  79168. }
  79169. if (this._fallbackTextureUsed) {
  79170. return false;
  79171. }
  79172. if (this._currentRefreshId === -1) { // At least render once
  79173. this._currentRefreshId = 1;
  79174. return true;
  79175. }
  79176. if (this.refreshRate === this._currentRefreshId) {
  79177. this._currentRefreshId = 1;
  79178. return true;
  79179. }
  79180. this._currentRefreshId++;
  79181. return false;
  79182. };
  79183. /**
  79184. * Get the size the texture is rendering at.
  79185. * @returns the size (texture is always squared)
  79186. */
  79187. ProceduralTexture.prototype.getRenderSize = function () {
  79188. return this._size;
  79189. };
  79190. /**
  79191. * Resize the texture to new value.
  79192. * @param size Define the new size the texture should have
  79193. * @param generateMipMaps Define whether the new texture should create mip maps
  79194. */
  79195. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  79196. if (this._fallbackTextureUsed) {
  79197. return;
  79198. }
  79199. this.releaseInternalTexture();
  79200. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  79201. // Update properties
  79202. this._size = size;
  79203. this._generateMipMaps = generateMipMaps;
  79204. };
  79205. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  79206. if (this._uniforms.indexOf(uniformName) === -1) {
  79207. this._uniforms.push(uniformName);
  79208. }
  79209. };
  79210. /**
  79211. * Set a texture in the shader program used to render.
  79212. * @param name Define the name of the uniform samplers as defined in the shader
  79213. * @param texture Define the texture to bind to this sampler
  79214. * @return the texture itself allowing "fluent" like uniform updates
  79215. */
  79216. ProceduralTexture.prototype.setTexture = function (name, texture) {
  79217. if (this._samplers.indexOf(name) === -1) {
  79218. this._samplers.push(name);
  79219. }
  79220. this._textures[name] = texture;
  79221. return this;
  79222. };
  79223. /**
  79224. * Set a float in the shader.
  79225. * @param name Define the name of the uniform as defined in the shader
  79226. * @param value Define the value to give to the uniform
  79227. * @return the texture itself allowing "fluent" like uniform updates
  79228. */
  79229. ProceduralTexture.prototype.setFloat = function (name, value) {
  79230. this._checkUniform(name);
  79231. this._floats[name] = value;
  79232. return this;
  79233. };
  79234. /**
  79235. * Set a int in the shader.
  79236. * @param name Define the name of the uniform as defined in the shader
  79237. * @param value Define the value to give to the uniform
  79238. * @return the texture itself allowing "fluent" like uniform updates
  79239. */
  79240. ProceduralTexture.prototype.setInt = function (name, value) {
  79241. this._checkUniform(name);
  79242. this._ints[name] = value;
  79243. return this;
  79244. };
  79245. /**
  79246. * Set an array of floats in the shader.
  79247. * @param name Define the name of the uniform as defined in the shader
  79248. * @param value Define the value to give to the uniform
  79249. * @return the texture itself allowing "fluent" like uniform updates
  79250. */
  79251. ProceduralTexture.prototype.setFloats = function (name, value) {
  79252. this._checkUniform(name);
  79253. this._floatsArrays[name] = value;
  79254. return this;
  79255. };
  79256. /**
  79257. * Set a vec3 in the shader from a Color3.
  79258. * @param name Define the name of the uniform as defined in the shader
  79259. * @param value Define the value to give to the uniform
  79260. * @return the texture itself allowing "fluent" like uniform updates
  79261. */
  79262. ProceduralTexture.prototype.setColor3 = function (name, value) {
  79263. this._checkUniform(name);
  79264. this._colors3[name] = value;
  79265. return this;
  79266. };
  79267. /**
  79268. * Set a vec4 in the shader from a Color4.
  79269. * @param name Define the name of the uniform as defined in the shader
  79270. * @param value Define the value to give to the uniform
  79271. * @return the texture itself allowing "fluent" like uniform updates
  79272. */
  79273. ProceduralTexture.prototype.setColor4 = function (name, value) {
  79274. this._checkUniform(name);
  79275. this._colors4[name] = value;
  79276. return this;
  79277. };
  79278. /**
  79279. * Set a vec2 in the shader from a Vector2.
  79280. * @param name Define the name of the uniform as defined in the shader
  79281. * @param value Define the value to give to the uniform
  79282. * @return the texture itself allowing "fluent" like uniform updates
  79283. */
  79284. ProceduralTexture.prototype.setVector2 = function (name, value) {
  79285. this._checkUniform(name);
  79286. this._vectors2[name] = value;
  79287. return this;
  79288. };
  79289. /**
  79290. * Set a vec3 in the shader from a Vector3.
  79291. * @param name Define the name of the uniform as defined in the shader
  79292. * @param value Define the value to give to the uniform
  79293. * @return the texture itself allowing "fluent" like uniform updates
  79294. */
  79295. ProceduralTexture.prototype.setVector3 = function (name, value) {
  79296. this._checkUniform(name);
  79297. this._vectors3[name] = value;
  79298. return this;
  79299. };
  79300. /**
  79301. * Set a mat4 in the shader from a MAtrix.
  79302. * @param name Define the name of the uniform as defined in the shader
  79303. * @param value Define the value to give to the uniform
  79304. * @return the texture itself allowing "fluent" like uniform updates
  79305. */
  79306. ProceduralTexture.prototype.setMatrix = function (name, value) {
  79307. this._checkUniform(name);
  79308. this._matrices[name] = value;
  79309. return this;
  79310. };
  79311. /**
  79312. * Render the texture to its associated render target.
  79313. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79314. */
  79315. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79316. var scene = this.getScene();
  79317. if (!scene) {
  79318. return;
  79319. }
  79320. var engine = this._engine;
  79321. // Render
  79322. engine.enableEffect(this._effect);
  79323. engine.setState(false);
  79324. // Texture
  79325. for (var name in this._textures) {
  79326. this._effect.setTexture(name, this._textures[name]);
  79327. }
  79328. // Float
  79329. for (name in this._ints) {
  79330. this._effect.setInt(name, this._ints[name]);
  79331. }
  79332. // Float
  79333. for (name in this._floats) {
  79334. this._effect.setFloat(name, this._floats[name]);
  79335. }
  79336. // Floats
  79337. for (name in this._floatsArrays) {
  79338. this._effect.setArray(name, this._floatsArrays[name]);
  79339. }
  79340. // Color3
  79341. for (name in this._colors3) {
  79342. this._effect.setColor3(name, this._colors3[name]);
  79343. }
  79344. // Color4
  79345. for (name in this._colors4) {
  79346. var color = this._colors4[name];
  79347. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  79348. }
  79349. // Vector2
  79350. for (name in this._vectors2) {
  79351. this._effect.setVector2(name, this._vectors2[name]);
  79352. }
  79353. // Vector3
  79354. for (name in this._vectors3) {
  79355. this._effect.setVector3(name, this._vectors3[name]);
  79356. }
  79357. // Matrix
  79358. for (name in this._matrices) {
  79359. this._effect.setMatrix(name, this._matrices[name]);
  79360. }
  79361. if (!this._texture) {
  79362. return;
  79363. }
  79364. if (this.isCube) {
  79365. for (var face = 0; face < 6; face++) {
  79366. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  79367. // VBOs
  79368. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79369. this._effect.setFloat("face", face);
  79370. // Clear
  79371. engine.clear(scene.clearColor, true, true, true);
  79372. // Draw order
  79373. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79374. // Mipmaps
  79375. if (face === 5) {
  79376. engine.generateMipMapsForCubemap(this._texture);
  79377. }
  79378. }
  79379. }
  79380. else {
  79381. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  79382. // VBOs
  79383. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  79384. // Clear
  79385. engine.clear(scene.clearColor, true, true, true);
  79386. // Draw order
  79387. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  79388. }
  79389. // Unbind
  79390. engine.unBindFramebuffer(this._texture, this.isCube);
  79391. if (this.onGenerated) {
  79392. this.onGenerated();
  79393. }
  79394. this.onGeneratedObservable.notifyObservers(this);
  79395. };
  79396. /**
  79397. * Clone the texture.
  79398. * @returns the cloned texture
  79399. */
  79400. ProceduralTexture.prototype.clone = function () {
  79401. var textureSize = this.getSize();
  79402. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  79403. // Base texture
  79404. newTexture.hasAlpha = this.hasAlpha;
  79405. newTexture.level = this.level;
  79406. // RenderTarget Texture
  79407. newTexture.coordinatesMode = this.coordinatesMode;
  79408. return newTexture;
  79409. };
  79410. /**
  79411. * Dispose the texture and release its asoociated resources.
  79412. */
  79413. ProceduralTexture.prototype.dispose = function () {
  79414. var scene = this.getScene();
  79415. if (!scene) {
  79416. return;
  79417. }
  79418. var index = scene.proceduralTextures.indexOf(this);
  79419. if (index >= 0) {
  79420. scene.proceduralTextures.splice(index, 1);
  79421. }
  79422. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  79423. if (vertexBuffer) {
  79424. vertexBuffer.dispose();
  79425. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  79426. }
  79427. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  79428. this._indexBuffer = null;
  79429. }
  79430. _super.prototype.dispose.call(this);
  79431. };
  79432. __decorate([
  79433. BABYLON.serialize()
  79434. ], ProceduralTexture.prototype, "isEnabled", void 0);
  79435. __decorate([
  79436. BABYLON.serialize()
  79437. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  79438. __decorate([
  79439. BABYLON.serialize()
  79440. ], ProceduralTexture.prototype, "_size", void 0);
  79441. __decorate([
  79442. BABYLON.serialize()
  79443. ], ProceduralTexture.prototype, "refreshRate", null);
  79444. return ProceduralTexture;
  79445. }(BABYLON.Texture));
  79446. BABYLON.ProceduralTexture = ProceduralTexture;
  79447. })(BABYLON || (BABYLON = {}));
  79448. //# sourceMappingURL=babylon.proceduralTexture.js.map
  79449. var BABYLON;
  79450. (function (BABYLON) {
  79451. /**
  79452. * Defines the Procedural Texture scene component responsible to manage any Procedural Texture
  79453. * in a given scene.
  79454. */
  79455. var ProceduralTextureSceneComponent = /** @class */ (function () {
  79456. /**
  79457. * Creates a new instance of the component for the given scene
  79458. * @param scene Defines the scene to register the component in
  79459. */
  79460. function ProceduralTextureSceneComponent(scene) {
  79461. /**
  79462. * The component name helpfull to identify the component in the list of scene components.
  79463. */
  79464. this.name = BABYLON.SceneComponentConstants.NAME_PROCEDURALTEXTURE;
  79465. this.scene = scene;
  79466. this.scene.proceduralTextures = new Array();
  79467. scene.layers = new Array();
  79468. }
  79469. /**
  79470. * Registers the component in a given scene
  79471. */
  79472. ProceduralTextureSceneComponent.prototype.register = function () {
  79473. this.scene._beforeClearStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECLEAR_PROCEDURALTEXTURE, this, this._beforeClear);
  79474. };
  79475. /**
  79476. * Rebuilds the elements related to this component in case of
  79477. * context lost for instance.
  79478. */
  79479. ProceduralTextureSceneComponent.prototype.rebuild = function () {
  79480. // Nothing to do here.
  79481. };
  79482. /**
  79483. * Disposes the component and the associated ressources.
  79484. */
  79485. ProceduralTextureSceneComponent.prototype.dispose = function () {
  79486. // Nothing to do here.
  79487. };
  79488. ProceduralTextureSceneComponent.prototype._beforeClear = function () {
  79489. if (this.scene.proceduralTexturesEnabled) {
  79490. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79491. for (var proceduralIndex = 0; proceduralIndex < this.scene.proceduralTextures.length; proceduralIndex++) {
  79492. var proceduralTexture = this.scene.proceduralTextures[proceduralIndex];
  79493. if (proceduralTexture._shouldRender()) {
  79494. proceduralTexture.render();
  79495. }
  79496. }
  79497. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.scene.proceduralTextures.length > 0);
  79498. }
  79499. };
  79500. return ProceduralTextureSceneComponent;
  79501. }());
  79502. BABYLON.ProceduralTextureSceneComponent = ProceduralTextureSceneComponent;
  79503. })(BABYLON || (BABYLON = {}));
  79504. //# sourceMappingURL=babylon.proceduralTextureSceneComponent.js.map
  79505. var BABYLON;
  79506. (function (BABYLON) {
  79507. /**
  79508. * 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.
  79509. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79510. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79511. */
  79512. var CustomProceduralTexture = /** @class */ (function (_super) {
  79513. __extends(CustomProceduralTexture, _super);
  79514. /**
  79515. * Instantiates a new Custom Procedural Texture.
  79516. * 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.
  79517. * Custom Procedural textures are the easiest way to create your own procedural in your application.
  79518. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures#creating-custom-procedural-textures
  79519. * @param name Define the name of the texture
  79520. * @param texturePath Define the folder path containing all the cutom texture related files (config, shaders...)
  79521. * @param size Define the size of the texture to create
  79522. * @param scene Define the scene the texture belongs to
  79523. * @param fallbackTexture Define a fallback texture in case there were issues to create the custom texture
  79524. * @param generateMipMaps Define if the texture should creates mip maps or not
  79525. */
  79526. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  79527. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  79528. _this._animate = true;
  79529. _this._time = 0;
  79530. _this._texturePath = texturePath;
  79531. //Try to load json
  79532. _this._loadJson(texturePath);
  79533. _this.refreshRate = 1;
  79534. return _this;
  79535. }
  79536. CustomProceduralTexture.prototype._loadJson = function (jsonUrl) {
  79537. var _this = this;
  79538. var noConfigFile = function () {
  79539. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  79540. try {
  79541. _this.setFragment(_this._texturePath);
  79542. }
  79543. catch (ex) {
  79544. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  79545. }
  79546. };
  79547. var configFileUrl = jsonUrl + "/config.json";
  79548. var xhr = new XMLHttpRequest();
  79549. xhr.open("GET", configFileUrl, true);
  79550. xhr.addEventListener("load", function () {
  79551. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  79552. try {
  79553. _this._config = JSON.parse(xhr.response);
  79554. _this.updateShaderUniforms();
  79555. _this.updateTextures();
  79556. _this.setFragment(_this._texturePath + "/custom");
  79557. _this._animate = _this._config.animate;
  79558. _this.refreshRate = _this._config.refreshrate;
  79559. }
  79560. catch (ex) {
  79561. noConfigFile();
  79562. }
  79563. }
  79564. else {
  79565. noConfigFile();
  79566. }
  79567. }, false);
  79568. xhr.addEventListener("error", function () {
  79569. noConfigFile();
  79570. }, false);
  79571. try {
  79572. xhr.send();
  79573. }
  79574. catch (ex) {
  79575. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  79576. }
  79577. };
  79578. /**
  79579. * Is the texture ready to be used ? (rendered at least once)
  79580. * @returns true if ready, otherwise, false.
  79581. */
  79582. CustomProceduralTexture.prototype.isReady = function () {
  79583. if (!_super.prototype.isReady.call(this)) {
  79584. return false;
  79585. }
  79586. for (var name in this._textures) {
  79587. var texture = this._textures[name];
  79588. if (!texture.isReady()) {
  79589. return false;
  79590. }
  79591. }
  79592. return true;
  79593. };
  79594. /**
  79595. * Render the texture to its associated render target.
  79596. * @param useCameraPostProcess Define if camera post process should be applied to the texture
  79597. */
  79598. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  79599. var scene = this.getScene();
  79600. if (this._animate && scene) {
  79601. this._time += scene.getAnimationRatio() * 0.03;
  79602. this.updateShaderUniforms();
  79603. }
  79604. _super.prototype.render.call(this, useCameraPostProcess);
  79605. };
  79606. /**
  79607. * Update the list of dependant textures samplers in the shader.
  79608. */
  79609. CustomProceduralTexture.prototype.updateTextures = function () {
  79610. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  79611. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  79612. }
  79613. };
  79614. /**
  79615. * Update the uniform values of the procedural texture in the shader.
  79616. */
  79617. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  79618. if (this._config) {
  79619. for (var j = 0; j < this._config.uniforms.length; j++) {
  79620. var uniform = this._config.uniforms[j];
  79621. switch (uniform.type) {
  79622. case "float":
  79623. this.setFloat(uniform.name, uniform.value);
  79624. break;
  79625. case "color3":
  79626. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  79627. break;
  79628. case "color4":
  79629. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  79630. break;
  79631. case "vector2":
  79632. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  79633. break;
  79634. case "vector3":
  79635. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  79636. break;
  79637. }
  79638. }
  79639. }
  79640. this.setFloat("time", this._time);
  79641. };
  79642. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  79643. /**
  79644. * Define if the texture animates or not.
  79645. */
  79646. get: function () {
  79647. return this._animate;
  79648. },
  79649. set: function (value) {
  79650. this._animate = value;
  79651. },
  79652. enumerable: true,
  79653. configurable: true
  79654. });
  79655. return CustomProceduralTexture;
  79656. }(BABYLON.ProceduralTexture));
  79657. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  79658. })(BABYLON || (BABYLON = {}));
  79659. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  79660. var BABYLON;
  79661. (function (BABYLON) {
  79662. /**
  79663. * Manage the gamepad inputs to control a free camera.
  79664. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79665. */
  79666. var FreeCameraGamepadInput = /** @class */ (function () {
  79667. function FreeCameraGamepadInput() {
  79668. /**
  79669. * Defines the gamepad rotation sensiblity.
  79670. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79671. */
  79672. this.gamepadAngularSensibility = 200;
  79673. /**
  79674. * Defines the gamepad move sensiblity.
  79675. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79676. */
  79677. this.gamepadMoveSensibility = 40;
  79678. this._cameraTransform = BABYLON.Matrix.Identity();
  79679. this._deltaTransform = BABYLON.Vector3.Zero();
  79680. this._vector3 = BABYLON.Vector3.Zero();
  79681. this._vector2 = BABYLON.Vector2.Zero();
  79682. }
  79683. /**
  79684. * Attach the input controls to a specific dom element to get the input from.
  79685. * @param element Defines the element the controls should be listened from
  79686. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79687. */
  79688. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79689. var _this = this;
  79690. var manager = this.camera.getScene().gamepadManager;
  79691. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79692. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79693. // prioritize XBOX gamepads.
  79694. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79695. _this.gamepad = gamepad;
  79696. }
  79697. }
  79698. });
  79699. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79700. if (_this.gamepad === gamepad) {
  79701. _this.gamepad = null;
  79702. }
  79703. });
  79704. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79705. };
  79706. /**
  79707. * Detach the current controls from the specified dom element.
  79708. * @param element Defines the element to stop listening the inputs from
  79709. */
  79710. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  79711. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79712. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79713. this.gamepad = null;
  79714. };
  79715. /**
  79716. * Update the current camera state depending on the inputs that have been used this frame.
  79717. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79718. */
  79719. FreeCameraGamepadInput.prototype.checkInputs = function () {
  79720. if (this.gamepad && this.gamepad.leftStick) {
  79721. var camera = this.camera;
  79722. var LSValues = this.gamepad.leftStick;
  79723. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  79724. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79725. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  79726. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  79727. var RSValues = this.gamepad.rightStick;
  79728. if (RSValues) {
  79729. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  79730. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  79731. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  79732. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  79733. }
  79734. else {
  79735. RSValues = { x: 0, y: 0 };
  79736. }
  79737. if (!camera.rotationQuaternion) {
  79738. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  79739. }
  79740. else {
  79741. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  79742. }
  79743. var speed = camera._computeLocalCameraSpeed() * 50.0;
  79744. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  79745. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  79746. camera.cameraDirection.addInPlace(this._deltaTransform);
  79747. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  79748. camera.cameraRotation.addInPlace(this._vector2);
  79749. }
  79750. };
  79751. /**
  79752. * Gets the class name of the current intput.
  79753. * @returns the class name
  79754. */
  79755. FreeCameraGamepadInput.prototype.getClassName = function () {
  79756. return "FreeCameraGamepadInput";
  79757. };
  79758. /**
  79759. * Get the friendly name associated with the input class.
  79760. * @returns the input friendly name
  79761. */
  79762. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  79763. return "gamepad";
  79764. };
  79765. __decorate([
  79766. BABYLON.serialize()
  79767. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  79768. __decorate([
  79769. BABYLON.serialize()
  79770. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79771. return FreeCameraGamepadInput;
  79772. }());
  79773. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  79774. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  79775. })(BABYLON || (BABYLON = {}));
  79776. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  79777. var BABYLON;
  79778. (function (BABYLON) {
  79779. /**
  79780. * Manage the gamepad inputs to control an arc rotate camera.
  79781. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  79782. */
  79783. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  79784. function ArcRotateCameraGamepadInput() {
  79785. /**
  79786. * Defines the gamepad rotation sensiblity.
  79787. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  79788. */
  79789. this.gamepadRotationSensibility = 80;
  79790. /**
  79791. * Defines the gamepad move sensiblity.
  79792. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  79793. */
  79794. this.gamepadMoveSensibility = 40;
  79795. }
  79796. /**
  79797. * Attach the input controls to a specific dom element to get the input from.
  79798. * @param element Defines the element the controls should be listened from
  79799. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  79800. */
  79801. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  79802. var _this = this;
  79803. var manager = this.camera.getScene().gamepadManager;
  79804. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  79805. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  79806. // prioritize XBOX gamepads.
  79807. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  79808. _this.gamepad = gamepad;
  79809. }
  79810. }
  79811. });
  79812. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  79813. if (_this.gamepad === gamepad) {
  79814. _this.gamepad = null;
  79815. }
  79816. });
  79817. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  79818. };
  79819. /**
  79820. * Detach the current controls from the specified dom element.
  79821. * @param element Defines the element to stop listening the inputs from
  79822. */
  79823. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  79824. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  79825. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  79826. this.gamepad = null;
  79827. };
  79828. /**
  79829. * Update the current camera state depending on the inputs that have been used this frame.
  79830. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  79831. */
  79832. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  79833. if (this.gamepad) {
  79834. var camera = this.camera;
  79835. var RSValues = this.gamepad.rightStick;
  79836. if (RSValues) {
  79837. if (RSValues.x != 0) {
  79838. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  79839. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  79840. camera.inertialAlphaOffset += normalizedRX;
  79841. }
  79842. }
  79843. if (RSValues.y != 0) {
  79844. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  79845. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  79846. camera.inertialBetaOffset += normalizedRY;
  79847. }
  79848. }
  79849. }
  79850. var LSValues = this.gamepad.leftStick;
  79851. if (LSValues && LSValues.y != 0) {
  79852. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  79853. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  79854. this.camera.inertialRadiusOffset -= normalizedLY;
  79855. }
  79856. }
  79857. }
  79858. };
  79859. /**
  79860. * Gets the class name of the current intput.
  79861. * @returns the class name
  79862. */
  79863. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  79864. return "ArcRotateCameraGamepadInput";
  79865. };
  79866. /**
  79867. * Get the friendly name associated with the input class.
  79868. * @returns the input friendly name
  79869. */
  79870. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  79871. return "gamepad";
  79872. };
  79873. __decorate([
  79874. BABYLON.serialize()
  79875. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  79876. __decorate([
  79877. BABYLON.serialize()
  79878. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  79879. return ArcRotateCameraGamepadInput;
  79880. }());
  79881. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  79882. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  79883. })(BABYLON || (BABYLON = {}));
  79884. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  79885. var BABYLON;
  79886. (function (BABYLON) {
  79887. /**
  79888. * Manager for handling gamepads
  79889. */
  79890. var GamepadManager = /** @class */ (function () {
  79891. /**
  79892. * Initializes the gamepad manager
  79893. * @param _scene BabylonJS scene
  79894. */
  79895. function GamepadManager(_scene) {
  79896. var _this = this;
  79897. this._scene = _scene;
  79898. this._babylonGamepads = [];
  79899. this._oneGamepadConnected = false;
  79900. /** @hidden */
  79901. this._isMonitoring = false;
  79902. /**
  79903. * observable to be triggered when the gamepad controller has been disconnected
  79904. */
  79905. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  79906. if (!BABYLON.Tools.IsWindowObjectExist()) {
  79907. this._gamepadEventSupported = false;
  79908. }
  79909. else {
  79910. this._gamepadEventSupported = 'GamepadEvent' in window;
  79911. this._gamepadSupport = (navigator.getGamepads ||
  79912. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  79913. }
  79914. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  79915. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  79916. for (var i in _this._babylonGamepads) {
  79917. var gamepad = _this._babylonGamepads[i];
  79918. if (gamepad && gamepad._isConnected) {
  79919. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  79920. }
  79921. }
  79922. });
  79923. this._onGamepadConnectedEvent = function (evt) {
  79924. var gamepad = evt.gamepad;
  79925. if (gamepad.index in _this._babylonGamepads) {
  79926. if (_this._babylonGamepads[gamepad.index].isConnected) {
  79927. return;
  79928. }
  79929. }
  79930. var newGamepad;
  79931. if (_this._babylonGamepads[gamepad.index]) {
  79932. newGamepad = _this._babylonGamepads[gamepad.index];
  79933. newGamepad.browserGamepad = gamepad;
  79934. newGamepad._isConnected = true;
  79935. }
  79936. else {
  79937. newGamepad = _this._addNewGamepad(gamepad);
  79938. }
  79939. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  79940. _this._startMonitoringGamepads();
  79941. };
  79942. this._onGamepadDisconnectedEvent = function (evt) {
  79943. var gamepad = evt.gamepad;
  79944. // Remove the gamepad from the list of gamepads to monitor.
  79945. for (var i in _this._babylonGamepads) {
  79946. if (_this._babylonGamepads[i].index === gamepad.index) {
  79947. var disconnectedGamepad = _this._babylonGamepads[i];
  79948. disconnectedGamepad._isConnected = false;
  79949. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  79950. break;
  79951. }
  79952. }
  79953. };
  79954. if (this._gamepadSupport) {
  79955. //first add already-connected gamepads
  79956. this._updateGamepadObjects();
  79957. if (this._babylonGamepads.length) {
  79958. this._startMonitoringGamepads();
  79959. }
  79960. // Checking if the gamepad connected event is supported (like in Firefox)
  79961. if (this._gamepadEventSupported) {
  79962. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  79963. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  79964. }
  79965. else {
  79966. this._startMonitoringGamepads();
  79967. }
  79968. }
  79969. }
  79970. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  79971. /**
  79972. * The gamepads in the game pad manager
  79973. */
  79974. get: function () {
  79975. return this._babylonGamepads;
  79976. },
  79977. enumerable: true,
  79978. configurable: true
  79979. });
  79980. /**
  79981. * Get the gamepad controllers based on type
  79982. * @param type The type of gamepad controller
  79983. * @returns Nullable gamepad
  79984. */
  79985. GamepadManager.prototype.getGamepadByType = function (type) {
  79986. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  79987. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  79988. var gamepad = _a[_i];
  79989. if (gamepad && gamepad.type === type) {
  79990. return gamepad;
  79991. }
  79992. }
  79993. return null;
  79994. };
  79995. /**
  79996. * Disposes the gamepad manager
  79997. */
  79998. GamepadManager.prototype.dispose = function () {
  79999. if (this._gamepadEventSupported) {
  80000. if (this._onGamepadConnectedEvent) {
  80001. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  80002. }
  80003. if (this._onGamepadDisconnectedEvent) {
  80004. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  80005. }
  80006. this._onGamepadConnectedEvent = null;
  80007. this._onGamepadDisconnectedEvent = null;
  80008. }
  80009. this._babylonGamepads.forEach(function (gamepad) {
  80010. gamepad.dispose();
  80011. });
  80012. this.onGamepadConnectedObservable.clear();
  80013. this.onGamepadDisconnectedObservable.clear();
  80014. this._oneGamepadConnected = false;
  80015. this._stopMonitoringGamepads();
  80016. this._babylonGamepads = [];
  80017. };
  80018. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  80019. if (!this._oneGamepadConnected) {
  80020. this._oneGamepadConnected = true;
  80021. }
  80022. var newGamepad;
  80023. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  80024. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  80025. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  80026. }
  80027. // if pose is supported, use the (WebVR) pose enabled controller
  80028. else if (gamepad.pose) {
  80029. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  80030. }
  80031. else {
  80032. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  80033. }
  80034. this._babylonGamepads[newGamepad.index] = newGamepad;
  80035. return newGamepad;
  80036. };
  80037. GamepadManager.prototype._startMonitoringGamepads = function () {
  80038. if (!this._isMonitoring) {
  80039. this._isMonitoring = true;
  80040. //back-comp
  80041. if (!this._scene) {
  80042. this._checkGamepadsStatus();
  80043. }
  80044. }
  80045. };
  80046. GamepadManager.prototype._stopMonitoringGamepads = function () {
  80047. this._isMonitoring = false;
  80048. };
  80049. /** @hidden */
  80050. GamepadManager.prototype._checkGamepadsStatus = function () {
  80051. var _this = this;
  80052. // Hack to be compatible Chrome
  80053. this._updateGamepadObjects();
  80054. for (var i in this._babylonGamepads) {
  80055. var gamepad = this._babylonGamepads[i];
  80056. if (!gamepad || !gamepad.isConnected) {
  80057. continue;
  80058. }
  80059. gamepad.update();
  80060. }
  80061. if (this._isMonitoring && !this._scene) {
  80062. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  80063. }
  80064. };
  80065. // This function is called only on Chrome, which does not properly support
  80066. // connection/disconnection events and forces you to recopy again the gamepad object
  80067. GamepadManager.prototype._updateGamepadObjects = function () {
  80068. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  80069. for (var i = 0; i < gamepads.length; i++) {
  80070. var gamepad = gamepads[i];
  80071. if (gamepad) {
  80072. if (!this._babylonGamepads[gamepad.index]) {
  80073. var newGamepad = this._addNewGamepad(gamepad);
  80074. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  80075. }
  80076. else {
  80077. // Forced to copy again this object for Chrome for unknown reason
  80078. this._babylonGamepads[i].browserGamepad = gamepad;
  80079. if (!this._babylonGamepads[i].isConnected) {
  80080. this._babylonGamepads[i]._isConnected = true;
  80081. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  80082. }
  80083. }
  80084. }
  80085. }
  80086. };
  80087. return GamepadManager;
  80088. }());
  80089. BABYLON.GamepadManager = GamepadManager;
  80090. })(BABYLON || (BABYLON = {}));
  80091. //# sourceMappingURL=babylon.gamepadManager.js.map
  80092. var BABYLON;
  80093. (function (BABYLON) {
  80094. /**
  80095. * Represents a gamepad control stick position
  80096. */
  80097. var StickValues = /** @class */ (function () {
  80098. /**
  80099. * Initializes the gamepad x and y control stick values
  80100. * @param x The x component of the gamepad control stick value
  80101. * @param y The y component of the gamepad control stick value
  80102. */
  80103. function StickValues(
  80104. /**
  80105. * The x component of the control stick
  80106. */
  80107. x,
  80108. /**
  80109. * The y component of the control stick
  80110. */
  80111. y) {
  80112. this.x = x;
  80113. this.y = y;
  80114. }
  80115. return StickValues;
  80116. }());
  80117. BABYLON.StickValues = StickValues;
  80118. /**
  80119. * Represents a gamepad
  80120. */
  80121. var Gamepad = /** @class */ (function () {
  80122. /**
  80123. * Initializes the gamepad
  80124. * @param id The id of the gamepad
  80125. * @param index The index of the gamepad
  80126. * @param browserGamepad The browser gamepad
  80127. * @param leftStickX The x component of the left joystick
  80128. * @param leftStickY The y component of the left joystick
  80129. * @param rightStickX The x component of the right joystick
  80130. * @param rightStickY The y component of the right joystick
  80131. */
  80132. function Gamepad(
  80133. /**
  80134. * The id of the gamepad
  80135. */
  80136. id,
  80137. /**
  80138. * The index of the gamepad
  80139. */
  80140. index,
  80141. /**
  80142. * The browser gamepad
  80143. */
  80144. browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  80145. if (leftStickX === void 0) { leftStickX = 0; }
  80146. if (leftStickY === void 0) { leftStickY = 1; }
  80147. if (rightStickX === void 0) { rightStickX = 2; }
  80148. if (rightStickY === void 0) { rightStickY = 3; }
  80149. this.id = id;
  80150. this.index = index;
  80151. this.browserGamepad = browserGamepad;
  80152. this._leftStick = { x: 0, y: 0 };
  80153. this._rightStick = { x: 0, y: 0 };
  80154. /** @hidden */
  80155. this._isConnected = true;
  80156. /**
  80157. * Specifies whether the left control stick should be Y-inverted
  80158. */
  80159. this._invertLeftStickY = false;
  80160. this.type = Gamepad.GAMEPAD;
  80161. this._leftStickAxisX = leftStickX;
  80162. this._leftStickAxisY = leftStickY;
  80163. this._rightStickAxisX = rightStickX;
  80164. this._rightStickAxisY = rightStickY;
  80165. if (this.browserGamepad.axes.length >= 2) {
  80166. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80167. }
  80168. if (this.browserGamepad.axes.length >= 4) {
  80169. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80170. }
  80171. }
  80172. Object.defineProperty(Gamepad.prototype, "isConnected", {
  80173. /**
  80174. * Specifies if the gamepad has been connected
  80175. */
  80176. get: function () {
  80177. return this._isConnected;
  80178. },
  80179. enumerable: true,
  80180. configurable: true
  80181. });
  80182. /**
  80183. * Callback triggered when the left joystick has changed
  80184. * @param callback
  80185. */
  80186. Gamepad.prototype.onleftstickchanged = function (callback) {
  80187. this._onleftstickchanged = callback;
  80188. };
  80189. /**
  80190. * Callback triggered when the right joystick has changed
  80191. * @param callback
  80192. */
  80193. Gamepad.prototype.onrightstickchanged = function (callback) {
  80194. this._onrightstickchanged = callback;
  80195. };
  80196. Object.defineProperty(Gamepad.prototype, "leftStick", {
  80197. /**
  80198. * Gets the left joystick
  80199. */
  80200. get: function () {
  80201. return this._leftStick;
  80202. },
  80203. /**
  80204. * Sets the left joystick values
  80205. */
  80206. set: function (newValues) {
  80207. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  80208. this._onleftstickchanged(newValues);
  80209. }
  80210. this._leftStick = newValues;
  80211. },
  80212. enumerable: true,
  80213. configurable: true
  80214. });
  80215. Object.defineProperty(Gamepad.prototype, "rightStick", {
  80216. /**
  80217. * Gets the right joystick
  80218. */
  80219. get: function () {
  80220. return this._rightStick;
  80221. },
  80222. /**
  80223. * Sets the right joystick value
  80224. */
  80225. set: function (newValues) {
  80226. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  80227. this._onrightstickchanged(newValues);
  80228. }
  80229. this._rightStick = newValues;
  80230. },
  80231. enumerable: true,
  80232. configurable: true
  80233. });
  80234. /**
  80235. * Updates the gamepad joystick positions
  80236. */
  80237. Gamepad.prototype.update = function () {
  80238. if (this._leftStick) {
  80239. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  80240. if (this._invertLeftStickY) {
  80241. this.leftStick.y *= -1;
  80242. }
  80243. }
  80244. if (this._rightStick) {
  80245. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  80246. }
  80247. };
  80248. /**
  80249. * Disposes the gamepad
  80250. */
  80251. Gamepad.prototype.dispose = function () {
  80252. };
  80253. /**
  80254. * Represents a gamepad controller
  80255. */
  80256. Gamepad.GAMEPAD = 0;
  80257. /**
  80258. * Represents a generic controller
  80259. */
  80260. Gamepad.GENERIC = 1;
  80261. /**
  80262. * Represents an XBox controller
  80263. */
  80264. Gamepad.XBOX = 2;
  80265. /**
  80266. * Represents a pose-enabled controller
  80267. */
  80268. Gamepad.POSE_ENABLED = 3;
  80269. return Gamepad;
  80270. }());
  80271. BABYLON.Gamepad = Gamepad;
  80272. /**
  80273. * Represents a generic gamepad
  80274. */
  80275. var GenericPad = /** @class */ (function (_super) {
  80276. __extends(GenericPad, _super);
  80277. /**
  80278. * Initializes the generic gamepad
  80279. * @param id The id of the generic gamepad
  80280. * @param index The index of the generic gamepad
  80281. * @param browserGamepad The browser gamepad
  80282. */
  80283. function GenericPad(id, index, browserGamepad) {
  80284. var _this = _super.call(this, id, index, browserGamepad) || this;
  80285. /**
  80286. * Observable triggered when a button has been pressed
  80287. */
  80288. _this.onButtonDownObservable = new BABYLON.Observable();
  80289. /**
  80290. * Observable triggered when a button has been released
  80291. */
  80292. _this.onButtonUpObservable = new BABYLON.Observable();
  80293. _this.type = Gamepad.GENERIC;
  80294. _this._buttons = new Array(browserGamepad.buttons.length);
  80295. return _this;
  80296. }
  80297. /**
  80298. * Callback triggered when a button has been pressed
  80299. * @param callback Called when a button has been pressed
  80300. */
  80301. GenericPad.prototype.onbuttondown = function (callback) {
  80302. this._onbuttondown = callback;
  80303. };
  80304. /**
  80305. * Callback triggered when a button has been released
  80306. * @param callback Called when a button has been released
  80307. */
  80308. GenericPad.prototype.onbuttonup = function (callback) {
  80309. this._onbuttonup = callback;
  80310. };
  80311. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  80312. if (newValue !== currentValue) {
  80313. if (newValue === 1) {
  80314. if (this._onbuttondown) {
  80315. this._onbuttondown(buttonIndex);
  80316. }
  80317. this.onButtonDownObservable.notifyObservers(buttonIndex);
  80318. }
  80319. if (newValue === 0) {
  80320. if (this._onbuttonup) {
  80321. this._onbuttonup(buttonIndex);
  80322. }
  80323. this.onButtonUpObservable.notifyObservers(buttonIndex);
  80324. }
  80325. }
  80326. return newValue;
  80327. };
  80328. /**
  80329. * Updates the generic gamepad
  80330. */
  80331. GenericPad.prototype.update = function () {
  80332. _super.prototype.update.call(this);
  80333. for (var index = 0; index < this._buttons.length; index++) {
  80334. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  80335. }
  80336. };
  80337. /**
  80338. * Disposes the generic gamepad
  80339. */
  80340. GenericPad.prototype.dispose = function () {
  80341. _super.prototype.dispose.call(this);
  80342. this.onButtonDownObservable.clear();
  80343. this.onButtonUpObservable.clear();
  80344. };
  80345. return GenericPad;
  80346. }(Gamepad));
  80347. BABYLON.GenericPad = GenericPad;
  80348. })(BABYLON || (BABYLON = {}));
  80349. //# sourceMappingURL=babylon.gamepad.js.map
  80350. var BABYLON;
  80351. (function (BABYLON) {
  80352. /**
  80353. * Defines supported buttons for XBox360 compatible gamepads
  80354. */
  80355. var Xbox360Button;
  80356. (function (Xbox360Button) {
  80357. /** A */
  80358. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  80359. /** B */
  80360. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  80361. /** X */
  80362. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  80363. /** Y */
  80364. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  80365. /** Start */
  80366. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  80367. /** Back */
  80368. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  80369. /** Left button */
  80370. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  80371. /** Right button */
  80372. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  80373. /** Left stick */
  80374. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  80375. /** Right stick */
  80376. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  80377. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  80378. /** Defines values for XBox360 DPad */
  80379. var Xbox360Dpad;
  80380. (function (Xbox360Dpad) {
  80381. /** Up */
  80382. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  80383. /** Down */
  80384. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  80385. /** Left */
  80386. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  80387. /** Right */
  80388. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  80389. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  80390. /**
  80391. * Defines a XBox360 gamepad
  80392. */
  80393. var Xbox360Pad = /** @class */ (function (_super) {
  80394. __extends(Xbox360Pad, _super);
  80395. /**
  80396. * Creates a new XBox360 gamepad object
  80397. * @param id defines the id of this gamepad
  80398. * @param index defines its index
  80399. * @param gamepad defines the internal HTML gamepad object
  80400. * @param xboxOne defines if it is a XBox One gamepad
  80401. */
  80402. function Xbox360Pad(id, index, gamepad, xboxOne) {
  80403. if (xboxOne === void 0) { xboxOne = false; }
  80404. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  80405. _this._leftTrigger = 0;
  80406. _this._rightTrigger = 0;
  80407. /** Observable raised when a button is pressed */
  80408. _this.onButtonDownObservable = new BABYLON.Observable();
  80409. /** Observable raised when a button is released */
  80410. _this.onButtonUpObservable = new BABYLON.Observable();
  80411. /** Observable raised when a pad is pressed */
  80412. _this.onPadDownObservable = new BABYLON.Observable();
  80413. /** Observable raised when a pad is released */
  80414. _this.onPadUpObservable = new BABYLON.Observable();
  80415. _this._buttonA = 0;
  80416. _this._buttonB = 0;
  80417. _this._buttonX = 0;
  80418. _this._buttonY = 0;
  80419. _this._buttonBack = 0;
  80420. _this._buttonStart = 0;
  80421. _this._buttonLB = 0;
  80422. _this._buttonRB = 0;
  80423. _this._buttonLeftStick = 0;
  80424. _this._buttonRightStick = 0;
  80425. _this._dPadUp = 0;
  80426. _this._dPadDown = 0;
  80427. _this._dPadLeft = 0;
  80428. _this._dPadRight = 0;
  80429. _this._isXboxOnePad = false;
  80430. _this.type = BABYLON.Gamepad.XBOX;
  80431. _this._isXboxOnePad = xboxOne;
  80432. return _this;
  80433. }
  80434. /**
  80435. * Defines the callback to call when left trigger is pressed
  80436. * @param callback defines the callback to use
  80437. */
  80438. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  80439. this._onlefttriggerchanged = callback;
  80440. };
  80441. /**
  80442. * Defines the callback to call when right trigger is pressed
  80443. * @param callback defines the callback to use
  80444. */
  80445. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  80446. this._onrighttriggerchanged = callback;
  80447. };
  80448. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  80449. /**
  80450. * Gets the left trigger value
  80451. */
  80452. get: function () {
  80453. return this._leftTrigger;
  80454. },
  80455. /**
  80456. * Sets the left trigger value
  80457. */
  80458. set: function (newValue) {
  80459. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  80460. this._onlefttriggerchanged(newValue);
  80461. }
  80462. this._leftTrigger = newValue;
  80463. },
  80464. enumerable: true,
  80465. configurable: true
  80466. });
  80467. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  80468. /**
  80469. * Gets the right trigger value
  80470. */
  80471. get: function () {
  80472. return this._rightTrigger;
  80473. },
  80474. /**
  80475. * Sets the right trigger value
  80476. */
  80477. set: function (newValue) {
  80478. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  80479. this._onrighttriggerchanged(newValue);
  80480. }
  80481. this._rightTrigger = newValue;
  80482. },
  80483. enumerable: true,
  80484. configurable: true
  80485. });
  80486. /**
  80487. * Defines the callback to call when a button is pressed
  80488. * @param callback defines the callback to use
  80489. */
  80490. Xbox360Pad.prototype.onbuttondown = function (callback) {
  80491. this._onbuttondown = callback;
  80492. };
  80493. /**
  80494. * Defines the callback to call when a button is released
  80495. * @param callback defines the callback to use
  80496. */
  80497. Xbox360Pad.prototype.onbuttonup = function (callback) {
  80498. this._onbuttonup = callback;
  80499. };
  80500. /**
  80501. * Defines the callback to call when a pad is pressed
  80502. * @param callback defines the callback to use
  80503. */
  80504. Xbox360Pad.prototype.ondpaddown = function (callback) {
  80505. this._ondpaddown = callback;
  80506. };
  80507. /**
  80508. * Defines the callback to call when a pad is released
  80509. * @param callback defines the callback to use
  80510. */
  80511. Xbox360Pad.prototype.ondpadup = function (callback) {
  80512. this._ondpadup = callback;
  80513. };
  80514. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  80515. if (newValue !== currentValue) {
  80516. if (newValue === 1) {
  80517. if (this._onbuttondown) {
  80518. this._onbuttondown(buttonType);
  80519. }
  80520. this.onButtonDownObservable.notifyObservers(buttonType);
  80521. }
  80522. if (newValue === 0) {
  80523. if (this._onbuttonup) {
  80524. this._onbuttonup(buttonType);
  80525. }
  80526. this.onButtonUpObservable.notifyObservers(buttonType);
  80527. }
  80528. }
  80529. return newValue;
  80530. };
  80531. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  80532. if (newValue !== currentValue) {
  80533. if (newValue === 1) {
  80534. if (this._ondpaddown) {
  80535. this._ondpaddown(buttonType);
  80536. }
  80537. this.onPadDownObservable.notifyObservers(buttonType);
  80538. }
  80539. if (newValue === 0) {
  80540. if (this._ondpadup) {
  80541. this._ondpadup(buttonType);
  80542. }
  80543. this.onPadUpObservable.notifyObservers(buttonType);
  80544. }
  80545. }
  80546. return newValue;
  80547. };
  80548. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  80549. /**
  80550. * Gets the value of the `A` button
  80551. */
  80552. get: function () {
  80553. return this._buttonA;
  80554. },
  80555. /**
  80556. * Sets the value of the `A` button
  80557. */
  80558. set: function (value) {
  80559. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  80560. },
  80561. enumerable: true,
  80562. configurable: true
  80563. });
  80564. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  80565. /**
  80566. * Gets the value of the `B` button
  80567. */
  80568. get: function () {
  80569. return this._buttonB;
  80570. },
  80571. /**
  80572. * Sets the value of the `B` button
  80573. */
  80574. set: function (value) {
  80575. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  80576. },
  80577. enumerable: true,
  80578. configurable: true
  80579. });
  80580. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  80581. /**
  80582. * Gets the value of the `X` button
  80583. */
  80584. get: function () {
  80585. return this._buttonX;
  80586. },
  80587. /**
  80588. * Sets the value of the `X` button
  80589. */
  80590. set: function (value) {
  80591. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  80592. },
  80593. enumerable: true,
  80594. configurable: true
  80595. });
  80596. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  80597. /**
  80598. * Gets the value of the `Y` button
  80599. */
  80600. get: function () {
  80601. return this._buttonY;
  80602. },
  80603. /**
  80604. * Sets the value of the `Y` button
  80605. */
  80606. set: function (value) {
  80607. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  80608. },
  80609. enumerable: true,
  80610. configurable: true
  80611. });
  80612. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  80613. /**
  80614. * Gets the value of the `Start` button
  80615. */
  80616. get: function () {
  80617. return this._buttonStart;
  80618. },
  80619. /**
  80620. * Sets the value of the `Start` button
  80621. */
  80622. set: function (value) {
  80623. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  80624. },
  80625. enumerable: true,
  80626. configurable: true
  80627. });
  80628. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  80629. /**
  80630. * Gets the value of the `Back` button
  80631. */
  80632. get: function () {
  80633. return this._buttonBack;
  80634. },
  80635. /**
  80636. * Sets the value of the `Back` button
  80637. */
  80638. set: function (value) {
  80639. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  80640. },
  80641. enumerable: true,
  80642. configurable: true
  80643. });
  80644. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  80645. /**
  80646. * Gets the value of the `Left` button
  80647. */
  80648. get: function () {
  80649. return this._buttonLB;
  80650. },
  80651. /**
  80652. * Sets the value of the `Left` button
  80653. */
  80654. set: function (value) {
  80655. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  80656. },
  80657. enumerable: true,
  80658. configurable: true
  80659. });
  80660. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  80661. /**
  80662. * Gets the value of the `Right` button
  80663. */
  80664. get: function () {
  80665. return this._buttonRB;
  80666. },
  80667. /**
  80668. * Sets the value of the `Right` button
  80669. */
  80670. set: function (value) {
  80671. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  80672. },
  80673. enumerable: true,
  80674. configurable: true
  80675. });
  80676. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  80677. /**
  80678. * Gets the value of the Left joystick
  80679. */
  80680. get: function () {
  80681. return this._buttonLeftStick;
  80682. },
  80683. /**
  80684. * Sets the value of the Left joystick
  80685. */
  80686. set: function (value) {
  80687. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  80688. },
  80689. enumerable: true,
  80690. configurable: true
  80691. });
  80692. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  80693. /**
  80694. * Gets the value of the Right joystick
  80695. */
  80696. get: function () {
  80697. return this._buttonRightStick;
  80698. },
  80699. /**
  80700. * Sets the value of the Right joystick
  80701. */
  80702. set: function (value) {
  80703. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  80704. },
  80705. enumerable: true,
  80706. configurable: true
  80707. });
  80708. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  80709. /**
  80710. * Gets the value of D-pad up
  80711. */
  80712. get: function () {
  80713. return this._dPadUp;
  80714. },
  80715. /**
  80716. * Sets the value of D-pad up
  80717. */
  80718. set: function (value) {
  80719. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  80720. },
  80721. enumerable: true,
  80722. configurable: true
  80723. });
  80724. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  80725. /**
  80726. * Gets the value of D-pad down
  80727. */
  80728. get: function () {
  80729. return this._dPadDown;
  80730. },
  80731. /**
  80732. * Sets the value of D-pad down
  80733. */
  80734. set: function (value) {
  80735. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  80736. },
  80737. enumerable: true,
  80738. configurable: true
  80739. });
  80740. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  80741. /**
  80742. * Gets the value of D-pad left
  80743. */
  80744. get: function () {
  80745. return this._dPadLeft;
  80746. },
  80747. /**
  80748. * Sets the value of D-pad left
  80749. */
  80750. set: function (value) {
  80751. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  80752. },
  80753. enumerable: true,
  80754. configurable: true
  80755. });
  80756. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  80757. /**
  80758. * Gets the value of D-pad right
  80759. */
  80760. get: function () {
  80761. return this._dPadRight;
  80762. },
  80763. /**
  80764. * Sets the value of D-pad right
  80765. */
  80766. set: function (value) {
  80767. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  80768. },
  80769. enumerable: true,
  80770. configurable: true
  80771. });
  80772. /**
  80773. * Force the gamepad to synchronize with device values
  80774. */
  80775. Xbox360Pad.prototype.update = function () {
  80776. _super.prototype.update.call(this);
  80777. if (this._isXboxOnePad) {
  80778. this.buttonA = this.browserGamepad.buttons[0].value;
  80779. this.buttonB = this.browserGamepad.buttons[1].value;
  80780. this.buttonX = this.browserGamepad.buttons[2].value;
  80781. this.buttonY = this.browserGamepad.buttons[3].value;
  80782. this.buttonLB = this.browserGamepad.buttons[4].value;
  80783. this.buttonRB = this.browserGamepad.buttons[5].value;
  80784. this.leftTrigger = this.browserGamepad.axes[2];
  80785. this.rightTrigger = this.browserGamepad.axes[5];
  80786. this.buttonBack = this.browserGamepad.buttons[9].value;
  80787. this.buttonStart = this.browserGamepad.buttons[8].value;
  80788. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  80789. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  80790. this.dPadUp = this.browserGamepad.buttons[11].value;
  80791. this.dPadDown = this.browserGamepad.buttons[12].value;
  80792. this.dPadLeft = this.browserGamepad.buttons[13].value;
  80793. this.dPadRight = this.browserGamepad.buttons[14].value;
  80794. }
  80795. else {
  80796. this.buttonA = this.browserGamepad.buttons[0].value;
  80797. this.buttonB = this.browserGamepad.buttons[1].value;
  80798. this.buttonX = this.browserGamepad.buttons[2].value;
  80799. this.buttonY = this.browserGamepad.buttons[3].value;
  80800. this.buttonLB = this.browserGamepad.buttons[4].value;
  80801. this.buttonRB = this.browserGamepad.buttons[5].value;
  80802. this.leftTrigger = this.browserGamepad.buttons[6].value;
  80803. this.rightTrigger = this.browserGamepad.buttons[7].value;
  80804. this.buttonBack = this.browserGamepad.buttons[8].value;
  80805. this.buttonStart = this.browserGamepad.buttons[9].value;
  80806. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  80807. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  80808. this.dPadUp = this.browserGamepad.buttons[12].value;
  80809. this.dPadDown = this.browserGamepad.buttons[13].value;
  80810. this.dPadLeft = this.browserGamepad.buttons[14].value;
  80811. this.dPadRight = this.browserGamepad.buttons[15].value;
  80812. }
  80813. };
  80814. /**
  80815. * Disposes the gamepad
  80816. */
  80817. Xbox360Pad.prototype.dispose = function () {
  80818. _super.prototype.dispose.call(this);
  80819. this.onButtonDownObservable.clear();
  80820. this.onButtonUpObservable.clear();
  80821. this.onPadDownObservable.clear();
  80822. this.onPadUpObservable.clear();
  80823. };
  80824. return Xbox360Pad;
  80825. }(BABYLON.Gamepad));
  80826. BABYLON.Xbox360Pad = Xbox360Pad;
  80827. })(BABYLON || (BABYLON = {}));
  80828. //# sourceMappingURL=babylon.xboxGamepad.js.map
  80829. var BABYLON;
  80830. (function (BABYLON) {
  80831. /**
  80832. * Defines the types of pose enabled controllers that are supported
  80833. */
  80834. var PoseEnabledControllerType;
  80835. (function (PoseEnabledControllerType) {
  80836. /**
  80837. * HTC Vive
  80838. */
  80839. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  80840. /**
  80841. * Oculus Rift
  80842. */
  80843. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  80844. /**
  80845. * Windows mixed reality
  80846. */
  80847. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  80848. /**
  80849. * Samsung gear VR
  80850. */
  80851. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  80852. /**
  80853. * Google Daydream
  80854. */
  80855. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  80856. /**
  80857. * Generic
  80858. */
  80859. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  80860. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  80861. /**
  80862. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80863. */
  80864. var PoseEnabledControllerHelper = /** @class */ (function () {
  80865. function PoseEnabledControllerHelper() {
  80866. }
  80867. /**
  80868. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  80869. * @param vrGamepad the gamepad to initialized
  80870. * @returns a vr controller of the type the gamepad identified as
  80871. */
  80872. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  80873. // Oculus Touch
  80874. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  80875. return new BABYLON.OculusTouchController(vrGamepad);
  80876. }
  80877. // Windows Mixed Reality controllers
  80878. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  80879. return new BABYLON.WindowsMotionController(vrGamepad);
  80880. }
  80881. // HTC Vive
  80882. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  80883. return new BABYLON.ViveController(vrGamepad);
  80884. }
  80885. // Samsung/Oculus Gear VR or Oculus Go
  80886. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  80887. return new BABYLON.GearVRController(vrGamepad);
  80888. }
  80889. // Google Daydream
  80890. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  80891. return new BABYLON.DaydreamController(vrGamepad);
  80892. }
  80893. // Generic
  80894. else {
  80895. return new BABYLON.GenericController(vrGamepad);
  80896. }
  80897. };
  80898. return PoseEnabledControllerHelper;
  80899. }());
  80900. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  80901. /**
  80902. * Defines the PoseEnabledController object that contains state of a vr capable controller
  80903. */
  80904. var PoseEnabledController = /** @class */ (function (_super) {
  80905. __extends(PoseEnabledController, _super);
  80906. /**
  80907. * Creates a new PoseEnabledController from a gamepad
  80908. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  80909. */
  80910. function PoseEnabledController(browserGamepad) {
  80911. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  80912. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  80913. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  80914. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  80915. /**
  80916. * The device position in babylon space
  80917. */
  80918. _this.devicePosition = BABYLON.Vector3.Zero();
  80919. /**
  80920. * The device rotation in babylon space
  80921. */
  80922. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  80923. /**
  80924. * The scale factor of the device in babylon space
  80925. */
  80926. _this.deviceScaleFactor = 1;
  80927. // Used to convert 6dof controllers to 3dof
  80928. _this._trackPosition = true;
  80929. _this._maxRotationDistFromHeadset = Math.PI / 5;
  80930. _this._draggedRoomRotation = 0;
  80931. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  80932. /**
  80933. * Internal, matrix used to convert room space to babylon space
  80934. * @hidden
  80935. */
  80936. _this._deviceToWorld = BABYLON.Matrix.Identity();
  80937. /**
  80938. * Node to be used when casting a ray from the controller
  80939. * @hidden
  80940. */
  80941. _this._pointingPoseNode = null;
  80942. _this._workingMatrix = BABYLON.Matrix.Identity();
  80943. /**
  80944. * @hidden
  80945. */
  80946. _this._meshAttachedObservable = new BABYLON.Observable();
  80947. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  80948. _this.controllerType = PoseEnabledControllerType.GENERIC;
  80949. _this.position = BABYLON.Vector3.Zero();
  80950. _this.rotationQuaternion = new BABYLON.Quaternion();
  80951. _this._calculatedPosition = BABYLON.Vector3.Zero();
  80952. _this._calculatedRotation = new BABYLON.Quaternion();
  80953. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  80954. return _this;
  80955. }
  80956. /**
  80957. * @hidden
  80958. */
  80959. PoseEnabledController.prototype._disableTrackPosition = function (fixedPosition) {
  80960. if (this._trackPosition) {
  80961. this._calculatedPosition.copyFrom(fixedPosition);
  80962. this._trackPosition = false;
  80963. }
  80964. };
  80965. /**
  80966. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  80967. */
  80968. PoseEnabledController.prototype.update = function () {
  80969. _super.prototype.update.call(this);
  80970. this._updatePoseAndMesh();
  80971. };
  80972. /**
  80973. * Updates only the pose device and mesh without doing any button event checking
  80974. */
  80975. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  80976. var pose = this.browserGamepad.pose;
  80977. this.updateFromDevice(pose);
  80978. if (!this._trackPosition && BABYLON.Engine.LastCreatedScene && BABYLON.Engine.LastCreatedScene.activeCamera && BABYLON.Engine.LastCreatedScene.activeCamera.devicePosition) {
  80979. var camera = BABYLON.Engine.LastCreatedScene.activeCamera;
  80980. camera._computeDevicePosition();
  80981. this._deviceToWorld.setTranslation(camera.devicePosition);
  80982. if (camera.deviceRotationQuaternion) {
  80983. var camera = camera;
  80984. camera._deviceRoomRotationQuaternion.toEulerAnglesToRef(BABYLON.Tmp.Vector3[0]);
  80985. // Find the radian distance away that the headset is from the controllers rotation
  80986. var distanceAway = Math.atan2(Math.sin(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation), Math.cos(BABYLON.Tmp.Vector3[0].y - this._draggedRoomRotation));
  80987. if (Math.abs(distanceAway) > this._maxRotationDistFromHeadset) {
  80988. // Only rotate enouph to be within the _maxRotationDistFromHeadset
  80989. var rotationAmount = distanceAway - (distanceAway < 0 ? -this._maxRotationDistFromHeadset : this._maxRotationDistFromHeadset);
  80990. this._draggedRoomRotation += rotationAmount;
  80991. // Rotate controller around headset
  80992. var sin = Math.sin(-rotationAmount);
  80993. var cos = Math.cos(-rotationAmount);
  80994. this._calculatedPosition.x = this._calculatedPosition.x * cos - this._calculatedPosition.z * sin;
  80995. this._calculatedPosition.z = this._calculatedPosition.x * sin + this._calculatedPosition.z * cos;
  80996. }
  80997. }
  80998. }
  80999. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  81000. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  81001. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  81002. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  81003. if (this._mesh) {
  81004. this._mesh.position.copyFrom(this.devicePosition);
  81005. if (this._mesh.rotationQuaternion) {
  81006. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  81007. }
  81008. }
  81009. };
  81010. /**
  81011. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  81012. * @param poseData raw pose fromthe device
  81013. */
  81014. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  81015. if (poseData) {
  81016. this.rawPose = poseData;
  81017. if (poseData.position) {
  81018. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  81019. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  81020. this._deviceRoomPosition.z *= -1;
  81021. }
  81022. if (this._trackPosition) {
  81023. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  81024. }
  81025. this._calculatedPosition.addInPlace(this.position);
  81026. }
  81027. var pose = this.rawPose;
  81028. if (poseData.orientation && pose.orientation) {
  81029. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  81030. if (this._mesh) {
  81031. if (this._mesh.getScene().useRightHandedSystem) {
  81032. this._deviceRoomRotationQuaternion.z *= -1;
  81033. this._deviceRoomRotationQuaternion.w *= -1;
  81034. }
  81035. else {
  81036. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  81037. }
  81038. }
  81039. // if the camera is set, rotate to the camera's rotation
  81040. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  81041. }
  81042. }
  81043. };
  81044. /**
  81045. * Attaches a mesh to the controller
  81046. * @param mesh the mesh to be attached
  81047. */
  81048. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  81049. if (this._mesh) {
  81050. this._mesh.parent = null;
  81051. }
  81052. this._mesh = mesh;
  81053. if (this._poseControlledCamera) {
  81054. this._mesh.parent = this._poseControlledCamera;
  81055. }
  81056. if (!this._mesh.rotationQuaternion) {
  81057. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  81058. }
  81059. // 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
  81060. this._updatePoseAndMesh();
  81061. if (this._pointingPoseNode) {
  81062. var parents = [];
  81063. var obj = this._pointingPoseNode;
  81064. while (obj.parent) {
  81065. parents.push(obj.parent);
  81066. obj = obj.parent;
  81067. }
  81068. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  81069. }
  81070. this._meshAttachedObservable.notifyObservers(mesh);
  81071. };
  81072. /**
  81073. * Attaches the controllers mesh to a camera
  81074. * @param camera the camera the mesh should be attached to
  81075. */
  81076. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  81077. this._poseControlledCamera = camera;
  81078. if (this._mesh) {
  81079. this._mesh.parent = this._poseControlledCamera;
  81080. }
  81081. };
  81082. /**
  81083. * Disposes of the controller
  81084. */
  81085. PoseEnabledController.prototype.dispose = function () {
  81086. if (this._mesh) {
  81087. this._mesh.dispose();
  81088. }
  81089. this._mesh = null;
  81090. _super.prototype.dispose.call(this);
  81091. };
  81092. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  81093. /**
  81094. * The mesh that is attached to the controller
  81095. */
  81096. get: function () {
  81097. return this._mesh;
  81098. },
  81099. enumerable: true,
  81100. configurable: true
  81101. });
  81102. /**
  81103. * Gets the ray of the controller in the direction the controller is pointing
  81104. * @param length the length the resulting ray should be
  81105. * @returns a ray in the direction the controller is pointing
  81106. */
  81107. PoseEnabledController.prototype.getForwardRay = function (length) {
  81108. if (length === void 0) { length = 100; }
  81109. if (!this.mesh) {
  81110. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  81111. }
  81112. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  81113. var origin = m.getTranslation();
  81114. var forward = new BABYLON.Vector3(0, 0, -1);
  81115. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  81116. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  81117. return new BABYLON.Ray(origin, direction, length);
  81118. };
  81119. /**
  81120. * Name of the child mesh that can be used to cast a ray from the controller
  81121. */
  81122. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  81123. return PoseEnabledController;
  81124. }(BABYLON.Gamepad));
  81125. BABYLON.PoseEnabledController = PoseEnabledController;
  81126. })(BABYLON || (BABYLON = {}));
  81127. //# sourceMappingURL=babylon.poseEnabledController.js.map
  81128. var BABYLON;
  81129. (function (BABYLON) {
  81130. /**
  81131. * Defines the WebVRController object that represents controllers tracked in 3D space
  81132. */
  81133. var WebVRController = /** @class */ (function (_super) {
  81134. __extends(WebVRController, _super);
  81135. /**
  81136. * Creates a new WebVRController from a gamepad
  81137. * @param vrGamepad the gamepad that the WebVRController should be created from
  81138. */
  81139. function WebVRController(vrGamepad) {
  81140. var _this = _super.call(this, vrGamepad) || this;
  81141. // Observables
  81142. /**
  81143. * Fired when the trigger state has changed
  81144. */
  81145. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  81146. /**
  81147. * Fired when the main button state has changed
  81148. */
  81149. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  81150. /**
  81151. * Fired when the secondary button state has changed
  81152. */
  81153. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  81154. /**
  81155. * Fired when the pad state has changed
  81156. */
  81157. _this.onPadStateChangedObservable = new BABYLON.Observable();
  81158. /**
  81159. * Fired when controllers stick values have changed
  81160. */
  81161. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  81162. /**
  81163. * X and Y axis corrisponding to the controllers joystick
  81164. */
  81165. _this.pad = { x: 0, y: 0 };
  81166. // avoid GC, store state in a tmp object
  81167. _this._changes = {
  81168. pressChanged: false,
  81169. touchChanged: false,
  81170. valueChanged: false,
  81171. changed: false
  81172. };
  81173. _this._buttons = new Array(vrGamepad.buttons.length);
  81174. _this.hand = vrGamepad.hand;
  81175. return _this;
  81176. }
  81177. /**
  81178. * Fired when a controller button's state has changed
  81179. * @param callback the callback containing the button that was modified
  81180. */
  81181. WebVRController.prototype.onButtonStateChange = function (callback) {
  81182. this._onButtonStateChange = callback;
  81183. };
  81184. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  81185. /**
  81186. * The default controller model for the controller
  81187. */
  81188. get: function () {
  81189. return this._defaultModel;
  81190. },
  81191. enumerable: true,
  81192. configurable: true
  81193. });
  81194. /**
  81195. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  81196. */
  81197. WebVRController.prototype.update = function () {
  81198. _super.prototype.update.call(this);
  81199. for (var index = 0; index < this._buttons.length; index++) {
  81200. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  81201. }
  81202. ;
  81203. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  81204. this.pad.x = this.leftStick.x;
  81205. this.pad.y = this.leftStick.y;
  81206. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  81207. }
  81208. };
  81209. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  81210. if (!newState) {
  81211. newState = {
  81212. pressed: false,
  81213. touched: false,
  81214. value: 0
  81215. };
  81216. }
  81217. if (!currentState) {
  81218. this._buttons[buttonIndex] = {
  81219. pressed: newState.pressed,
  81220. touched: newState.touched,
  81221. value: newState.value
  81222. };
  81223. return;
  81224. }
  81225. this._checkChanges(newState, currentState);
  81226. if (this._changes.changed) {
  81227. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  81228. this._handleButtonChange(buttonIndex, newState, this._changes);
  81229. }
  81230. this._buttons[buttonIndex].pressed = newState.pressed;
  81231. this._buttons[buttonIndex].touched = newState.touched;
  81232. // oculus triggers are never 0, thou not touched.
  81233. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  81234. };
  81235. WebVRController.prototype._checkChanges = function (newState, currentState) {
  81236. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  81237. this._changes.touchChanged = newState.touched !== currentState.touched;
  81238. this._changes.valueChanged = newState.value !== currentState.value;
  81239. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  81240. return this._changes;
  81241. };
  81242. /**
  81243. * Disposes of th webVRCOntroller
  81244. */
  81245. WebVRController.prototype.dispose = function () {
  81246. _super.prototype.dispose.call(this);
  81247. this.onTriggerStateChangedObservable.clear();
  81248. this.onMainButtonStateChangedObservable.clear();
  81249. this.onSecondaryButtonStateChangedObservable.clear();
  81250. this.onPadStateChangedObservable.clear();
  81251. this.onPadValuesChangedObservable.clear();
  81252. };
  81253. return WebVRController;
  81254. }(BABYLON.PoseEnabledController));
  81255. BABYLON.WebVRController = WebVRController;
  81256. })(BABYLON || (BABYLON = {}));
  81257. //# sourceMappingURL=babylon.webVRController.js.map
  81258. var BABYLON;
  81259. (function (BABYLON) {
  81260. /**
  81261. * Oculus Touch Controller
  81262. */
  81263. var OculusTouchController = /** @class */ (function (_super) {
  81264. __extends(OculusTouchController, _super);
  81265. /**
  81266. * Creates a new OculusTouchController from a gamepad
  81267. * @param vrGamepad the gamepad that the controller should be created from
  81268. */
  81269. function OculusTouchController(vrGamepad) {
  81270. var _this = _super.call(this, vrGamepad) || this;
  81271. /**
  81272. * Fired when the secondary trigger on this controller is modified
  81273. */
  81274. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  81275. /**
  81276. * Fired when the thumb rest on this controller is modified
  81277. */
  81278. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  81279. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  81280. return _this;
  81281. }
  81282. /**
  81283. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81284. * @param scene scene in which to add meshes
  81285. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81286. */
  81287. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81288. var _this = this;
  81289. var meshName;
  81290. // Hand
  81291. if (this.hand === 'left') {
  81292. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  81293. }
  81294. else { // Right is the default if no hand is specified
  81295. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  81296. }
  81297. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  81298. /*
  81299. Parent Mesh name: oculus_touch_left
  81300. - body
  81301. - trigger
  81302. - thumbstick
  81303. - grip
  81304. - button_y
  81305. - button_x
  81306. - button_enter
  81307. */
  81308. _this._defaultModel = newMeshes[1];
  81309. _this.attachToMesh(_this._defaultModel);
  81310. if (meshLoaded) {
  81311. meshLoaded(_this._defaultModel);
  81312. }
  81313. });
  81314. };
  81315. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  81316. /**
  81317. * Fired when the A button on this controller is modified
  81318. */
  81319. get: function () {
  81320. if (this.hand === 'right') {
  81321. return this.onMainButtonStateChangedObservable;
  81322. }
  81323. else {
  81324. throw new Error('No A button on left hand');
  81325. }
  81326. },
  81327. enumerable: true,
  81328. configurable: true
  81329. });
  81330. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  81331. /**
  81332. * Fired when the B button on this controller is modified
  81333. */
  81334. get: function () {
  81335. if (this.hand === 'right') {
  81336. return this.onSecondaryButtonStateChangedObservable;
  81337. }
  81338. else {
  81339. throw new Error('No B button on left hand');
  81340. }
  81341. },
  81342. enumerable: true,
  81343. configurable: true
  81344. });
  81345. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  81346. /**
  81347. * Fired when the X button on this controller is modified
  81348. */
  81349. get: function () {
  81350. if (this.hand === 'left') {
  81351. return this.onMainButtonStateChangedObservable;
  81352. }
  81353. else {
  81354. throw new Error('No X button on right hand');
  81355. }
  81356. },
  81357. enumerable: true,
  81358. configurable: true
  81359. });
  81360. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  81361. /**
  81362. * Fired when the Y button on this controller is modified
  81363. */
  81364. get: function () {
  81365. if (this.hand === 'left') {
  81366. return this.onSecondaryButtonStateChangedObservable;
  81367. }
  81368. else {
  81369. throw new Error('No Y button on right hand');
  81370. }
  81371. },
  81372. enumerable: true,
  81373. configurable: true
  81374. });
  81375. /**
  81376. * Called once for each button that changed state since the last frame
  81377. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  81378. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  81379. * 2) secondary trigger (same)
  81380. * 3) A (right) X (left), touch, pressed = value
  81381. * 4) B / Y
  81382. * 5) thumb rest
  81383. * @param buttonIdx Which button index changed
  81384. * @param state New state of the button
  81385. * @param changes Which properties on the state changed since last frame
  81386. */
  81387. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81388. var notifyObject = state; //{ state: state, changes: changes };
  81389. var triggerDirection = this.hand === 'right' ? -1 : 1;
  81390. switch (buttonIdx) {
  81391. case 0:
  81392. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81393. return;
  81394. case 1: // index trigger
  81395. if (this._defaultModel) {
  81396. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  81397. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  81398. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  81399. }
  81400. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81401. return;
  81402. case 2: // secondary trigger
  81403. if (this._defaultModel) {
  81404. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  81405. }
  81406. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  81407. return;
  81408. case 3:
  81409. if (this._defaultModel) {
  81410. if (notifyObject.pressed) {
  81411. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  81412. }
  81413. else {
  81414. (this._defaultModel.getChildren()[1]).position.y = 0;
  81415. }
  81416. }
  81417. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81418. return;
  81419. case 4:
  81420. if (this._defaultModel) {
  81421. if (notifyObject.pressed) {
  81422. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81423. }
  81424. else {
  81425. (this._defaultModel.getChildren()[2]).position.y = 0;
  81426. }
  81427. }
  81428. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81429. return;
  81430. case 5:
  81431. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  81432. return;
  81433. }
  81434. };
  81435. /**
  81436. * Base Url for the controller model.
  81437. */
  81438. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  81439. /**
  81440. * File name for the left controller model.
  81441. */
  81442. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  81443. /**
  81444. * File name for the right controller model.
  81445. */
  81446. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  81447. return OculusTouchController;
  81448. }(BABYLON.WebVRController));
  81449. BABYLON.OculusTouchController = OculusTouchController;
  81450. })(BABYLON || (BABYLON = {}));
  81451. //# sourceMappingURL=babylon.oculusTouchController.js.map
  81452. var BABYLON;
  81453. (function (BABYLON) {
  81454. /**
  81455. * Vive Controller
  81456. */
  81457. var ViveController = /** @class */ (function (_super) {
  81458. __extends(ViveController, _super);
  81459. /**
  81460. * Creates a new ViveController from a gamepad
  81461. * @param vrGamepad the gamepad that the controller should be created from
  81462. */
  81463. function ViveController(vrGamepad) {
  81464. var _this = _super.call(this, vrGamepad) || this;
  81465. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  81466. _this._invertLeftStickY = true;
  81467. return _this;
  81468. }
  81469. /**
  81470. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81471. * @param scene scene in which to add meshes
  81472. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81473. */
  81474. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81475. var _this = this;
  81476. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  81477. /*
  81478. Parent Mesh name: ViveWand
  81479. - body
  81480. - r_gripper
  81481. - l_gripper
  81482. - menu_button
  81483. - system_button
  81484. - trackpad
  81485. - trigger
  81486. - LED
  81487. */
  81488. _this._defaultModel = newMeshes[1];
  81489. _this.attachToMesh(_this._defaultModel);
  81490. if (meshLoaded) {
  81491. meshLoaded(_this._defaultModel);
  81492. }
  81493. });
  81494. };
  81495. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  81496. /**
  81497. * Fired when the left button on this controller is modified
  81498. */
  81499. get: function () {
  81500. return this.onMainButtonStateChangedObservable;
  81501. },
  81502. enumerable: true,
  81503. configurable: true
  81504. });
  81505. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  81506. /**
  81507. * Fired when the right button on this controller is modified
  81508. */
  81509. get: function () {
  81510. return this.onMainButtonStateChangedObservable;
  81511. },
  81512. enumerable: true,
  81513. configurable: true
  81514. });
  81515. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  81516. /**
  81517. * Fired when the menu button on this controller is modified
  81518. */
  81519. get: function () {
  81520. return this.onSecondaryButtonStateChangedObservable;
  81521. },
  81522. enumerable: true,
  81523. configurable: true
  81524. });
  81525. /**
  81526. * Called once for each button that changed state since the last frame
  81527. * Vive mapping:
  81528. * 0: touchpad
  81529. * 1: trigger
  81530. * 2: left AND right buttons
  81531. * 3: menu button
  81532. * @param buttonIdx Which button index changed
  81533. * @param state New state of the button
  81534. * @param changes Which properties on the state changed since last frame
  81535. */
  81536. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81537. var notifyObject = state; //{ state: state, changes: changes };
  81538. switch (buttonIdx) {
  81539. case 0:
  81540. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  81541. return;
  81542. case 1: // index trigger
  81543. if (this._defaultModel) {
  81544. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  81545. }
  81546. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  81547. return;
  81548. case 2: // left AND right button
  81549. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  81550. return;
  81551. case 3:
  81552. if (this._defaultModel) {
  81553. if (notifyObject.pressed) {
  81554. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  81555. }
  81556. else {
  81557. (this._defaultModel.getChildren()[2]).position.y = 0;
  81558. }
  81559. }
  81560. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  81561. return;
  81562. }
  81563. };
  81564. /**
  81565. * Base Url for the controller model.
  81566. */
  81567. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  81568. /**
  81569. * File name for the controller model.
  81570. */
  81571. ViveController.MODEL_FILENAME = 'wand.babylon';
  81572. return ViveController;
  81573. }(BABYLON.WebVRController));
  81574. BABYLON.ViveController = ViveController;
  81575. })(BABYLON || (BABYLON = {}));
  81576. //# sourceMappingURL=babylon.viveController.js.map
  81577. var BABYLON;
  81578. (function (BABYLON) {
  81579. /**
  81580. * Generic Controller
  81581. */
  81582. var GenericController = /** @class */ (function (_super) {
  81583. __extends(GenericController, _super);
  81584. /**
  81585. * Creates a new GenericController from a gamepad
  81586. * @param vrGamepad the gamepad that the controller should be created from
  81587. */
  81588. function GenericController(vrGamepad) {
  81589. return _super.call(this, vrGamepad) || this;
  81590. }
  81591. /**
  81592. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81593. * @param scene scene in which to add meshes
  81594. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81595. */
  81596. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  81597. var _this = this;
  81598. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  81599. _this._defaultModel = newMeshes[1];
  81600. _this.attachToMesh(_this._defaultModel);
  81601. if (meshLoaded) {
  81602. meshLoaded(_this._defaultModel);
  81603. }
  81604. });
  81605. };
  81606. /**
  81607. * Called once for each button that changed state since the last frame
  81608. * @param buttonIdx Which button index changed
  81609. * @param state New state of the button
  81610. * @param changes Which properties on the state changed since last frame
  81611. */
  81612. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81613. console.log("Button id: " + buttonIdx + "state: ");
  81614. console.dir(state);
  81615. };
  81616. /**
  81617. * Base Url for the controller model.
  81618. */
  81619. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  81620. /**
  81621. * File name for the controller model.
  81622. */
  81623. GenericController.MODEL_FILENAME = 'generic.babylon';
  81624. return GenericController;
  81625. }(BABYLON.WebVRController));
  81626. BABYLON.GenericController = GenericController;
  81627. })(BABYLON || (BABYLON = {}));
  81628. //# sourceMappingURL=babylon.genericController.js.map
  81629. var BABYLON;
  81630. (function (BABYLON) {
  81631. /**
  81632. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  81633. */
  81634. var LoadedMeshInfo = /** @class */ (function () {
  81635. function LoadedMeshInfo() {
  81636. /**
  81637. * Map of the button meshes contained in the controller
  81638. */
  81639. this.buttonMeshes = {};
  81640. /**
  81641. * Map of the axis meshes contained in the controller
  81642. */
  81643. this.axisMeshes = {};
  81644. }
  81645. return LoadedMeshInfo;
  81646. }());
  81647. /**
  81648. * Defines the WindowsMotionController object that the state of the windows motion controller
  81649. */
  81650. var WindowsMotionController = /** @class */ (function (_super) {
  81651. __extends(WindowsMotionController, _super);
  81652. /**
  81653. * Creates a new WindowsMotionController from a gamepad
  81654. * @param vrGamepad the gamepad that the controller should be created from
  81655. */
  81656. function WindowsMotionController(vrGamepad) {
  81657. var _this = _super.call(this, vrGamepad) || this;
  81658. _this._mapping = {
  81659. // Semantic button names
  81660. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  81661. // A mapping of the button name to glTF model node name
  81662. // that should be transformed by button value.
  81663. buttonMeshNames: {
  81664. 'trigger': 'SELECT',
  81665. 'menu': 'MENU',
  81666. 'grip': 'GRASP',
  81667. 'thumbstick': 'THUMBSTICK_PRESS',
  81668. 'trackpad': 'TOUCHPAD_PRESS'
  81669. },
  81670. // This mapping is used to translate from the Motion Controller to Babylon semantics
  81671. buttonObservableNames: {
  81672. 'trigger': 'onTriggerStateChangedObservable',
  81673. 'menu': 'onSecondaryButtonStateChangedObservable',
  81674. 'grip': 'onMainButtonStateChangedObservable',
  81675. 'thumbstick': 'onPadStateChangedObservable',
  81676. 'trackpad': 'onTrackpadChangedObservable'
  81677. },
  81678. // A mapping of the axis name to glTF model node name
  81679. // that should be transformed by axis value.
  81680. // This array mirrors the browserGamepad.axes array, such that
  81681. // the mesh corresponding to axis 0 is in this array index 0.
  81682. axisMeshNames: [
  81683. 'THUMBSTICK_X',
  81684. 'THUMBSTICK_Y',
  81685. 'TOUCHPAD_TOUCH_X',
  81686. 'TOUCHPAD_TOUCH_Y'
  81687. ],
  81688. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  81689. };
  81690. /**
  81691. * Fired when the trackpad on this controller is clicked
  81692. */
  81693. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  81694. /**
  81695. * Fired when the trackpad on this controller is modified
  81696. */
  81697. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  81698. /**
  81699. * The current x and y values of this controller's trackpad
  81700. */
  81701. _this.trackpad = { x: 0, y: 0 };
  81702. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  81703. _this._loadedMeshInfo = null;
  81704. return _this;
  81705. }
  81706. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  81707. /**
  81708. * Fired when the trigger on this controller is modified
  81709. */
  81710. get: function () {
  81711. return this.onTriggerStateChangedObservable;
  81712. },
  81713. enumerable: true,
  81714. configurable: true
  81715. });
  81716. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  81717. /**
  81718. * Fired when the menu button on this controller is modified
  81719. */
  81720. get: function () {
  81721. return this.onSecondaryButtonStateChangedObservable;
  81722. },
  81723. enumerable: true,
  81724. configurable: true
  81725. });
  81726. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  81727. /**
  81728. * Fired when the grip button on this controller is modified
  81729. */
  81730. get: function () {
  81731. return this.onMainButtonStateChangedObservable;
  81732. },
  81733. enumerable: true,
  81734. configurable: true
  81735. });
  81736. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  81737. /**
  81738. * Fired when the thumbstick button on this controller is modified
  81739. */
  81740. get: function () {
  81741. return this.onPadStateChangedObservable;
  81742. },
  81743. enumerable: true,
  81744. configurable: true
  81745. });
  81746. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  81747. /**
  81748. * Fired when the touchpad button on this controller is modified
  81749. */
  81750. get: function () {
  81751. return this.onTrackpadChangedObservable;
  81752. },
  81753. enumerable: true,
  81754. configurable: true
  81755. });
  81756. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  81757. /**
  81758. * Fired when the touchpad values on this controller are modified
  81759. */
  81760. get: function () {
  81761. return this.onTrackpadValuesChangedObservable;
  81762. },
  81763. enumerable: true,
  81764. configurable: true
  81765. });
  81766. WindowsMotionController.prototype._updateTrackpad = function () {
  81767. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  81768. this.trackpad.x = this.browserGamepad["axes"][2];
  81769. this.trackpad.y = this.browserGamepad["axes"][3];
  81770. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  81771. }
  81772. };
  81773. /**
  81774. * Called once per frame by the engine.
  81775. */
  81776. WindowsMotionController.prototype.update = function () {
  81777. _super.prototype.update.call(this);
  81778. if (this.browserGamepad.axes) {
  81779. this._updateTrackpad();
  81780. // Only need to animate axes if there is a loaded mesh
  81781. if (this._loadedMeshInfo) {
  81782. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  81783. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  81784. }
  81785. }
  81786. }
  81787. };
  81788. /**
  81789. * Called once for each button that changed state since the last frame
  81790. * @param buttonIdx Which button index changed
  81791. * @param state New state of the button
  81792. * @param changes Which properties on the state changed since last frame
  81793. */
  81794. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  81795. var buttonName = this._mapping.buttons[buttonIdx];
  81796. if (!buttonName) {
  81797. return;
  81798. }
  81799. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  81800. this._updateTrackpad();
  81801. // Only emit events for buttons that we know how to map from index to name
  81802. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  81803. if (observable) {
  81804. observable.notifyObservers(state);
  81805. }
  81806. this._lerpButtonTransform(buttonName, state.value);
  81807. };
  81808. /**
  81809. * Moves the buttons on the controller mesh based on their current state
  81810. * @param buttonName the name of the button to move
  81811. * @param buttonValue the value of the button which determines the buttons new position
  81812. */
  81813. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  81814. // If there is no loaded mesh, there is nothing to transform.
  81815. if (!this._loadedMeshInfo) {
  81816. return;
  81817. }
  81818. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  81819. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  81820. return;
  81821. }
  81822. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  81823. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  81824. };
  81825. /**
  81826. * Moves the axis on the controller mesh based on its current state
  81827. * @param axis the index of the axis
  81828. * @param axisValue the value of the axis which determines the meshes new position
  81829. * @hidden
  81830. */
  81831. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  81832. if (!this._loadedMeshInfo) {
  81833. return;
  81834. }
  81835. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  81836. if (!meshInfo) {
  81837. return;
  81838. }
  81839. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  81840. return;
  81841. }
  81842. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  81843. var lerpValue = axisValue * 0.5 + 0.5;
  81844. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  81845. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  81846. };
  81847. /**
  81848. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  81849. * @param scene scene in which to add meshes
  81850. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  81851. */
  81852. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  81853. var _this = this;
  81854. if (forceDefault === void 0) { forceDefault = false; }
  81855. var path;
  81856. var filename;
  81857. // Checking if GLB loader is present
  81858. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  81859. // Determine the device specific folder based on the ID suffix
  81860. var device = 'default';
  81861. if (this.id && !forceDefault) {
  81862. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  81863. device = ((match && match[0]) || device);
  81864. }
  81865. // Hand
  81866. if (this.hand === 'left') {
  81867. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  81868. }
  81869. else { // Right is the default if no hand is specified
  81870. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  81871. }
  81872. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  81873. }
  81874. else {
  81875. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  81876. path = BABYLON.GenericController.MODEL_BASE_URL;
  81877. filename = BABYLON.GenericController.MODEL_FILENAME;
  81878. }
  81879. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  81880. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  81881. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  81882. if (!_this._loadedMeshInfo) {
  81883. return;
  81884. }
  81885. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  81886. _this.attachToMesh(_this._defaultModel);
  81887. if (meshLoaded) {
  81888. meshLoaded(_this._defaultModel);
  81889. }
  81890. }, null, function (scene, message) {
  81891. BABYLON.Tools.Log(message);
  81892. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  81893. if (!forceDefault) {
  81894. _this.initControllerMesh(scene, meshLoaded, true);
  81895. }
  81896. });
  81897. };
  81898. /**
  81899. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  81900. * can be transformed by button presses and axes values, based on this._mapping.
  81901. *
  81902. * @param scene scene in which the meshes exist
  81903. * @param meshes list of meshes that make up the controller model to process
  81904. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  81905. */
  81906. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  81907. var loadedMeshInfo = null;
  81908. // Create a new mesh to contain the glTF hierarchy
  81909. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  81910. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  81911. var childMesh = null;
  81912. for (var i = 0; i < meshes.length; i++) {
  81913. var mesh = meshes[i];
  81914. if (!mesh.parent) {
  81915. // Exclude controller meshes from picking results
  81916. mesh.isPickable = false;
  81917. // Handle root node, attach to the new parentMesh
  81918. childMesh = mesh;
  81919. break;
  81920. }
  81921. }
  81922. if (childMesh) {
  81923. childMesh.setParent(parentMesh);
  81924. // Create our mesh info. Note that this method will always return non-null.
  81925. loadedMeshInfo = this.createMeshInfo(parentMesh);
  81926. }
  81927. else {
  81928. BABYLON.Tools.Warn('Could not find root node in model file.');
  81929. }
  81930. return loadedMeshInfo;
  81931. };
  81932. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  81933. var loadedMeshInfo = new LoadedMeshInfo();
  81934. var i;
  81935. loadedMeshInfo.rootNode = rootNode;
  81936. // Reset the caches
  81937. loadedMeshInfo.buttonMeshes = {};
  81938. loadedMeshInfo.axisMeshes = {};
  81939. // Button Meshes
  81940. for (i = 0; i < this._mapping.buttons.length; i++) {
  81941. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  81942. if (!buttonMeshName) {
  81943. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  81944. continue;
  81945. }
  81946. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  81947. if (!buttonMesh) {
  81948. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  81949. continue;
  81950. }
  81951. var buttonMeshInfo = {
  81952. index: i,
  81953. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  81954. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  81955. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  81956. };
  81957. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  81958. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  81959. }
  81960. else {
  81961. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  81962. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  81963. '(VALUE: ' + !!buttonMeshInfo.value +
  81964. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  81965. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  81966. ')');
  81967. }
  81968. }
  81969. // Axis Meshes
  81970. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  81971. var axisMeshName = this._mapping.axisMeshNames[i];
  81972. if (!axisMeshName) {
  81973. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  81974. continue;
  81975. }
  81976. var axisMesh = getChildByName(rootNode, axisMeshName);
  81977. if (!axisMesh) {
  81978. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  81979. continue;
  81980. }
  81981. var axisMeshInfo = {
  81982. index: i,
  81983. value: getImmediateChildByName(axisMesh, 'VALUE'),
  81984. min: getImmediateChildByName(axisMesh, 'MIN'),
  81985. max: getImmediateChildByName(axisMesh, 'MAX')
  81986. };
  81987. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  81988. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  81989. }
  81990. else {
  81991. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  81992. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  81993. '(VALUE: ' + !!axisMeshInfo.value +
  81994. ', MIN: ' + !!axisMeshInfo.min +
  81995. ', MAX:' + !!axisMeshInfo.max +
  81996. ')');
  81997. }
  81998. }
  81999. // Pointing Ray
  82000. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  82001. if (!loadedMeshInfo.pointingPoseNode) {
  82002. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  82003. }
  82004. else {
  82005. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  82006. }
  82007. return loadedMeshInfo;
  82008. // Look through all children recursively. This will return null if no mesh exists with the given name.
  82009. function getChildByName(node, name) {
  82010. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  82011. }
  82012. // Look through only immediate children. This will return null if no mesh exists with the given name.
  82013. function getImmediateChildByName(node, name) {
  82014. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  82015. }
  82016. };
  82017. /**
  82018. * Gets the ray of the controller in the direction the controller is pointing
  82019. * @param length the length the resulting ray should be
  82020. * @returns a ray in the direction the controller is pointing
  82021. */
  82022. WindowsMotionController.prototype.getForwardRay = function (length) {
  82023. if (length === void 0) { length = 100; }
  82024. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  82025. return _super.prototype.getForwardRay.call(this, length);
  82026. }
  82027. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  82028. var origin = m.getTranslation();
  82029. var forward = new BABYLON.Vector3(0, 0, -1);
  82030. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  82031. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  82032. return new BABYLON.Ray(origin, direction, length);
  82033. };
  82034. /**
  82035. * Disposes of the controller
  82036. */
  82037. WindowsMotionController.prototype.dispose = function () {
  82038. _super.prototype.dispose.call(this);
  82039. this.onTrackpadChangedObservable.clear();
  82040. };
  82041. /**
  82042. * The base url used to load the left and right controller models
  82043. */
  82044. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  82045. /**
  82046. * The name of the left controller model file
  82047. */
  82048. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  82049. /**
  82050. * The name of the right controller model file
  82051. */
  82052. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  82053. /**
  82054. * The controller name prefix for this controller type
  82055. */
  82056. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  82057. /**
  82058. * The controller id pattern for this controller type
  82059. */
  82060. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  82061. return WindowsMotionController;
  82062. }(BABYLON.WebVRController));
  82063. BABYLON.WindowsMotionController = WindowsMotionController;
  82064. })(BABYLON || (BABYLON = {}));
  82065. //# sourceMappingURL=babylon.windowsMotionController.js.map
  82066. var BABYLON;
  82067. (function (BABYLON) {
  82068. /**
  82069. * Gear VR Controller
  82070. */
  82071. var GearVRController = /** @class */ (function (_super) {
  82072. __extends(GearVRController, _super);
  82073. /**
  82074. * Creates a new GearVRController from a gamepad
  82075. * @param vrGamepad the gamepad that the controller should be created from
  82076. */
  82077. function GearVRController(vrGamepad) {
  82078. var _this = _super.call(this, vrGamepad) || this;
  82079. _this._buttonIndexToObservableNameMap = [
  82080. 'onTrackpadChangedObservable',
  82081. 'onTriggerStateChangedObservable' // Trigger
  82082. ];
  82083. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  82084. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  82085. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.25);
  82086. _this._disableTrackPosition(_this._calculatedPosition);
  82087. return _this;
  82088. }
  82089. /**
  82090. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82091. * @param scene scene in which to add meshes
  82092. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82093. */
  82094. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82095. var _this = this;
  82096. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  82097. // Offset the controller so it will rotate around the users wrist
  82098. var mesh = new BABYLON.Mesh("", scene);
  82099. newMeshes[1].parent = mesh;
  82100. newMeshes[1].position.z = -0.15;
  82101. _this._defaultModel = mesh;
  82102. _this.attachToMesh(_this._defaultModel);
  82103. if (meshLoaded) {
  82104. meshLoaded(_this._defaultModel);
  82105. }
  82106. });
  82107. };
  82108. /**
  82109. * Called once for each button that changed state since the last frame
  82110. * @param buttonIdx Which button index changed
  82111. * @param state New state of the button
  82112. * @param changes Which properties on the state changed since last frame
  82113. */
  82114. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82115. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  82116. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  82117. // Only emit events for buttons that we know how to map from index to observable
  82118. var observable = this[observableName];
  82119. if (observable) {
  82120. observable.notifyObservers(state);
  82121. }
  82122. }
  82123. };
  82124. /**
  82125. * Base Url for the controller model.
  82126. */
  82127. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82128. /**
  82129. * File name for the controller model.
  82130. */
  82131. GearVRController.MODEL_FILENAME = 'generic.babylon';
  82132. /**
  82133. * Gamepad Id prefix used to identify this controller.
  82134. */
  82135. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  82136. return GearVRController;
  82137. }(BABYLON.WebVRController));
  82138. BABYLON.GearVRController = GearVRController;
  82139. })(BABYLON || (BABYLON = {}));
  82140. //# sourceMappingURL=babylon.gearVRController.js.map
  82141. var BABYLON;
  82142. (function (BABYLON) {
  82143. /**
  82144. * Google Daydream controller
  82145. */
  82146. var DaydreamController = /** @class */ (function (_super) {
  82147. __extends(DaydreamController, _super);
  82148. /**
  82149. * Creates a new DaydreamController from a gamepad
  82150. * @param vrGamepad the gamepad that the controller should be created from
  82151. */
  82152. function DaydreamController(vrGamepad) {
  82153. var _this = _super.call(this, vrGamepad) || this;
  82154. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  82155. return _this;
  82156. }
  82157. /**
  82158. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  82159. * @param scene scene in which to add meshes
  82160. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  82161. */
  82162. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  82163. var _this = this;
  82164. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  82165. _this._defaultModel = newMeshes[1];
  82166. _this.attachToMesh(_this._defaultModel);
  82167. if (meshLoaded) {
  82168. meshLoaded(_this._defaultModel);
  82169. }
  82170. });
  82171. };
  82172. /**
  82173. * Called once for each button that changed state since the last frame
  82174. * @param buttonIdx Which button index changed
  82175. * @param state New state of the button
  82176. * @param changes Which properties on the state changed since last frame
  82177. */
  82178. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  82179. // Daydream controller only has 1 GamepadButton (on the trackpad).
  82180. if (buttonIdx === 0) {
  82181. var observable = this.onTriggerStateChangedObservable;
  82182. if (observable) {
  82183. observable.notifyObservers(state);
  82184. }
  82185. }
  82186. else {
  82187. // If the app or home buttons are ever made available
  82188. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  82189. }
  82190. };
  82191. /**
  82192. * Base Url for the controller model.
  82193. */
  82194. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  82195. /**
  82196. * File name for the controller model.
  82197. */
  82198. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  82199. /**
  82200. * Gamepad Id prefix used to identify Daydream Controller.
  82201. */
  82202. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  82203. return DaydreamController;
  82204. }(BABYLON.WebVRController));
  82205. BABYLON.DaydreamController = DaydreamController;
  82206. })(BABYLON || (BABYLON = {}));
  82207. //# sourceMappingURL=babylon.daydreamController.js.map
  82208. var BABYLON;
  82209. (function (BABYLON) {
  82210. Object.defineProperty(BABYLON.Scene.prototype, "gamepadManager", {
  82211. get: function () {
  82212. if (!this._gamepadManager) {
  82213. this._gamepadManager = new BABYLON.GamepadManager(this);
  82214. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_GAMEPAD);
  82215. if (!component) {
  82216. component = new GamepadSystemSceneComponent(this);
  82217. this._addComponent(component);
  82218. }
  82219. }
  82220. return this._gamepadManager;
  82221. },
  82222. enumerable: true,
  82223. configurable: true
  82224. });
  82225. /**
  82226. * Adds a gamepad to the free camera inputs manager
  82227. */
  82228. BABYLON.FreeCameraInputsManager.prototype.addGamepad = function () {
  82229. this.add(new BABYLON.FreeCameraGamepadInput());
  82230. return this;
  82231. };
  82232. /**
  82233. * Adds a gamepad to the arc rotate camera inputs manager
  82234. */
  82235. BABYLON.ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  82236. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  82237. return this;
  82238. };
  82239. /**
  82240. * Defines the gamepad scene component responsible to manage gamepads in a given scene
  82241. */
  82242. var GamepadSystemSceneComponent = /** @class */ (function () {
  82243. /**
  82244. * Creates a new instance of the component for the given scene
  82245. * @param scene Defines the scene to register the component in
  82246. */
  82247. function GamepadSystemSceneComponent(scene) {
  82248. /**
  82249. * The component name helpfull to identify the component in the list of scene components.
  82250. */
  82251. this.name = BABYLON.SceneComponentConstants.NAME_GAMEPAD;
  82252. this.scene = scene;
  82253. }
  82254. /**
  82255. * Registers the component in a given scene
  82256. */
  82257. GamepadSystemSceneComponent.prototype.register = function () {
  82258. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_GAMEPAD, this, this._beforeCameraUpdate);
  82259. };
  82260. /**
  82261. * Rebuilds the elements related to this component in case of
  82262. * context lost for instance.
  82263. */
  82264. GamepadSystemSceneComponent.prototype.rebuild = function () {
  82265. // Nothing to do for gamepads
  82266. };
  82267. /**
  82268. * Disposes the component and the associated ressources
  82269. */
  82270. GamepadSystemSceneComponent.prototype.dispose = function () {
  82271. var gamepadManager = this.scene._gamepadManager;
  82272. if (gamepadManager) {
  82273. gamepadManager.dispose();
  82274. this.scene._gamepadManager = null;
  82275. }
  82276. };
  82277. GamepadSystemSceneComponent.prototype._beforeCameraUpdate = function () {
  82278. var gamepadManager = this.scene._gamepadManager;
  82279. if (gamepadManager && gamepadManager._isMonitoring) {
  82280. gamepadManager._checkGamepadsStatus();
  82281. }
  82282. };
  82283. return GamepadSystemSceneComponent;
  82284. }());
  82285. BABYLON.GamepadSystemSceneComponent = GamepadSystemSceneComponent;
  82286. })(BABYLON || (BABYLON = {}));
  82287. //# sourceMappingURL=babylon.gamepadSceneComponent.js.map
  82288. var BABYLON;
  82289. (function (BABYLON) {
  82290. BABYLON.Node.AddNodeConstructor("FollowCamera", function (name, scene) {
  82291. return function () { return new FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  82292. });
  82293. BABYLON.Node.AddNodeConstructor("ArcFollowCamera", function (name, scene) {
  82294. return function () { return new ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  82295. });
  82296. /**
  82297. * A follow camera takes a mesh as a target and follows it as it moves. Both a free camera version followCamera and
  82298. * an arc rotate version arcFollowCamera are available.
  82299. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82300. */
  82301. var FollowCamera = /** @class */ (function (_super) {
  82302. __extends(FollowCamera, _super);
  82303. /**
  82304. * Instantiates the follow camera.
  82305. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82306. * @param name Define the name of the camera in the scene
  82307. * @param position Define the position of the camera
  82308. * @param scene Define the scene the camera belong to
  82309. * @param lockedTarget Define the target of the camera
  82310. */
  82311. function FollowCamera(name, position, scene, lockedTarget) {
  82312. if (lockedTarget === void 0) { lockedTarget = null; }
  82313. var _this = _super.call(this, name, position, scene) || this;
  82314. /**
  82315. * Distance the follow camera should follow an object at
  82316. */
  82317. _this.radius = 12;
  82318. /**
  82319. * Define a rotation offset between the camera and the object it follows
  82320. */
  82321. _this.rotationOffset = 0;
  82322. /**
  82323. * Define a height offset between the camera and the object it follows.
  82324. * It can help following an object from the top (like a car chaing a plane)
  82325. */
  82326. _this.heightOffset = 4;
  82327. /**
  82328. * Define how fast the camera can accelerate to follow it s target.
  82329. */
  82330. _this.cameraAcceleration = 0.05;
  82331. /**
  82332. * Define the speed limit of the camera following an object.
  82333. */
  82334. _this.maxCameraSpeed = 20;
  82335. _this.lockedTarget = lockedTarget;
  82336. return _this;
  82337. }
  82338. FollowCamera.prototype._follow = function (cameraTarget) {
  82339. if (!cameraTarget)
  82340. return;
  82341. var yRotation;
  82342. if (cameraTarget.rotationQuaternion) {
  82343. var rotMatrix = new BABYLON.Matrix();
  82344. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  82345. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  82346. }
  82347. else {
  82348. yRotation = cameraTarget.rotation.y;
  82349. }
  82350. var radians = BABYLON.Tools.ToRadians(this.rotationOffset) + yRotation;
  82351. var targetPosition = cameraTarget.getAbsolutePosition();
  82352. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  82353. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  82354. var dx = targetX - this.position.x;
  82355. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  82356. var dz = (targetZ) - this.position.z;
  82357. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  82358. var vy = dy * this.cameraAcceleration;
  82359. var vz = dz * this.cameraAcceleration * 2;
  82360. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  82361. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82362. }
  82363. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  82364. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82365. }
  82366. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  82367. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  82368. }
  82369. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  82370. this.setTarget(targetPosition);
  82371. };
  82372. /** @hidden */
  82373. FollowCamera.prototype._checkInputs = function () {
  82374. _super.prototype._checkInputs.call(this);
  82375. if (this.lockedTarget) {
  82376. this._follow(this.lockedTarget);
  82377. }
  82378. };
  82379. /**
  82380. * Gets the camera class name.
  82381. * @returns the class name
  82382. */
  82383. FollowCamera.prototype.getClassName = function () {
  82384. return "FollowCamera";
  82385. };
  82386. __decorate([
  82387. BABYLON.serialize()
  82388. ], FollowCamera.prototype, "radius", void 0);
  82389. __decorate([
  82390. BABYLON.serialize()
  82391. ], FollowCamera.prototype, "rotationOffset", void 0);
  82392. __decorate([
  82393. BABYLON.serialize()
  82394. ], FollowCamera.prototype, "heightOffset", void 0);
  82395. __decorate([
  82396. BABYLON.serialize()
  82397. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  82398. __decorate([
  82399. BABYLON.serialize()
  82400. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  82401. __decorate([
  82402. BABYLON.serializeAsMeshReference("lockedTargetId")
  82403. ], FollowCamera.prototype, "lockedTarget", void 0);
  82404. return FollowCamera;
  82405. }(BABYLON.TargetCamera));
  82406. BABYLON.FollowCamera = FollowCamera;
  82407. /**
  82408. * Arc Rotate version of the follow camera.
  82409. * It still follows a Defined mesh but in an Arc Rotate Camera fashion.
  82410. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82411. */
  82412. var ArcFollowCamera = /** @class */ (function (_super) {
  82413. __extends(ArcFollowCamera, _super);
  82414. /**
  82415. * Instantiates a new ArcFollowCamera
  82416. * @see http://doc.babylonjs.com/features/cameras#follow-camera
  82417. * @param name Define the name of the camera
  82418. * @param alpha Define the rotation angle of the camera around the logitudinal axis
  82419. * @param beta Define the rotation angle of the camera around the elevation axis
  82420. * @param radius Define the radius of the camera from its target point
  82421. * @param target Define the target of the camera
  82422. * @param scene Define the scene the camera belongs to
  82423. */
  82424. function ArcFollowCamera(name,
  82425. /** The longitudinal angle of the camera */
  82426. alpha,
  82427. /** The latitudinal angle of the camera */
  82428. beta,
  82429. /** The radius of the camera from its target */
  82430. radius,
  82431. /** Define the camera target (the messh it should follow) */
  82432. target, scene) {
  82433. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  82434. _this.alpha = alpha;
  82435. _this.beta = beta;
  82436. _this.radius = radius;
  82437. _this.target = target;
  82438. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  82439. _this._follow();
  82440. return _this;
  82441. }
  82442. ArcFollowCamera.prototype._follow = function () {
  82443. if (!this.target) {
  82444. return;
  82445. }
  82446. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  82447. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  82448. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  82449. var targetPosition = this.target.getAbsolutePosition();
  82450. this.position = targetPosition.add(this._cartesianCoordinates);
  82451. this.setTarget(targetPosition);
  82452. };
  82453. /** @hidden */
  82454. ArcFollowCamera.prototype._checkInputs = function () {
  82455. _super.prototype._checkInputs.call(this);
  82456. this._follow();
  82457. };
  82458. /**
  82459. * Returns the class name of the object.
  82460. * It is mostly used internally for serialization purposes.
  82461. */
  82462. ArcFollowCamera.prototype.getClassName = function () {
  82463. return "ArcFollowCamera";
  82464. };
  82465. return ArcFollowCamera;
  82466. }(BABYLON.TargetCamera));
  82467. BABYLON.ArcFollowCamera = ArcFollowCamera;
  82468. })(BABYLON || (BABYLON = {}));
  82469. //# sourceMappingURL=babylon.followCamera.js.map
  82470. var BABYLON;
  82471. (function (BABYLON) {
  82472. /**
  82473. * 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,
  82474. * which still works and will still be found in many Playgrounds.
  82475. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82476. */
  82477. var UniversalCamera = /** @class */ (function (_super) {
  82478. __extends(UniversalCamera, _super);
  82479. /**
  82480. * 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,
  82481. * which still works and will still be found in many Playgrounds.
  82482. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82483. * @param name Define the name of the camera in the scene
  82484. * @param position Define the start position of the camera in the scene
  82485. * @param scene Define the scene the camera belongs to
  82486. */
  82487. function UniversalCamera(name, position, scene) {
  82488. var _this = _super.call(this, name, position, scene) || this;
  82489. _this.inputs.addGamepad();
  82490. return _this;
  82491. }
  82492. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  82493. /**
  82494. * Defines the gamepad rotation sensiblity.
  82495. * This is the threshold from when rotation starts to be accounted for to prevent jittering.
  82496. */
  82497. get: function () {
  82498. var gamepad = this.inputs.attached["gamepad"];
  82499. if (gamepad)
  82500. return gamepad.gamepadAngularSensibility;
  82501. return 0;
  82502. },
  82503. set: function (value) {
  82504. var gamepad = this.inputs.attached["gamepad"];
  82505. if (gamepad)
  82506. gamepad.gamepadAngularSensibility = value;
  82507. },
  82508. enumerable: true,
  82509. configurable: true
  82510. });
  82511. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  82512. /**
  82513. * Defines the gamepad move sensiblity.
  82514. * This is the threshold from when moving starts to be accounted for for to prevent jittering.
  82515. */
  82516. get: function () {
  82517. var gamepad = this.inputs.attached["gamepad"];
  82518. if (gamepad)
  82519. return gamepad.gamepadMoveSensibility;
  82520. return 0;
  82521. },
  82522. set: function (value) {
  82523. var gamepad = this.inputs.attached["gamepad"];
  82524. if (gamepad)
  82525. gamepad.gamepadMoveSensibility = value;
  82526. },
  82527. enumerable: true,
  82528. configurable: true
  82529. });
  82530. /**
  82531. * Gets the current object class name.
  82532. * @return the class name
  82533. */
  82534. UniversalCamera.prototype.getClassName = function () {
  82535. return "UniversalCamera";
  82536. };
  82537. return UniversalCamera;
  82538. }(BABYLON.TouchCamera));
  82539. BABYLON.UniversalCamera = UniversalCamera;
  82540. })(BABYLON || (BABYLON = {}));
  82541. //# sourceMappingURL=babylon.universalCamera.js.map
  82542. var BABYLON;
  82543. (function (BABYLON) {
  82544. BABYLON.Node.AddNodeConstructor("GamepadCamera", function (name, scene) {
  82545. return function () { return new GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  82546. });
  82547. /**
  82548. * This represents a FPS type of camera. This is only here for back compat purpose.
  82549. * Please use the UniversalCamera instead as both are identical.
  82550. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82551. */
  82552. var GamepadCamera = /** @class */ (function (_super) {
  82553. __extends(GamepadCamera, _super);
  82554. /**
  82555. * Instantiates a new Gamepad Camera
  82556. * This represents a FPS type of camera. This is only here for back compat purpose.
  82557. * Please use the UniversalCamera instead as both are identical.
  82558. * @see http://doc.babylonjs.com/features/cameras#universal-camera
  82559. * @param name Define the name of the camera in the scene
  82560. * @param position Define the start position of the camera in the scene
  82561. * @param scene Define the scene the camera belongs to
  82562. */
  82563. function GamepadCamera(name, position, scene) {
  82564. return _super.call(this, name, position, scene) || this;
  82565. }
  82566. /**
  82567. * Gets the current object class name.
  82568. * @return the class name
  82569. */
  82570. GamepadCamera.prototype.getClassName = function () {
  82571. return "GamepadCamera";
  82572. };
  82573. return GamepadCamera;
  82574. }(BABYLON.UniversalCamera));
  82575. BABYLON.GamepadCamera = GamepadCamera;
  82576. })(BABYLON || (BABYLON = {}));
  82577. //# sourceMappingURL=babylon.gamepadCamera.js.map
  82578. var BABYLON;
  82579. (function (BABYLON) {
  82580. /**
  82581. * PostProcessRenderPipelineManager class
  82582. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82583. */
  82584. var PostProcessRenderPipelineManager = /** @class */ (function () {
  82585. /**
  82586. * Initializes a PostProcessRenderPipelineManager
  82587. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82588. */
  82589. function PostProcessRenderPipelineManager() {
  82590. this._renderPipelines = {};
  82591. }
  82592. /**
  82593. * Adds a pipeline to the manager
  82594. * @param renderPipeline The pipeline to add
  82595. */
  82596. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  82597. this._renderPipelines[renderPipeline._name] = renderPipeline;
  82598. };
  82599. /**
  82600. * Attaches a camera to the pipeline
  82601. * @param renderPipelineName The name of the pipeline to attach to
  82602. * @param cameras the camera to attach
  82603. * @param unique if the camera can be attached multiple times to the pipeline
  82604. */
  82605. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  82606. if (unique === void 0) { unique = false; }
  82607. var renderPipeline = this._renderPipelines[renderPipelineName];
  82608. if (!renderPipeline) {
  82609. return;
  82610. }
  82611. renderPipeline._attachCameras(cameras, unique);
  82612. };
  82613. /**
  82614. * Detaches a camera from the pipeline
  82615. * @param renderPipelineName The name of the pipeline to detach from
  82616. * @param cameras the camera to detach
  82617. */
  82618. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  82619. var renderPipeline = this._renderPipelines[renderPipelineName];
  82620. if (!renderPipeline) {
  82621. return;
  82622. }
  82623. renderPipeline._detachCameras(cameras);
  82624. };
  82625. /**
  82626. * Enables an effect by name on a pipeline
  82627. * @param renderPipelineName the name of the pipeline to enable the effect in
  82628. * @param renderEffectName the name of the effect to enable
  82629. * @param cameras the cameras that the effect should be enabled on
  82630. */
  82631. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82632. var renderPipeline = this._renderPipelines[renderPipelineName];
  82633. if (!renderPipeline) {
  82634. return;
  82635. }
  82636. renderPipeline._enableEffect(renderEffectName, cameras);
  82637. };
  82638. /**
  82639. * Disables an effect by name on a pipeline
  82640. * @param renderPipelineName the name of the pipeline to disable the effect in
  82641. * @param renderEffectName the name of the effect to disable
  82642. * @param cameras the cameras that the effect should be disabled on
  82643. */
  82644. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  82645. var renderPipeline = this._renderPipelines[renderPipelineName];
  82646. if (!renderPipeline) {
  82647. return;
  82648. }
  82649. renderPipeline._disableEffect(renderEffectName, cameras);
  82650. };
  82651. /**
  82652. * Updates the state of all contained render pipelines and disposes of any non supported pipelines
  82653. */
  82654. PostProcessRenderPipelineManager.prototype.update = function () {
  82655. for (var renderPipelineName in this._renderPipelines) {
  82656. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82657. var pipeline = this._renderPipelines[renderPipelineName];
  82658. if (!pipeline.isSupported) {
  82659. pipeline.dispose();
  82660. delete this._renderPipelines[renderPipelineName];
  82661. }
  82662. else {
  82663. pipeline._update();
  82664. }
  82665. }
  82666. }
  82667. };
  82668. /** @hidden */
  82669. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  82670. for (var renderPipelineName in this._renderPipelines) {
  82671. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82672. var pipeline = this._renderPipelines[renderPipelineName];
  82673. pipeline._rebuild();
  82674. }
  82675. }
  82676. };
  82677. /**
  82678. * Disposes of the manager and pipelines
  82679. */
  82680. PostProcessRenderPipelineManager.prototype.dispose = function () {
  82681. for (var renderPipelineName in this._renderPipelines) {
  82682. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  82683. var pipeline = this._renderPipelines[renderPipelineName];
  82684. pipeline.dispose();
  82685. }
  82686. }
  82687. };
  82688. return PostProcessRenderPipelineManager;
  82689. }());
  82690. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  82691. })(BABYLON || (BABYLON = {}));
  82692. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  82693. var BABYLON;
  82694. (function (BABYLON) {
  82695. Object.defineProperty(BABYLON.Scene.prototype, "postProcessRenderPipelineManager", {
  82696. get: function () {
  82697. if (!this._postProcessRenderPipelineManager) {
  82698. // Register the G Buffer component to the scene.
  82699. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER);
  82700. if (!component) {
  82701. component = new PostProcessRenderPipelineManagerSceneComponent(this);
  82702. this._addComponent(component);
  82703. }
  82704. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  82705. }
  82706. return this._postProcessRenderPipelineManager;
  82707. },
  82708. enumerable: true,
  82709. configurable: true
  82710. });
  82711. /**
  82712. * Defines the Render Pipeline scene component responsible to rendering pipelines
  82713. */
  82714. var PostProcessRenderPipelineManagerSceneComponent = /** @class */ (function () {
  82715. /**
  82716. * Creates a new instance of the component for the given scene
  82717. * @param scene Defines the scene to register the component in
  82718. */
  82719. function PostProcessRenderPipelineManagerSceneComponent(scene) {
  82720. /**
  82721. * The component name helpfull to identify the component in the list of scene components.
  82722. */
  82723. this.name = BABYLON.SceneComponentConstants.NAME_POSTPROCESSRENDERPIPELINEMANAGER;
  82724. this.scene = scene;
  82725. }
  82726. /**
  82727. * Registers the component in a given scene
  82728. */
  82729. PostProcessRenderPipelineManagerSceneComponent.prototype.register = function () {
  82730. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_POSTPROCESSRENDERPIPELINEMANAGER, this, this._gatherRenderTargets);
  82731. };
  82732. /**
  82733. * Rebuilds the elements related to this component in case of
  82734. * context lost for instance.
  82735. */
  82736. PostProcessRenderPipelineManagerSceneComponent.prototype.rebuild = function () {
  82737. if (this.scene._postProcessRenderPipelineManager) {
  82738. this.scene._postProcessRenderPipelineManager._rebuild();
  82739. }
  82740. };
  82741. /**
  82742. * Disposes the component and the associated ressources
  82743. */
  82744. PostProcessRenderPipelineManagerSceneComponent.prototype.dispose = function () {
  82745. if (this.scene._postProcessRenderPipelineManager) {
  82746. this.scene._postProcessRenderPipelineManager.dispose();
  82747. }
  82748. };
  82749. PostProcessRenderPipelineManagerSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  82750. if (this.scene._postProcessRenderPipelineManager) {
  82751. this.scene._postProcessRenderPipelineManager.update();
  82752. }
  82753. };
  82754. return PostProcessRenderPipelineManagerSceneComponent;
  82755. }());
  82756. BABYLON.PostProcessRenderPipelineManagerSceneComponent = PostProcessRenderPipelineManagerSceneComponent;
  82757. })(BABYLON || (BABYLON = {}));
  82758. //# sourceMappingURL=babylon.postProcessRenderPipelineManagerSceneComponent.js.map
  82759. var BABYLON;
  82760. (function (BABYLON) {
  82761. /**
  82762. * This represents a set of one or more post processes in Babylon.
  82763. * A post process can be used to apply a shader to a texture after it is rendered.
  82764. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82765. */
  82766. var PostProcessRenderEffect = /** @class */ (function () {
  82767. /**
  82768. * Instantiates a post process render effect.
  82769. * A post process can be used to apply a shader to a texture after it is rendered.
  82770. * @param engine The engine the effect is tied to
  82771. * @param name The name of the effect
  82772. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  82773. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  82774. */
  82775. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  82776. this._name = name;
  82777. this._singleInstance = singleInstance || true;
  82778. this._getPostProcesses = getPostProcesses;
  82779. this._cameras = {};
  82780. this._indicesForCamera = {};
  82781. this._postProcesses = {};
  82782. }
  82783. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  82784. /**
  82785. * Checks if all the post processes in the effect are supported.
  82786. */
  82787. get: function () {
  82788. for (var index in this._postProcesses) {
  82789. if (this._postProcesses.hasOwnProperty(index)) {
  82790. var pps = this._postProcesses[index];
  82791. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  82792. if (!pps[ppIndex].isSupported) {
  82793. return false;
  82794. }
  82795. }
  82796. }
  82797. }
  82798. return true;
  82799. },
  82800. enumerable: true,
  82801. configurable: true
  82802. });
  82803. /**
  82804. * Updates the current state of the effect
  82805. * @hidden
  82806. */
  82807. PostProcessRenderEffect.prototype._update = function () {
  82808. };
  82809. /**
  82810. * Attaches the effect on cameras
  82811. * @param cameras The camera to attach to.
  82812. * @hidden
  82813. */
  82814. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  82815. var _this = this;
  82816. var cameraKey;
  82817. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82818. if (!cams) {
  82819. return;
  82820. }
  82821. for (var i = 0; i < cams.length; i++) {
  82822. var camera = cams[i];
  82823. var cameraName = camera.name;
  82824. if (this._singleInstance) {
  82825. cameraKey = 0;
  82826. }
  82827. else {
  82828. cameraKey = cameraName;
  82829. }
  82830. if (!this._postProcesses[cameraKey]) {
  82831. var postProcess = this._getPostProcesses();
  82832. if (postProcess) {
  82833. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  82834. }
  82835. }
  82836. if (!this._indicesForCamera[cameraName]) {
  82837. this._indicesForCamera[cameraName] = [];
  82838. }
  82839. this._postProcesses[cameraKey].forEach(function (postProcess) {
  82840. var index = camera.attachPostProcess(postProcess);
  82841. _this._indicesForCamera[cameraName].push(index);
  82842. });
  82843. if (!this._cameras[cameraName]) {
  82844. this._cameras[cameraName] = camera;
  82845. }
  82846. }
  82847. };
  82848. /**
  82849. * Detatches the effect on cameras
  82850. * @param cameras The camera to detatch from.
  82851. * @hidden
  82852. */
  82853. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  82854. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82855. if (!cams) {
  82856. return;
  82857. }
  82858. for (var i = 0; i < cams.length; i++) {
  82859. var camera = cams[i];
  82860. var cameraName = camera.name;
  82861. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82862. camera.detachPostProcess(postProcess);
  82863. });
  82864. if (this._cameras[cameraName]) {
  82865. //this._indicesForCamera.splice(index, 1);
  82866. this._cameras[cameraName] = null;
  82867. }
  82868. }
  82869. };
  82870. /**
  82871. * Enables the effect on given cameras
  82872. * @param cameras The camera to enable.
  82873. * @hidden
  82874. */
  82875. PostProcessRenderEffect.prototype._enable = function (cameras) {
  82876. var _this = this;
  82877. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82878. if (!cams) {
  82879. return;
  82880. }
  82881. for (var i = 0; i < cams.length; i++) {
  82882. var camera = cams[i];
  82883. var cameraName = camera.name;
  82884. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  82885. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  82886. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82887. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  82888. });
  82889. }
  82890. }
  82891. }
  82892. };
  82893. /**
  82894. * Disables the effect on the given cameras
  82895. * @param cameras The camera to disable.
  82896. * @hidden
  82897. */
  82898. PostProcessRenderEffect.prototype._disable = function (cameras) {
  82899. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  82900. if (!cams) {
  82901. return;
  82902. }
  82903. for (var i = 0; i < cams.length; i++) {
  82904. var camera = cams[i];
  82905. var cameraName = camera.name;
  82906. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  82907. camera.detachPostProcess(postProcess);
  82908. });
  82909. }
  82910. };
  82911. /**
  82912. * Gets a list of the post processes contained in the effect.
  82913. * @param camera The camera to get the post processes on.
  82914. * @returns The list of the post processes in the effect.
  82915. */
  82916. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  82917. if (this._singleInstance) {
  82918. return this._postProcesses[0];
  82919. }
  82920. else {
  82921. if (!camera) {
  82922. return null;
  82923. }
  82924. return this._postProcesses[camera.name];
  82925. }
  82926. };
  82927. return PostProcessRenderEffect;
  82928. }());
  82929. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  82930. })(BABYLON || (BABYLON = {}));
  82931. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  82932. var BABYLON;
  82933. (function (BABYLON) {
  82934. /**
  82935. * PostProcessRenderPipeline
  82936. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  82937. */
  82938. var PostProcessRenderPipeline = /** @class */ (function () {
  82939. /**
  82940. * Initializes a PostProcessRenderPipeline
  82941. * @param engine engine to add the pipeline to
  82942. * @param name name of the pipeline
  82943. */
  82944. function PostProcessRenderPipeline(engine, name) {
  82945. this.engine = engine;
  82946. this._name = name;
  82947. this._renderEffects = {};
  82948. this._renderEffectsForIsolatedPass = new Array();
  82949. this._cameras = [];
  82950. }
  82951. /**
  82952. * "PostProcessRenderPipeline"
  82953. * @returns "PostProcessRenderPipeline"
  82954. */
  82955. PostProcessRenderPipeline.prototype.getClassName = function () {
  82956. return "PostProcessRenderPipeline";
  82957. };
  82958. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  82959. /**
  82960. * If all the render effects in the pipeline are support
  82961. */
  82962. get: function () {
  82963. for (var renderEffectName in this._renderEffects) {
  82964. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  82965. if (!this._renderEffects[renderEffectName].isSupported) {
  82966. return false;
  82967. }
  82968. }
  82969. }
  82970. return true;
  82971. },
  82972. enumerable: true,
  82973. configurable: true
  82974. });
  82975. /**
  82976. * Adds an effect to the pipeline
  82977. * @param renderEffect the effect to add
  82978. */
  82979. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  82980. this._renderEffects[renderEffect._name] = renderEffect;
  82981. };
  82982. // private
  82983. /** @hidden */
  82984. PostProcessRenderPipeline.prototype._rebuild = function () {
  82985. };
  82986. /** @hidden */
  82987. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  82988. var renderEffects = this._renderEffects[renderEffectName];
  82989. if (!renderEffects) {
  82990. return;
  82991. }
  82992. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  82993. };
  82994. /** @hidden */
  82995. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  82996. var renderEffects = this._renderEffects[renderEffectName];
  82997. if (!renderEffects) {
  82998. return;
  82999. }
  83000. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  83001. };
  83002. /** @hidden */
  83003. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  83004. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83005. if (!cams) {
  83006. return;
  83007. }
  83008. var indicesToDelete = [];
  83009. var i;
  83010. for (i = 0; i < cams.length; i++) {
  83011. var camera = cams[i];
  83012. var cameraName = camera.name;
  83013. if (this._cameras.indexOf(camera) === -1) {
  83014. this._cameras[cameraName] = camera;
  83015. }
  83016. else if (unique) {
  83017. indicesToDelete.push(i);
  83018. }
  83019. }
  83020. for (i = 0; i < indicesToDelete.length; i++) {
  83021. cameras.splice(indicesToDelete[i], 1);
  83022. }
  83023. for (var renderEffectName in this._renderEffects) {
  83024. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83025. this._renderEffects[renderEffectName]._attachCameras(cams);
  83026. }
  83027. }
  83028. };
  83029. /** @hidden */
  83030. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  83031. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  83032. if (!cams) {
  83033. return;
  83034. }
  83035. for (var renderEffectName in this._renderEffects) {
  83036. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83037. this._renderEffects[renderEffectName]._detachCameras(cams);
  83038. }
  83039. }
  83040. for (var i = 0; i < cams.length; i++) {
  83041. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  83042. }
  83043. };
  83044. /** @hidden */
  83045. PostProcessRenderPipeline.prototype._update = function () {
  83046. for (var renderEffectName in this._renderEffects) {
  83047. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  83048. this._renderEffects[renderEffectName]._update();
  83049. }
  83050. }
  83051. for (var i = 0; i < this._cameras.length; i++) {
  83052. var cameraName = this._cameras[i].name;
  83053. if (this._renderEffectsForIsolatedPass[cameraName]) {
  83054. this._renderEffectsForIsolatedPass[cameraName]._update();
  83055. }
  83056. }
  83057. };
  83058. /** @hidden */
  83059. PostProcessRenderPipeline.prototype._reset = function () {
  83060. this._renderEffects = {};
  83061. this._renderEffectsForIsolatedPass = new Array();
  83062. };
  83063. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  83064. // 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)
  83065. var effectKeys = Object.keys(this._renderEffects);
  83066. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  83067. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  83068. if (postProcesses) {
  83069. postProcesses[0].samples = sampleCount;
  83070. return true;
  83071. }
  83072. }
  83073. return false;
  83074. };
  83075. /**
  83076. * Disposes of the pipeline
  83077. */
  83078. PostProcessRenderPipeline.prototype.dispose = function () {
  83079. // Must be implemented by children
  83080. };
  83081. __decorate([
  83082. BABYLON.serialize()
  83083. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  83084. return PostProcessRenderPipeline;
  83085. }());
  83086. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  83087. })(BABYLON || (BABYLON = {}));
  83088. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  83089. var BABYLON;
  83090. (function (BABYLON) {
  83091. /**
  83092. * This represents a depth renderer in Babylon.
  83093. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  83094. */
  83095. var DepthRenderer = /** @class */ (function () {
  83096. /**
  83097. * Instantiates a depth renderer
  83098. * @param scene The scene the renderer belongs to
  83099. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  83100. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  83101. */
  83102. function DepthRenderer(scene, type, camera) {
  83103. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  83104. if (camera === void 0) { camera = null; }
  83105. var _this = this;
  83106. /**
  83107. * Specifiess that the depth renderer will only be used within
  83108. * the camera it is created for.
  83109. * This can help forcing its rendering during the camera processing.
  83110. */
  83111. this.useOnlyInActiveCamera = false;
  83112. this._scene = scene;
  83113. // Register the G Buffer component to the scene.
  83114. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER);
  83115. if (!component) {
  83116. component = new BABYLON.DepthRendererSceneComponent(scene);
  83117. scene._addComponent(component);
  83118. }
  83119. this._camera = camera;
  83120. var engine = scene.getEngine();
  83121. // Render target
  83122. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  83123. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83124. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83125. this._depthMap.refreshRate = 1;
  83126. this._depthMap.renderParticles = false;
  83127. this._depthMap.renderList = null;
  83128. // Camera to get depth map from to support multiple concurrent cameras
  83129. this._depthMap.activeCamera = this._camera;
  83130. this._depthMap.ignoreCameraViewport = true;
  83131. this._depthMap.useCameraPostProcesses = false;
  83132. // set default depth value to 1.0 (far away)
  83133. this._depthMap.onClearObservable.add(function (engine) {
  83134. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  83135. });
  83136. // Custom render function
  83137. var renderSubMesh = function (subMesh) {
  83138. var mesh = subMesh.getRenderingMesh();
  83139. var scene = _this._scene;
  83140. var engine = scene.getEngine();
  83141. var material = subMesh.getMaterial();
  83142. if (!material) {
  83143. return;
  83144. }
  83145. // Culling and reverse (right handed system)
  83146. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83147. // Managing instances
  83148. var batch = mesh._getInstancesRenderList(subMesh._id);
  83149. if (batch.mustReturn) {
  83150. return;
  83151. }
  83152. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83153. var camera = _this._camera || scene.activeCamera;
  83154. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  83155. engine.enableEffect(_this._effect);
  83156. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83157. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83158. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  83159. // Alpha test
  83160. if (material && material.needAlphaTesting()) {
  83161. var alphaTexture = material.getAlphaTestTexture();
  83162. if (alphaTexture) {
  83163. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83164. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83165. }
  83166. }
  83167. // Bones
  83168. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83169. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83170. }
  83171. // Draw
  83172. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83173. }
  83174. };
  83175. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83176. var index;
  83177. if (depthOnlySubMeshes.length) {
  83178. engine.setColorWrite(false);
  83179. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83180. renderSubMesh(depthOnlySubMeshes.data[index]);
  83181. }
  83182. engine.setColorWrite(true);
  83183. }
  83184. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83185. renderSubMesh(opaqueSubMeshes.data[index]);
  83186. }
  83187. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83188. renderSubMesh(alphaTestSubMeshes.data[index]);
  83189. }
  83190. };
  83191. }
  83192. /**
  83193. * Creates the depth rendering effect and checks if the effect is ready.
  83194. * @param subMesh The submesh to be used to render the depth map of
  83195. * @param useInstances If multiple world instances should be used
  83196. * @returns if the depth renderer is ready to render the depth map
  83197. */
  83198. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  83199. var material = subMesh.getMaterial();
  83200. if (material.disableDepthWrite) {
  83201. return false;
  83202. }
  83203. var defines = [];
  83204. var attribs = [BABYLON.VertexBuffer.PositionKind];
  83205. var mesh = subMesh.getMesh();
  83206. // Alpha test
  83207. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  83208. defines.push("#define ALPHATEST");
  83209. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83210. attribs.push(BABYLON.VertexBuffer.UVKind);
  83211. defines.push("#define UV1");
  83212. }
  83213. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83214. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83215. defines.push("#define UV2");
  83216. }
  83217. }
  83218. // Bones
  83219. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83220. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83221. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83222. if (mesh.numBoneInfluencers > 4) {
  83223. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83224. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83225. }
  83226. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83227. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83228. }
  83229. else {
  83230. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83231. }
  83232. // Instances
  83233. if (useInstances) {
  83234. defines.push("#define INSTANCES");
  83235. attribs.push("world0");
  83236. attribs.push("world1");
  83237. attribs.push("world2");
  83238. attribs.push("world3");
  83239. }
  83240. // Get correct effect
  83241. var join = defines.join("\n");
  83242. if (this._cachedDefines !== join) {
  83243. this._cachedDefines = join;
  83244. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  83245. }
  83246. return this._effect.isReady();
  83247. };
  83248. /**
  83249. * Gets the texture which the depth map will be written to.
  83250. * @returns The depth map texture
  83251. */
  83252. DepthRenderer.prototype.getDepthMap = function () {
  83253. return this._depthMap;
  83254. };
  83255. /**
  83256. * Disposes of the depth renderer.
  83257. */
  83258. DepthRenderer.prototype.dispose = function () {
  83259. this._depthMap.dispose();
  83260. };
  83261. return DepthRenderer;
  83262. }());
  83263. BABYLON.DepthRenderer = DepthRenderer;
  83264. })(BABYLON || (BABYLON = {}));
  83265. //# sourceMappingURL=babylon.depthRenderer.js.map
  83266. var BABYLON;
  83267. (function (BABYLON) {
  83268. BABYLON.Scene.prototype.enableDepthRenderer = function (camera) {
  83269. camera = camera || this.activeCamera;
  83270. if (!camera) {
  83271. throw "No camera available to enable depth renderer";
  83272. }
  83273. if (!this._depthRenderer) {
  83274. this._depthRenderer = {};
  83275. }
  83276. if (!this._depthRenderer[camera.id]) {
  83277. var textureType = 0;
  83278. if (this.getEngine().getCaps().textureHalfFloatRender) {
  83279. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  83280. }
  83281. else if (this.getEngine().getCaps().textureFloatRender) {
  83282. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  83283. }
  83284. else {
  83285. throw "Depth renderer does not support int texture type";
  83286. }
  83287. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  83288. }
  83289. return this._depthRenderer[camera.id];
  83290. };
  83291. BABYLON.Scene.prototype.disableDepthRenderer = function (camera) {
  83292. camera = camera || this.activeCamera;
  83293. if (!camera || !this._depthRenderer || !this._depthRenderer[camera.id]) {
  83294. return;
  83295. }
  83296. this._depthRenderer[camera.id].dispose();
  83297. delete this._depthRenderer[camera.id];
  83298. };
  83299. /**
  83300. * Defines the Depth Renderer scene component responsible to manage a depth buffer usefull
  83301. * in several rendering techniques.
  83302. */
  83303. var DepthRendererSceneComponent = /** @class */ (function () {
  83304. /**
  83305. * Creates a new instance of the component for the given scene
  83306. * @param scene Defines the scene to register the component in
  83307. */
  83308. function DepthRendererSceneComponent(scene) {
  83309. /**
  83310. * The component name helpfull to identify the component in the list of scene components.
  83311. */
  83312. this.name = BABYLON.SceneComponentConstants.NAME_DEPTHRENDERER;
  83313. this.scene = scene;
  83314. }
  83315. /**
  83316. * Registers the component in a given scene
  83317. */
  83318. DepthRendererSceneComponent.prototype.register = function () {
  83319. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_DEPTHRENDERER, this, this._gatherRenderTargets);
  83320. this.scene._gatherActiveCameraRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERACTIVECAMERARENDERTARGETS_DEPTHRENDERER, this, this._gatherActiveCameraRenderTargets);
  83321. };
  83322. /**
  83323. * Rebuilds the elements related to this component in case of
  83324. * context lost for instance.
  83325. */
  83326. DepthRendererSceneComponent.prototype.rebuild = function () {
  83327. // Nothing to do for this component
  83328. };
  83329. /**
  83330. * Disposes the component and the associated ressources
  83331. */
  83332. DepthRendererSceneComponent.prototype.dispose = function () {
  83333. for (var key in this.scene._depthRenderer) {
  83334. this.scene._depthRenderer[key].dispose();
  83335. }
  83336. };
  83337. DepthRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83338. if (this.scene._depthRenderer) {
  83339. for (var key in this.scene._depthRenderer) {
  83340. var depthRenderer = this.scene._depthRenderer[key];
  83341. if (!depthRenderer.useOnlyInActiveCamera) {
  83342. renderTargets.push(depthRenderer.getDepthMap());
  83343. }
  83344. }
  83345. }
  83346. };
  83347. DepthRendererSceneComponent.prototype._gatherActiveCameraRenderTargets = function (renderTargets) {
  83348. if (this.scene._depthRenderer) {
  83349. for (var key in this.scene._depthRenderer) {
  83350. var depthRenderer = this.scene._depthRenderer[key];
  83351. if (depthRenderer.useOnlyInActiveCamera && this.scene.activeCamera.id === key) {
  83352. renderTargets.push(depthRenderer.getDepthMap());
  83353. }
  83354. }
  83355. }
  83356. };
  83357. return DepthRendererSceneComponent;
  83358. }());
  83359. BABYLON.DepthRendererSceneComponent = DepthRendererSceneComponent;
  83360. })(BABYLON || (BABYLON = {}));
  83361. //# sourceMappingURL=babylon.depthRendererSceneComponent.js.map
  83362. var BABYLON;
  83363. (function (BABYLON) {
  83364. /**
  83365. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  83366. */
  83367. var GeometryBufferRenderer = /** @class */ (function () {
  83368. /**
  83369. * Creates a new G Buffer for the scene
  83370. * @param scene The scene the buffer belongs to
  83371. * @param ratio How big is the buffer related to the main canvas.
  83372. */
  83373. function GeometryBufferRenderer(scene, ratio) {
  83374. if (ratio === void 0) { ratio = 1; }
  83375. this._enablePosition = false;
  83376. this._scene = scene;
  83377. this._ratio = ratio;
  83378. // Register the G Buffer component to the scene.
  83379. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER);
  83380. if (!component) {
  83381. component = new BABYLON.GeometryBufferRendererSceneComponent(scene);
  83382. scene._addComponent(component);
  83383. }
  83384. // Render target
  83385. this._createRenderTargets();
  83386. }
  83387. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  83388. /**
  83389. * Set the render list (meshes to be rendered) used in the G buffer.
  83390. */
  83391. set: function (meshes) {
  83392. this._multiRenderTarget.renderList = meshes;
  83393. },
  83394. enumerable: true,
  83395. configurable: true
  83396. });
  83397. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  83398. /**
  83399. * Gets wether or not G buffer are supported by the running hardware.
  83400. * This requires draw buffer supports
  83401. */
  83402. get: function () {
  83403. return this._multiRenderTarget.isSupported;
  83404. },
  83405. enumerable: true,
  83406. configurable: true
  83407. });
  83408. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  83409. /**
  83410. * Gets wether or not position are enabled for the G buffer.
  83411. */
  83412. get: function () {
  83413. return this._enablePosition;
  83414. },
  83415. /**
  83416. * Sets wether or not position are enabled for the G buffer.
  83417. */
  83418. set: function (enable) {
  83419. this._enablePosition = enable;
  83420. this.dispose();
  83421. this._createRenderTargets();
  83422. },
  83423. enumerable: true,
  83424. configurable: true
  83425. });
  83426. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  83427. /**
  83428. * Gets the scene associated with the buffer.
  83429. */
  83430. get: function () {
  83431. return this._scene;
  83432. },
  83433. enumerable: true,
  83434. configurable: true
  83435. });
  83436. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  83437. /**
  83438. * Gets the ratio used by the buffer during its creation.
  83439. * How big is the buffer related to the main canvas.
  83440. */
  83441. get: function () {
  83442. return this._ratio;
  83443. },
  83444. enumerable: true,
  83445. configurable: true
  83446. });
  83447. /**
  83448. * Checks wether everything is ready to render a submesh to the G buffer.
  83449. * @param subMesh the submesh to check readiness for
  83450. * @param useInstances is the mesh drawn using instance or not
  83451. * @returns true if ready otherwise false
  83452. */
  83453. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  83454. var material = subMesh.getMaterial();
  83455. if (material && material.disableDepthWrite) {
  83456. return false;
  83457. }
  83458. var defines = [];
  83459. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  83460. var mesh = subMesh.getMesh();
  83461. // Alpha test
  83462. if (material && material.needAlphaTesting()) {
  83463. defines.push("#define ALPHATEST");
  83464. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  83465. attribs.push(BABYLON.VertexBuffer.UVKind);
  83466. defines.push("#define UV1");
  83467. }
  83468. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  83469. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  83470. defines.push("#define UV2");
  83471. }
  83472. }
  83473. // Buffers
  83474. if (this._enablePosition) {
  83475. defines.push("#define POSITION");
  83476. }
  83477. // Bones
  83478. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  83479. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  83480. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  83481. if (mesh.numBoneInfluencers > 4) {
  83482. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  83483. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  83484. }
  83485. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  83486. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  83487. }
  83488. else {
  83489. defines.push("#define NUM_BONE_INFLUENCERS 0");
  83490. }
  83491. // Instances
  83492. if (useInstances) {
  83493. defines.push("#define INSTANCES");
  83494. attribs.push("world0");
  83495. attribs.push("world1");
  83496. attribs.push("world2");
  83497. attribs.push("world3");
  83498. }
  83499. // Get correct effect
  83500. var join = defines.join("\n");
  83501. if (this._cachedDefines !== join) {
  83502. this._cachedDefines = join;
  83503. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  83504. }
  83505. return this._effect.isReady();
  83506. };
  83507. /**
  83508. * Gets the current underlying G Buffer.
  83509. * @returns the buffer
  83510. */
  83511. GeometryBufferRenderer.prototype.getGBuffer = function () {
  83512. return this._multiRenderTarget;
  83513. };
  83514. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  83515. /**
  83516. * Gets the number of samples used to render the buffer (anti aliasing).
  83517. */
  83518. get: function () {
  83519. return this._multiRenderTarget.samples;
  83520. },
  83521. /**
  83522. * Sets the number of samples used to render the buffer (anti aliasing).
  83523. */
  83524. set: function (value) {
  83525. this._multiRenderTarget.samples = value;
  83526. },
  83527. enumerable: true,
  83528. configurable: true
  83529. });
  83530. /**
  83531. * Disposes the renderer and frees up associated resources.
  83532. */
  83533. GeometryBufferRenderer.prototype.dispose = function () {
  83534. this.getGBuffer().dispose();
  83535. };
  83536. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  83537. var _this = this;
  83538. var engine = this._scene.getEngine();
  83539. var count = this._enablePosition ? 3 : 2;
  83540. 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 });
  83541. if (!this.isSupported) {
  83542. return;
  83543. }
  83544. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83545. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  83546. this._multiRenderTarget.refreshRate = 1;
  83547. this._multiRenderTarget.renderParticles = false;
  83548. this._multiRenderTarget.renderList = null;
  83549. // set default depth value to 1.0 (far away)
  83550. this._multiRenderTarget.onClearObservable.add(function (engine) {
  83551. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  83552. });
  83553. // Custom render function
  83554. var renderSubMesh = function (subMesh) {
  83555. var mesh = subMesh.getRenderingMesh();
  83556. var scene = _this._scene;
  83557. var engine = scene.getEngine();
  83558. var material = subMesh.getMaterial();
  83559. if (!material) {
  83560. return;
  83561. }
  83562. // Culling
  83563. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  83564. // Managing instances
  83565. var batch = mesh._getInstancesRenderList(subMesh._id);
  83566. if (batch.mustReturn) {
  83567. return;
  83568. }
  83569. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  83570. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  83571. engine.enableEffect(_this._effect);
  83572. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  83573. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  83574. _this._effect.setMatrix("view", scene.getViewMatrix());
  83575. // Alpha test
  83576. if (material && material.needAlphaTesting()) {
  83577. var alphaTexture = material.getAlphaTestTexture();
  83578. if (alphaTexture) {
  83579. _this._effect.setTexture("diffuseSampler", alphaTexture);
  83580. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  83581. }
  83582. }
  83583. // Bones
  83584. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  83585. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  83586. }
  83587. // Draw
  83588. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  83589. }
  83590. };
  83591. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  83592. var index;
  83593. if (depthOnlySubMeshes.length) {
  83594. engine.setColorWrite(false);
  83595. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  83596. renderSubMesh(depthOnlySubMeshes.data[index]);
  83597. }
  83598. engine.setColorWrite(true);
  83599. }
  83600. for (index = 0; index < opaqueSubMeshes.length; index++) {
  83601. renderSubMesh(opaqueSubMeshes.data[index]);
  83602. }
  83603. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  83604. renderSubMesh(alphaTestSubMeshes.data[index]);
  83605. }
  83606. };
  83607. };
  83608. return GeometryBufferRenderer;
  83609. }());
  83610. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  83611. })(BABYLON || (BABYLON = {}));
  83612. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  83613. var BABYLON;
  83614. (function (BABYLON) {
  83615. Object.defineProperty(BABYLON.Scene.prototype, "geometryBufferRenderer", {
  83616. get: function () {
  83617. this._geometryBufferRenderer;
  83618. },
  83619. set: function (value) {
  83620. if (value && value.isSupported) {
  83621. this._geometryBufferRenderer = value;
  83622. }
  83623. ;
  83624. },
  83625. enumerable: true,
  83626. configurable: true
  83627. });
  83628. BABYLON.Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  83629. if (ratio === void 0) { ratio = 1; }
  83630. if (this._geometryBufferRenderer) {
  83631. return this._geometryBufferRenderer;
  83632. }
  83633. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  83634. if (!this._geometryBufferRenderer.isSupported) {
  83635. this._geometryBufferRenderer = null;
  83636. }
  83637. return this._geometryBufferRenderer;
  83638. };
  83639. BABYLON.Scene.prototype.disableGeometryBufferRenderer = function () {
  83640. if (!this._geometryBufferRenderer) {
  83641. return;
  83642. }
  83643. this._geometryBufferRenderer.dispose();
  83644. this._geometryBufferRenderer = null;
  83645. };
  83646. /**
  83647. * Defines the Geometry Buffer scene component responsible to manage a G-Buffer useful
  83648. * in several rendering techniques.
  83649. */
  83650. var GeometryBufferRendererSceneComponent = /** @class */ (function () {
  83651. /**
  83652. * Creates a new instance of the component for the given scene
  83653. * @param scene Defines the scene to register the component in
  83654. */
  83655. function GeometryBufferRendererSceneComponent(scene) {
  83656. /**
  83657. * The component name helpful to identify the component in the list of scene components.
  83658. */
  83659. this.name = BABYLON.SceneComponentConstants.NAME_GEOMETRYBUFFERRENDERER;
  83660. this.scene = scene;
  83661. }
  83662. /**
  83663. * Registers the component in a given scene
  83664. */
  83665. GeometryBufferRendererSceneComponent.prototype.register = function () {
  83666. this.scene._gatherRenderTargetsStage.registerStep(BABYLON.SceneComponentConstants.STEP_GATHERRENDERTARGETS_GEOMETRYBUFFERRENDERER, this, this._gatherRenderTargets);
  83667. };
  83668. /**
  83669. * Rebuilds the elements related to this component in case of
  83670. * context lost for instance.
  83671. */
  83672. GeometryBufferRendererSceneComponent.prototype.rebuild = function () {
  83673. // Nothing to do for this component
  83674. };
  83675. /**
  83676. * Disposes the component and the associated ressources
  83677. */
  83678. GeometryBufferRendererSceneComponent.prototype.dispose = function () {
  83679. // Nothing to do for this component
  83680. };
  83681. GeometryBufferRendererSceneComponent.prototype._gatherRenderTargets = function (renderTargets) {
  83682. if (this.scene._geometryBufferRenderer) {
  83683. renderTargets.push(this.scene._geometryBufferRenderer.getGBuffer());
  83684. }
  83685. };
  83686. return GeometryBufferRendererSceneComponent;
  83687. }());
  83688. BABYLON.GeometryBufferRendererSceneComponent = GeometryBufferRendererSceneComponent;
  83689. })(BABYLON || (BABYLON = {}));
  83690. //# sourceMappingURL=babylon.geometryBufferRendererSceneComponent.js.map
  83691. var BABYLON;
  83692. (function (BABYLON) {
  83693. /**
  83694. * Render pipeline to produce ssao effect
  83695. */
  83696. var SSAORenderingPipeline = /** @class */ (function (_super) {
  83697. __extends(SSAORenderingPipeline, _super);
  83698. /**
  83699. * @constructor
  83700. * @param name - The rendering pipeline name
  83701. * @param scene - The scene linked to this pipeline
  83702. * @param 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 }
  83703. * @param cameras - The array of cameras that the rendering pipeline will be attached to
  83704. */
  83705. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  83706. var _this = _super.call(this, scene.getEngine(), name) || this;
  83707. // Members
  83708. /**
  83709. * @ignore
  83710. * The PassPostProcess id in the pipeline that contains the original scene color
  83711. */
  83712. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83713. /**
  83714. * @ignore
  83715. * The SSAO PostProcess id in the pipeline
  83716. */
  83717. _this.SSAORenderEffect = "SSAORenderEffect";
  83718. /**
  83719. * @ignore
  83720. * The horizontal blur PostProcess id in the pipeline
  83721. */
  83722. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83723. /**
  83724. * @ignore
  83725. * The vertical blur PostProcess id in the pipeline
  83726. */
  83727. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83728. /**
  83729. * @ignore
  83730. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83731. */
  83732. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83733. /**
  83734. * The output strength of the SSAO post-process. Default value is 1.0.
  83735. */
  83736. _this.totalStrength = 1.0;
  83737. /**
  83738. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  83739. */
  83740. _this.radius = 0.0001;
  83741. /**
  83742. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  83743. * Must not be equal to fallOff and superior to fallOff.
  83744. * Default value is 0.975
  83745. */
  83746. _this.area = 0.0075;
  83747. /**
  83748. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  83749. * Must not be equal to area and inferior to area.
  83750. * Default value is 0.0
  83751. */
  83752. _this.fallOff = 0.000001;
  83753. /**
  83754. * The base color of the SSAO post-process
  83755. * The final result is "base + ssao" between [0, 1]
  83756. */
  83757. _this.base = 0.5;
  83758. _this._firstUpdate = true;
  83759. _this._scene = scene;
  83760. // Set up assets
  83761. _this._createRandomTexture();
  83762. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  83763. var ssaoRatio = ratio.ssaoRatio || ratio;
  83764. var combineRatio = ratio.combineRatio || ratio;
  83765. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83766. _this._createSSAOPostProcess(ssaoRatio);
  83767. _this._createBlurPostProcess(ssaoRatio);
  83768. _this._createSSAOCombinePostProcess(combineRatio);
  83769. // Set up pipeline
  83770. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83771. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  83772. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  83773. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  83774. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  83775. // Finish
  83776. scene.postProcessRenderPipelineManager.addPipeline(_this);
  83777. if (cameras)
  83778. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  83779. return _this;
  83780. }
  83781. // Public Methods
  83782. /**
  83783. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  83784. */
  83785. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  83786. if (disableDepthRender === void 0) { disableDepthRender = false; }
  83787. for (var i = 0; i < this._scene.cameras.length; i++) {
  83788. var camera = this._scene.cameras[i];
  83789. this._originalColorPostProcess.dispose(camera);
  83790. this._ssaoPostProcess.dispose(camera);
  83791. this._blurHPostProcess.dispose(camera);
  83792. this._blurVPostProcess.dispose(camera);
  83793. this._ssaoCombinePostProcess.dispose(camera);
  83794. }
  83795. this._randomTexture.dispose();
  83796. if (disableDepthRender)
  83797. this._scene.disableDepthRenderer();
  83798. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  83799. _super.prototype.dispose.call(this);
  83800. };
  83801. // Private Methods
  83802. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  83803. var _this = this;
  83804. var size = 16;
  83805. 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);
  83806. 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);
  83807. this._blurHPostProcess.onActivateObservable.add(function () {
  83808. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  83809. _this._blurHPostProcess.kernel = size * dw;
  83810. });
  83811. this._blurVPostProcess.onActivateObservable.add(function () {
  83812. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  83813. _this._blurVPostProcess.kernel = size * dw;
  83814. });
  83815. };
  83816. /** @hidden */
  83817. SSAORenderingPipeline.prototype._rebuild = function () {
  83818. this._firstUpdate = true;
  83819. _super.prototype._rebuild.call(this);
  83820. };
  83821. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  83822. var _this = this;
  83823. var numSamples = 16;
  83824. var sampleSphere = [
  83825. 0.5381, 0.1856, -0.4319,
  83826. 0.1379, 0.2486, 0.4430,
  83827. 0.3371, 0.5679, -0.0057,
  83828. -0.6999, -0.0451, -0.0019,
  83829. 0.0689, -0.1598, -0.8547,
  83830. 0.0560, 0.0069, -0.1843,
  83831. -0.0146, 0.1402, 0.0762,
  83832. 0.0100, -0.1924, -0.0344,
  83833. -0.3577, -0.5301, -0.4358,
  83834. -0.3169, 0.1063, 0.0158,
  83835. 0.0103, -0.5869, 0.0046,
  83836. -0.0897, -0.4940, 0.3287,
  83837. 0.7119, -0.0154, -0.0918,
  83838. -0.0533, 0.0596, -0.5411,
  83839. 0.0352, -0.0631, 0.5460,
  83840. -0.4776, 0.2847, -0.0271
  83841. ];
  83842. var samplesFactor = 1.0 / numSamples;
  83843. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  83844. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  83845. "area", "fallOff", "base", "range", "viewport"
  83846. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  83847. this._ssaoPostProcess.onApply = function (effect) {
  83848. if (_this._firstUpdate) {
  83849. effect.setArray3("sampleSphere", sampleSphere);
  83850. effect.setFloat("samplesFactor", samplesFactor);
  83851. effect.setFloat("randTextureTiles", 4.0);
  83852. }
  83853. effect.setFloat("totalStrength", _this.totalStrength);
  83854. effect.setFloat("radius", _this.radius);
  83855. effect.setFloat("area", _this.area);
  83856. effect.setFloat("fallOff", _this.fallOff);
  83857. effect.setFloat("base", _this.base);
  83858. effect.setTexture("textureSampler", _this._depthTexture);
  83859. effect.setTexture("randomSampler", _this._randomTexture);
  83860. };
  83861. };
  83862. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  83863. var _this = this;
  83864. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  83865. this._ssaoCombinePostProcess.onApply = function (effect) {
  83866. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  83867. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  83868. };
  83869. };
  83870. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  83871. var size = 512;
  83872. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  83873. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  83874. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  83875. var context = this._randomTexture.getContext();
  83876. var rand = function (min, max) {
  83877. return Math.random() * (max - min) + min;
  83878. };
  83879. var randVector = BABYLON.Vector3.Zero();
  83880. for (var x = 0; x < size; x++) {
  83881. for (var y = 0; y < size; y++) {
  83882. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  83883. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  83884. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  83885. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  83886. context.fillRect(x, y, 1, 1);
  83887. }
  83888. }
  83889. this._randomTexture.update(false);
  83890. };
  83891. __decorate([
  83892. BABYLON.serialize()
  83893. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  83894. __decorate([
  83895. BABYLON.serialize()
  83896. ], SSAORenderingPipeline.prototype, "radius", void 0);
  83897. __decorate([
  83898. BABYLON.serialize()
  83899. ], SSAORenderingPipeline.prototype, "area", void 0);
  83900. __decorate([
  83901. BABYLON.serialize()
  83902. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  83903. __decorate([
  83904. BABYLON.serialize()
  83905. ], SSAORenderingPipeline.prototype, "base", void 0);
  83906. return SSAORenderingPipeline;
  83907. }(BABYLON.PostProcessRenderPipeline));
  83908. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  83909. })(BABYLON || (BABYLON = {}));
  83910. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  83911. var BABYLON;
  83912. (function (BABYLON) {
  83913. /**
  83914. * Render pipeline to produce ssao effect
  83915. */
  83916. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  83917. __extends(SSAO2RenderingPipeline, _super);
  83918. /**
  83919. * @constructor
  83920. * @param name The rendering pipeline name
  83921. * @param scene The scene linked to this pipeline
  83922. * @param 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 }
  83923. * @param cameras The array of cameras that the rendering pipeline will be attached to
  83924. */
  83925. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  83926. var _this = _super.call(this, scene.getEngine(), name) || this;
  83927. // Members
  83928. /**
  83929. * @ignore
  83930. * The PassPostProcess id in the pipeline that contains the original scene color
  83931. */
  83932. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  83933. /**
  83934. * @ignore
  83935. * The SSAO PostProcess id in the pipeline
  83936. */
  83937. _this.SSAORenderEffect = "SSAORenderEffect";
  83938. /**
  83939. * @ignore
  83940. * The horizontal blur PostProcess id in the pipeline
  83941. */
  83942. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  83943. /**
  83944. * @ignore
  83945. * The vertical blur PostProcess id in the pipeline
  83946. */
  83947. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  83948. /**
  83949. * @ignore
  83950. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  83951. */
  83952. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  83953. /**
  83954. * The output strength of the SSAO post-process. Default value is 1.0.
  83955. */
  83956. _this.totalStrength = 1.0;
  83957. /**
  83958. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  83959. */
  83960. _this.maxZ = 100.0;
  83961. /**
  83962. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  83963. */
  83964. _this.minZAspect = 0.2;
  83965. _this._samples = 8;
  83966. _this._textureSamples = 1;
  83967. _this._expensiveBlur = true;
  83968. /**
  83969. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  83970. */
  83971. _this.radius = 2.0;
  83972. /**
  83973. * The base color of the SSAO post-process
  83974. * The final result is "base + ssao" between [0, 1]
  83975. */
  83976. _this.base = 0;
  83977. _this._firstUpdate = true;
  83978. _this._bits = new Uint32Array(1);
  83979. _this._scene = scene;
  83980. _this._ratio = ratio;
  83981. if (!_this.isSupported) {
  83982. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  83983. return _this;
  83984. }
  83985. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  83986. var blurRatio = _this._ratio.blurRatio || ratio;
  83987. // Set up assets
  83988. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  83989. _this._createRandomTexture();
  83990. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  83991. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  83992. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  83993. _this._originalColorPostProcess.samples = _this.textureSamples;
  83994. _this._createSSAOPostProcess(1.0);
  83995. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  83996. _this._createSSAOCombinePostProcess(blurRatio);
  83997. // Set up pipeline
  83998. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  83999. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  84000. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  84001. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  84002. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  84003. // Finish
  84004. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84005. if (cameras)
  84006. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84007. return _this;
  84008. }
  84009. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  84010. get: function () {
  84011. return this._samples;
  84012. },
  84013. /**
  84014. * Number of samples used for the SSAO calculations. Default value is 8
  84015. */
  84016. set: function (n) {
  84017. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  84018. this._samples = n;
  84019. this._sampleSphere = this._generateHemisphere();
  84020. this._firstUpdate = true;
  84021. },
  84022. enumerable: true,
  84023. configurable: true
  84024. });
  84025. Object.defineProperty(SSAO2RenderingPipeline.prototype, "textureSamples", {
  84026. get: function () {
  84027. return this._textureSamples;
  84028. },
  84029. /**
  84030. * Number of samples to use for antialiasing
  84031. */
  84032. set: function (n) {
  84033. this._textureSamples = n;
  84034. this._originalColorPostProcess.samples = n;
  84035. this._blurHPostProcess.samples = n;
  84036. this._blurVPostProcess.samples = n;
  84037. this._ssaoPostProcess.samples = n;
  84038. this._ssaoCombinePostProcess.samples = n;
  84039. },
  84040. enumerable: true,
  84041. configurable: true
  84042. });
  84043. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  84044. get: function () {
  84045. return this._expensiveBlur;
  84046. },
  84047. /**
  84048. * If bilateral blur should be used
  84049. */
  84050. set: function (b) {
  84051. 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"]);
  84052. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  84053. this._expensiveBlur = b;
  84054. this._firstUpdate = true;
  84055. },
  84056. enumerable: true,
  84057. configurable: true
  84058. });
  84059. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  84060. /**
  84061. * Support test.
  84062. */
  84063. get: function () {
  84064. var engine = BABYLON.Engine.LastCreatedEngine;
  84065. if (!engine) {
  84066. return false;
  84067. }
  84068. return engine.getCaps().drawBuffersExtension;
  84069. },
  84070. enumerable: true,
  84071. configurable: true
  84072. });
  84073. // Public Methods
  84074. /**
  84075. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  84076. */
  84077. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  84078. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  84079. for (var i = 0; i < this._scene.cameras.length; i++) {
  84080. var camera = this._scene.cameras[i];
  84081. this._originalColorPostProcess.dispose(camera);
  84082. this._ssaoPostProcess.dispose(camera);
  84083. this._blurHPostProcess.dispose(camera);
  84084. this._blurVPostProcess.dispose(camera);
  84085. this._ssaoCombinePostProcess.dispose(camera);
  84086. }
  84087. this._randomTexture.dispose();
  84088. if (disableGeometryBufferRenderer)
  84089. this._scene.disableGeometryBufferRenderer();
  84090. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84091. _super.prototype.dispose.call(this);
  84092. };
  84093. // Private Methods
  84094. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  84095. var _this = this;
  84096. this._samplerOffsets = [];
  84097. var expensive = this.expensiveBlur;
  84098. for (var i = -8; i < 8; i++) {
  84099. this._samplerOffsets.push(i * 2 + 0.5);
  84100. }
  84101. 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");
  84102. this._blurHPostProcess.onApply = function (effect) {
  84103. if (!_this._scene.activeCamera) {
  84104. return;
  84105. }
  84106. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  84107. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84108. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84109. effect.setFloat("radius", _this.radius);
  84110. effect.setTexture("depthSampler", _this._depthTexture);
  84111. if (_this._firstUpdate) {
  84112. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84113. }
  84114. };
  84115. 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");
  84116. this._blurVPostProcess.onApply = function (effect) {
  84117. if (!_this._scene.activeCamera) {
  84118. return;
  84119. }
  84120. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  84121. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84122. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84123. effect.setFloat("radius", _this.radius);
  84124. effect.setTexture("depthSampler", _this._depthTexture);
  84125. if (_this._firstUpdate) {
  84126. effect.setArray("samplerOffsets", _this._samplerOffsets);
  84127. _this._firstUpdate = false;
  84128. }
  84129. };
  84130. this._blurHPostProcess.samples = this.textureSamples;
  84131. this._blurVPostProcess.samples = this.textureSamples;
  84132. };
  84133. /** @hidden */
  84134. SSAO2RenderingPipeline.prototype._rebuild = function () {
  84135. this._firstUpdate = true;
  84136. _super.prototype._rebuild.call(this);
  84137. };
  84138. //Van der Corput radical inverse
  84139. SSAO2RenderingPipeline.prototype._radicalInverse_VdC = function (i) {
  84140. this._bits[0] = i;
  84141. this._bits[0] = ((this._bits[0] << 16) | (this._bits[0] >> 16)) >>> 0;
  84142. this._bits[0] = ((this._bits[0] & 0x55555555) << 1) | ((this._bits[0] & 0xAAAAAAAA) >>> 1) >>> 0;
  84143. this._bits[0] = ((this._bits[0] & 0x33333333) << 2) | ((this._bits[0] & 0xCCCCCCCC) >>> 2) >>> 0;
  84144. this._bits[0] = ((this._bits[0] & 0x0F0F0F0F) << 4) | ((this._bits[0] & 0xF0F0F0F0) >>> 4) >>> 0;
  84145. this._bits[0] = ((this._bits[0] & 0x00FF00FF) << 8) | ((this._bits[0] & 0xFF00FF00) >>> 8) >>> 0;
  84146. return this._bits[0] * 2.3283064365386963e-10; // / 0x100000000 or / 4294967296
  84147. };
  84148. SSAO2RenderingPipeline.prototype._hammersley = function (i, n) {
  84149. return [i / n, this._radicalInverse_VdC(i)];
  84150. };
  84151. SSAO2RenderingPipeline.prototype._hemisphereSample_uniform = function (u, v) {
  84152. var phi = v * 2.0 * Math.PI;
  84153. // rejecting samples that are close to tangent plane to avoid z-fighting artifacts
  84154. var cosTheta = 1.0 - (u * 0.85 + 0.15);
  84155. var sinTheta = Math.sqrt(1.0 - cosTheta * cosTheta);
  84156. return new BABYLON.Vector3(Math.cos(phi) * sinTheta, Math.sin(phi) * sinTheta, cosTheta);
  84157. };
  84158. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  84159. var numSamples = this.samples;
  84160. var result = [];
  84161. var vector;
  84162. var i = 0;
  84163. while (i < numSamples) {
  84164. if (numSamples < 16) {
  84165. vector = this._hemisphereSample_uniform(Math.random(), Math.random());
  84166. }
  84167. else {
  84168. var rand = this._hammersley(i, numSamples);
  84169. vector = this._hemisphereSample_uniform(rand[0], rand[1]);
  84170. }
  84171. result.push(vector.x, vector.y, vector.z);
  84172. i++;
  84173. }
  84174. return result;
  84175. };
  84176. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  84177. var _this = this;
  84178. var numSamples = this.samples;
  84179. this._sampleSphere = this._generateHemisphere();
  84180. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  84181. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  84182. "base", "range", "projection", "near", "far", "texelSize",
  84183. "xViewport", "yViewport", "maxZ", "minZAspect"
  84184. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  84185. this._ssaoPostProcess.onApply = function (effect) {
  84186. if (_this._firstUpdate) {
  84187. effect.setArray3("sampleSphere", _this._sampleSphere);
  84188. effect.setFloat("randTextureTiles", 32.0);
  84189. }
  84190. if (!_this._scene.activeCamera) {
  84191. return;
  84192. }
  84193. effect.setFloat("samplesFactor", 1 / _this.samples);
  84194. effect.setFloat("totalStrength", _this.totalStrength);
  84195. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  84196. effect.setFloat("radius", _this.radius);
  84197. effect.setFloat("maxZ", _this.maxZ);
  84198. effect.setFloat("minZAspect", _this.minZAspect);
  84199. effect.setFloat("base", _this.base);
  84200. effect.setFloat("near", _this._scene.activeCamera.minZ);
  84201. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  84202. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  84203. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  84204. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  84205. effect.setTexture("textureSampler", _this._depthTexture);
  84206. effect.setTexture("normalSampler", _this._normalTexture);
  84207. effect.setTexture("randomSampler", _this._randomTexture);
  84208. };
  84209. this._ssaoPostProcess.samples = this.textureSamples;
  84210. };
  84211. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  84212. var _this = this;
  84213. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84214. this._ssaoCombinePostProcess.onApply = function (effect) {
  84215. var viewport = _this._scene.activeCamera.viewport;
  84216. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  84217. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  84218. };
  84219. this._ssaoCombinePostProcess.samples = this.textureSamples;
  84220. };
  84221. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  84222. var size = 128;
  84223. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  84224. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84225. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84226. var context = this._randomTexture.getContext();
  84227. var rand = function (min, max) {
  84228. return Math.random() * (max - min) + min;
  84229. };
  84230. var randVector = BABYLON.Vector3.Zero();
  84231. for (var x = 0; x < size; x++) {
  84232. for (var y = 0; y < size; y++) {
  84233. randVector.x = rand(0.0, 1.0);
  84234. randVector.y = rand(0.0, 1.0);
  84235. randVector.z = 0.0;
  84236. randVector.normalize();
  84237. randVector.scaleInPlace(255);
  84238. randVector.x = Math.floor(randVector.x);
  84239. randVector.y = Math.floor(randVector.y);
  84240. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  84241. context.fillRect(x, y, 1, 1);
  84242. }
  84243. }
  84244. this._randomTexture.update(false);
  84245. };
  84246. /**
  84247. * Serialize the rendering pipeline (Used when exporting)
  84248. * @returns the serialized object
  84249. */
  84250. SSAO2RenderingPipeline.prototype.serialize = function () {
  84251. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  84252. serializationObject.customType = "SSAO2RenderingPipeline";
  84253. return serializationObject;
  84254. };
  84255. /**
  84256. * Parse the serialized pipeline
  84257. * @param source Source pipeline.
  84258. * @param scene The scene to load the pipeline to.
  84259. * @param rootUrl The URL of the serialized pipeline.
  84260. * @returns An instantiated pipeline from the serialized object.
  84261. */
  84262. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  84263. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  84264. };
  84265. __decorate([
  84266. BABYLON.serialize()
  84267. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  84268. __decorate([
  84269. BABYLON.serialize()
  84270. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  84271. __decorate([
  84272. BABYLON.serialize()
  84273. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  84274. __decorate([
  84275. BABYLON.serialize("samples")
  84276. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  84277. __decorate([
  84278. BABYLON.serialize("textureSamples")
  84279. ], SSAO2RenderingPipeline.prototype, "_textureSamples", void 0);
  84280. __decorate([
  84281. BABYLON.serialize()
  84282. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  84283. __decorate([
  84284. BABYLON.serialize("expensiveBlur")
  84285. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  84286. __decorate([
  84287. BABYLON.serialize()
  84288. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  84289. __decorate([
  84290. BABYLON.serialize()
  84291. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  84292. return SSAO2RenderingPipeline;
  84293. }(BABYLON.PostProcessRenderPipeline));
  84294. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  84295. })(BABYLON || (BABYLON = {}));
  84296. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  84297. var BABYLON;
  84298. (function (BABYLON) {
  84299. /**
  84300. * BABYLON.JS Chromatic Aberration GLSL Shader
  84301. * Author: Olivier Guyot
  84302. * Separates very slightly R, G and B colors on the edges of the screen
  84303. * Inspired by Francois Tarlier & Martins Upitis
  84304. */
  84305. var LensRenderingPipeline = /** @class */ (function (_super) {
  84306. __extends(LensRenderingPipeline, _super);
  84307. /**
  84308. * @constructor
  84309. *
  84310. * Effect parameters are as follow:
  84311. * {
  84312. * chromatic_aberration: number; // from 0 to x (1 for realism)
  84313. * edge_blur: number; // from 0 to x (1 for realism)
  84314. * distortion: number; // from 0 to x (1 for realism)
  84315. * grain_amount: number; // from 0 to 1
  84316. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  84317. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  84318. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  84319. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  84320. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  84321. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  84322. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  84323. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  84324. * }
  84325. * Note: if an effect parameter is unset, effect is disabled
  84326. *
  84327. * @param name The rendering pipeline name
  84328. * @param parameters - An object containing all parameters (see above)
  84329. * @param scene The scene linked to this pipeline
  84330. * @param 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)
  84331. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84332. */
  84333. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  84334. if (ratio === void 0) { ratio = 1.0; }
  84335. var _this = _super.call(this, scene.getEngine(), name) || this;
  84336. // Lens effects can be of the following:
  84337. // - chromatic aberration (slight shift of RGB colors)
  84338. // - blur on the edge of the lens
  84339. // - lens distortion
  84340. // - depth-of-field blur & highlights enhancing
  84341. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  84342. // - grain effect (noise or custom texture)
  84343. // Two additional texture samplers are needed:
  84344. // - depth map (for depth-of-field)
  84345. // - grain texture
  84346. /**
  84347. * @ignore
  84348. * The chromatic aberration PostProcess id in the pipeline
  84349. */
  84350. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  84351. /**
  84352. * @ignore
  84353. * The highlights enhancing PostProcess id in the pipeline
  84354. */
  84355. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  84356. /**
  84357. * @ignore
  84358. * The depth-of-field PostProcess id in the pipeline
  84359. */
  84360. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  84361. _this._scene = scene;
  84362. // Fetch texture samplers
  84363. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  84364. if (parameters.grain_texture) {
  84365. _this._grainTexture = parameters.grain_texture;
  84366. }
  84367. else {
  84368. _this._createGrainTexture();
  84369. }
  84370. // save parameters
  84371. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  84372. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  84373. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  84374. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  84375. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  84376. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  84377. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  84378. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  84379. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  84380. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  84381. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  84382. // Create effects
  84383. _this._createChromaticAberrationPostProcess(ratio);
  84384. _this._createHighlightsPostProcess(ratio);
  84385. _this._createDepthOfFieldPostProcess(ratio / 4);
  84386. // Set up pipeline
  84387. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  84388. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  84389. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  84390. if (_this._highlightsGain === -1) {
  84391. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  84392. }
  84393. // Finish
  84394. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84395. if (cameras) {
  84396. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  84397. }
  84398. return _this;
  84399. }
  84400. // public methods (self explanatory)
  84401. /**
  84402. * Sets the amount of blur at the edges
  84403. * @param amount blur amount
  84404. */
  84405. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  84406. /**
  84407. * Sets edge blur to 0
  84408. */
  84409. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  84410. /**
  84411. * Sets the amout of grain
  84412. * @param amount Amount of grain
  84413. */
  84414. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  84415. /**
  84416. * Set grain amount to 0
  84417. */
  84418. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  84419. /**
  84420. * Sets the chromatic aberration amount
  84421. * @param amount amount of chromatic aberration
  84422. */
  84423. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  84424. /**
  84425. * Sets chromatic aberration amount to 0
  84426. */
  84427. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  84428. /**
  84429. * Sets the EdgeDistortion amount
  84430. * @param amount amount of EdgeDistortion
  84431. */
  84432. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  84433. /**
  84434. * Sets edge distortion to 0
  84435. */
  84436. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  84437. /**
  84438. * Sets the FocusDistance amount
  84439. * @param amount amount of FocusDistance
  84440. */
  84441. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  84442. /**
  84443. * Disables depth of field
  84444. */
  84445. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  84446. /**
  84447. * Sets the Aperture amount
  84448. * @param amount amount of Aperture
  84449. */
  84450. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  84451. /**
  84452. * Sets the DarkenOutOfFocus amount
  84453. * @param amount amount of DarkenOutOfFocus
  84454. */
  84455. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  84456. /**
  84457. * Creates a pentagon bokeh effect
  84458. */
  84459. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  84460. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  84461. };
  84462. /**
  84463. * Disables the pentagon bokeh effect
  84464. */
  84465. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  84466. this._highlightsPostProcess.updateEffect();
  84467. };
  84468. /**
  84469. * Enables noise blur
  84470. */
  84471. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  84472. /**
  84473. * Disables noise blur
  84474. */
  84475. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  84476. /**
  84477. * Sets the HighlightsGain amount
  84478. * @param amount amount of HighlightsGain
  84479. */
  84480. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  84481. this._highlightsGain = amount;
  84482. };
  84483. /**
  84484. * Sets the HighlightsThreshold amount
  84485. * @param amount amount of HighlightsThreshold
  84486. */
  84487. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  84488. if (this._highlightsGain === -1) {
  84489. this._highlightsGain = 1.0;
  84490. }
  84491. this._highlightsThreshold = amount;
  84492. };
  84493. /**
  84494. * Disables highlights
  84495. */
  84496. LensRenderingPipeline.prototype.disableHighlights = function () {
  84497. this._highlightsGain = -1;
  84498. };
  84499. /**
  84500. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  84501. * @param disableDepthRender If the scens depth rendering should be disabled (default: false)
  84502. */
  84503. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  84504. if (disableDepthRender === void 0) { disableDepthRender = false; }
  84505. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  84506. this._chromaticAberrationPostProcess = null;
  84507. this._highlightsPostProcess = null;
  84508. this._depthOfFieldPostProcess = null;
  84509. this._grainTexture.dispose();
  84510. if (disableDepthRender)
  84511. this._scene.disableDepthRenderer();
  84512. };
  84513. // colors shifting and distortion
  84514. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  84515. var _this = this;
  84516. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  84517. [], // samplers
  84518. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84519. this._chromaticAberrationPostProcess.onApply = function (effect) {
  84520. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  84521. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84522. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84523. effect.setFloat('radialIntensity', 1);
  84524. effect.setFloat2('direction', 17, 17);
  84525. effect.setFloat2('centerPosition', 0.5, 0.5);
  84526. };
  84527. };
  84528. // highlights enhancing
  84529. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  84530. var _this = this;
  84531. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  84532. [], // samplers
  84533. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  84534. this._highlightsPostProcess.onApply = function (effect) {
  84535. effect.setFloat('gain', _this._highlightsGain);
  84536. effect.setFloat('threshold', _this._highlightsThreshold);
  84537. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  84538. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84539. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84540. };
  84541. };
  84542. // colors shifting and distortion
  84543. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  84544. var _this = this;
  84545. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  84546. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  84547. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  84548. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  84549. this._depthOfFieldPostProcess.onApply = function (effect) {
  84550. effect.setTexture("depthSampler", _this._depthTexture);
  84551. effect.setTexture("grainSampler", _this._grainTexture);
  84552. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  84553. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  84554. effect.setFloat('grain_amount', _this._grainAmount);
  84555. effect.setBool('blur_noise', _this._blurNoise);
  84556. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  84557. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  84558. effect.setFloat('distortion', _this._distortion);
  84559. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  84560. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  84561. effect.setFloat('aperture', _this._dofAperture);
  84562. effect.setFloat('darken', _this._dofDarken);
  84563. effect.setFloat('edge_blur', _this._edgeBlur);
  84564. effect.setBool('highlights', (_this._highlightsGain !== -1));
  84565. if (_this._scene.activeCamera) {
  84566. effect.setFloat('near', _this._scene.activeCamera.minZ);
  84567. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  84568. }
  84569. };
  84570. };
  84571. // creates a black and white random noise texture, 512x512
  84572. LensRenderingPipeline.prototype._createGrainTexture = function () {
  84573. var size = 512;
  84574. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  84575. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  84576. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  84577. var context = this._grainTexture.getContext();
  84578. var rand = function (min, max) {
  84579. return Math.random() * (max - min) + min;
  84580. };
  84581. var value;
  84582. for (var x = 0; x < size; x++) {
  84583. for (var y = 0; y < size; y++) {
  84584. value = Math.floor(rand(0.42, 0.58) * 255);
  84585. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  84586. context.fillRect(x, y, 1, 1);
  84587. }
  84588. }
  84589. this._grainTexture.update(false);
  84590. };
  84591. return LensRenderingPipeline;
  84592. }(BABYLON.PostProcessRenderPipeline));
  84593. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  84594. })(BABYLON || (BABYLON = {}));
  84595. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  84596. var BABYLON;
  84597. (function (BABYLON) {
  84598. /**
  84599. * Standard rendering pipeline
  84600. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84601. * @see https://doc.babylonjs.com/how_to/using_standard_rendering_pipeline
  84602. */
  84603. var StandardRenderingPipeline = /** @class */ (function (_super) {
  84604. __extends(StandardRenderingPipeline, _super);
  84605. /**
  84606. * Default pipeline should be used going forward but the standard pipeline will be kept for backwards compatibility.
  84607. * @constructor
  84608. * @param name The rendering pipeline name
  84609. * @param scene The scene linked to this pipeline
  84610. * @param 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)
  84611. * @param originalPostProcess the custom original color post-process. Must be "reusable". Can be null.
  84612. * @param cameras The array of cameras that the rendering pipeline will be attached to
  84613. */
  84614. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  84615. if (originalPostProcess === void 0) { originalPostProcess = null; }
  84616. var _this = _super.call(this, scene.getEngine(), name) || this;
  84617. /**
  84618. * Post-process used to down scale an image x4
  84619. */
  84620. _this.downSampleX4PostProcess = null;
  84621. /**
  84622. * Post-process used to calculate the illuminated surfaces controlled by a threshold
  84623. */
  84624. _this.brightPassPostProcess = null;
  84625. /**
  84626. * Post-process array storing all the horizontal blur post-processes used by the pipeline
  84627. */
  84628. _this.blurHPostProcesses = [];
  84629. /**
  84630. * Post-process array storing all the vertical blur post-processes used by the pipeline
  84631. */
  84632. _this.blurVPostProcesses = [];
  84633. /**
  84634. * Post-process used to add colors of 2 textures (typically brightness + real scene color)
  84635. */
  84636. _this.textureAdderPostProcess = null;
  84637. /**
  84638. * Post-process used to create volumetric lighting effect
  84639. */
  84640. _this.volumetricLightPostProcess = null;
  84641. /**
  84642. * Post-process used to smooth the previous volumetric light post-process on the X axis
  84643. */
  84644. _this.volumetricLightSmoothXPostProcess = null;
  84645. /**
  84646. * Post-process used to smooth the previous volumetric light post-process on the Y axis
  84647. */
  84648. _this.volumetricLightSmoothYPostProcess = null;
  84649. /**
  84650. * Post-process used to merge the volumetric light effect and the real scene color
  84651. */
  84652. _this.volumetricLightMergePostProces = null;
  84653. /**
  84654. * Post-process used to store the final volumetric light post-process (attach/detach for debug purpose)
  84655. */
  84656. _this.volumetricLightFinalPostProcess = null;
  84657. /**
  84658. * Base post-process used to calculate the average luminance of the final image for HDR
  84659. */
  84660. _this.luminancePostProcess = null;
  84661. /**
  84662. * Post-processes used to create down sample post-processes in order to get
  84663. * the average luminance of the final image for HDR
  84664. * Array of length "StandardRenderingPipeline.LuminanceSteps"
  84665. */
  84666. _this.luminanceDownSamplePostProcesses = [];
  84667. /**
  84668. * Post-process used to create a HDR effect (light adaptation)
  84669. */
  84670. _this.hdrPostProcess = null;
  84671. /**
  84672. * Post-process used to store the final texture adder post-process (attach/detach for debug purpose)
  84673. */
  84674. _this.textureAdderFinalPostProcess = null;
  84675. /**
  84676. * Post-process used to store the final lens flare post-process (attach/detach for debug purpose)
  84677. */
  84678. _this.lensFlareFinalPostProcess = null;
  84679. /**
  84680. * Post-process used to merge the final HDR post-process and the real scene color
  84681. */
  84682. _this.hdrFinalPostProcess = null;
  84683. /**
  84684. * Post-process used to create a lens flare effect
  84685. */
  84686. _this.lensFlarePostProcess = null;
  84687. /**
  84688. * Post-process that merges the result of the lens flare post-process and the real scene color
  84689. */
  84690. _this.lensFlareComposePostProcess = null;
  84691. /**
  84692. * Post-process used to create a motion blur effect
  84693. */
  84694. _this.motionBlurPostProcess = null;
  84695. /**
  84696. * Post-process used to create a depth of field effect
  84697. */
  84698. _this.depthOfFieldPostProcess = null;
  84699. /**
  84700. * The Fast Approximate Anti-Aliasing post process which attemps to remove aliasing from an image.
  84701. */
  84702. _this.fxaaPostProcess = null;
  84703. // Values
  84704. /**
  84705. * Represents the brightness threshold in order to configure the illuminated surfaces
  84706. */
  84707. _this.brightThreshold = 1.0;
  84708. /**
  84709. * Configures the blur intensity used for surexposed surfaces are highlighted surfaces (light halo)
  84710. */
  84711. _this.blurWidth = 512.0;
  84712. /**
  84713. * Sets if the blur for highlighted surfaces must be only horizontal
  84714. */
  84715. _this.horizontalBlur = false;
  84716. /**
  84717. * Sets the overall exposure used by the pipeline
  84718. */
  84719. _this.exposure = 1.0;
  84720. /**
  84721. * Texture used typically to simulate "dirty" on camera lens
  84722. */
  84723. _this.lensTexture = null;
  84724. /**
  84725. * Represents the offset coefficient based on Rayleigh principle. Typically in interval [-0.2, 0.2]
  84726. */
  84727. _this.volumetricLightCoefficient = 0.2;
  84728. /**
  84729. * The overall power of volumetric lights, typically in interval [0, 10] maximum
  84730. */
  84731. _this.volumetricLightPower = 4.0;
  84732. /**
  84733. * Used the set the blur intensity to smooth the volumetric lights
  84734. */
  84735. _this.volumetricLightBlurScale = 64.0;
  84736. /**
  84737. * Light (spot or directional) used to generate the volumetric lights rays
  84738. * The source light must have a shadow generate so the pipeline can get its
  84739. * depth map
  84740. */
  84741. _this.sourceLight = null;
  84742. /**
  84743. * For eye adaptation, represents the minimum luminance the eye can see
  84744. */
  84745. _this.hdrMinimumLuminance = 1.0;
  84746. /**
  84747. * For eye adaptation, represents the decrease luminance speed
  84748. */
  84749. _this.hdrDecreaseRate = 0.5;
  84750. /**
  84751. * For eye adaptation, represents the increase luminance speed
  84752. */
  84753. _this.hdrIncreaseRate = 0.5;
  84754. /**
  84755. * Lens color texture used by the lens flare effect. Mandatory if lens flare effect enabled
  84756. */
  84757. _this.lensColorTexture = null;
  84758. /**
  84759. * The overall strengh for the lens flare effect
  84760. */
  84761. _this.lensFlareStrength = 20.0;
  84762. /**
  84763. * Dispersion coefficient for lens flare ghosts
  84764. */
  84765. _this.lensFlareGhostDispersal = 1.4;
  84766. /**
  84767. * Main lens flare halo width
  84768. */
  84769. _this.lensFlareHaloWidth = 0.7;
  84770. /**
  84771. * Based on the lens distortion effect, defines how much the lens flare result
  84772. * is distorted
  84773. */
  84774. _this.lensFlareDistortionStrength = 16.0;
  84775. /**
  84776. * Lens star texture must be used to simulate rays on the flares and is available
  84777. * in the documentation
  84778. */
  84779. _this.lensStarTexture = null;
  84780. /**
  84781. * As the "lensTexture" (can be the same texture or different), it is used to apply the lens
  84782. * flare effect by taking account of the dirt texture
  84783. */
  84784. _this.lensFlareDirtTexture = null;
  84785. /**
  84786. * Represents the focal length for the depth of field effect
  84787. */
  84788. _this.depthOfFieldDistance = 10.0;
  84789. /**
  84790. * Represents the blur intensity for the blurred part of the depth of field effect
  84791. */
  84792. _this.depthOfFieldBlurWidth = 64.0;
  84793. /**
  84794. * For motion blur, defines how much the image is blurred by the movement
  84795. */
  84796. _this.motionStrength = 1.0;
  84797. /**
  84798. * List of animations for the pipeline (IAnimatable implementation)
  84799. */
  84800. _this.animations = [];
  84801. _this._currentDepthOfFieldSource = null;
  84802. _this._hdrCurrentLuminance = 1.0;
  84803. // Getters and setters
  84804. _this._bloomEnabled = false;
  84805. _this._depthOfFieldEnabled = false;
  84806. _this._vlsEnabled = false;
  84807. _this._lensFlareEnabled = false;
  84808. _this._hdrEnabled = false;
  84809. _this._motionBlurEnabled = false;
  84810. _this._fxaaEnabled = false;
  84811. _this._motionBlurSamples = 64.0;
  84812. _this._volumetricLightStepsCount = 50.0;
  84813. _this._samples = 1;
  84814. _this._cameras = cameras || [];
  84815. // Initialize
  84816. _this._scene = scene;
  84817. _this._basePostProcess = originalPostProcess;
  84818. _this._ratio = ratio;
  84819. // Misc
  84820. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84821. // Finish
  84822. scene.postProcessRenderPipelineManager.addPipeline(_this);
  84823. _this._buildPipeline();
  84824. return _this;
  84825. }
  84826. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  84827. /**
  84828. * @ignore
  84829. * Specifies if the bloom pipeline is enabled
  84830. */
  84831. get: function () {
  84832. return this._bloomEnabled;
  84833. },
  84834. set: function (enabled) {
  84835. if (this._bloomEnabled === enabled) {
  84836. return;
  84837. }
  84838. this._bloomEnabled = enabled;
  84839. this._buildPipeline();
  84840. },
  84841. enumerable: true,
  84842. configurable: true
  84843. });
  84844. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  84845. /**
  84846. * @ignore
  84847. * Specifies if the depth of field pipeline is enabed
  84848. */
  84849. get: function () {
  84850. return this._depthOfFieldEnabled;
  84851. },
  84852. set: function (enabled) {
  84853. if (this._depthOfFieldEnabled === enabled) {
  84854. return;
  84855. }
  84856. this._depthOfFieldEnabled = enabled;
  84857. this._buildPipeline();
  84858. },
  84859. enumerable: true,
  84860. configurable: true
  84861. });
  84862. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  84863. /**
  84864. * @ignore
  84865. * Specifies if the lens flare pipeline is enabed
  84866. */
  84867. get: function () {
  84868. return this._lensFlareEnabled;
  84869. },
  84870. set: function (enabled) {
  84871. if (this._lensFlareEnabled === enabled) {
  84872. return;
  84873. }
  84874. this._lensFlareEnabled = enabled;
  84875. this._buildPipeline();
  84876. },
  84877. enumerable: true,
  84878. configurable: true
  84879. });
  84880. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  84881. /**
  84882. * @ignore
  84883. * Specifies if the HDR pipeline is enabled
  84884. */
  84885. get: function () {
  84886. return this._hdrEnabled;
  84887. },
  84888. set: function (enabled) {
  84889. if (this._hdrEnabled === enabled) {
  84890. return;
  84891. }
  84892. this._hdrEnabled = enabled;
  84893. this._buildPipeline();
  84894. },
  84895. enumerable: true,
  84896. configurable: true
  84897. });
  84898. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  84899. /**
  84900. * @ignore
  84901. * Specifies if the volumetric lights scattering effect is enabled
  84902. */
  84903. get: function () {
  84904. return this._vlsEnabled;
  84905. },
  84906. set: function (enabled) {
  84907. if (this._vlsEnabled === enabled) {
  84908. return;
  84909. }
  84910. if (enabled) {
  84911. var geometry = this._scene.enableGeometryBufferRenderer();
  84912. if (!geometry) {
  84913. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  84914. return;
  84915. }
  84916. }
  84917. this._vlsEnabled = enabled;
  84918. this._buildPipeline();
  84919. },
  84920. enumerable: true,
  84921. configurable: true
  84922. });
  84923. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  84924. /**
  84925. * @ignore
  84926. * Specifies if the motion blur effect is enabled
  84927. */
  84928. get: function () {
  84929. return this._motionBlurEnabled;
  84930. },
  84931. set: function (enabled) {
  84932. if (this._motionBlurEnabled === enabled) {
  84933. return;
  84934. }
  84935. this._motionBlurEnabled = enabled;
  84936. this._buildPipeline();
  84937. },
  84938. enumerable: true,
  84939. configurable: true
  84940. });
  84941. Object.defineProperty(StandardRenderingPipeline.prototype, "fxaaEnabled", {
  84942. /**
  84943. * Specifies if anti-aliasing is enabled
  84944. */
  84945. get: function () {
  84946. return this._fxaaEnabled;
  84947. },
  84948. set: function (enabled) {
  84949. if (this._fxaaEnabled === enabled) {
  84950. return;
  84951. }
  84952. this._fxaaEnabled = enabled;
  84953. this._buildPipeline();
  84954. },
  84955. enumerable: true,
  84956. configurable: true
  84957. });
  84958. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  84959. /**
  84960. * Specifies the number of steps used to calculate the volumetric lights
  84961. * Typically in interval [50, 200]
  84962. */
  84963. get: function () {
  84964. return this._volumetricLightStepsCount;
  84965. },
  84966. set: function (count) {
  84967. if (this.volumetricLightPostProcess) {
  84968. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  84969. }
  84970. this._volumetricLightStepsCount = count;
  84971. },
  84972. enumerable: true,
  84973. configurable: true
  84974. });
  84975. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  84976. /**
  84977. * Specifies the number of samples used for the motion blur effect
  84978. * Typically in interval [16, 64]
  84979. */
  84980. get: function () {
  84981. return this._motionBlurSamples;
  84982. },
  84983. set: function (samples) {
  84984. if (this.motionBlurPostProcess) {
  84985. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  84986. }
  84987. this._motionBlurSamples = samples;
  84988. },
  84989. enumerable: true,
  84990. configurable: true
  84991. });
  84992. Object.defineProperty(StandardRenderingPipeline.prototype, "samples", {
  84993. /**
  84994. * Specifies MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  84995. */
  84996. get: function () {
  84997. return this._samples;
  84998. },
  84999. set: function (sampleCount) {
  85000. if (this._samples === sampleCount) {
  85001. return;
  85002. }
  85003. this._samples = sampleCount;
  85004. this._buildPipeline();
  85005. },
  85006. enumerable: true,
  85007. configurable: true
  85008. });
  85009. StandardRenderingPipeline.prototype._buildPipeline = function () {
  85010. var _this = this;
  85011. var ratio = this._ratio;
  85012. var scene = this._scene;
  85013. this._disposePostProcesses();
  85014. this._reset();
  85015. // Create pass post-process
  85016. if (!this._basePostProcess) {
  85017. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  85018. this.originalPostProcess.onApply = function (effect) {
  85019. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  85020. };
  85021. }
  85022. else {
  85023. this.originalPostProcess = this._basePostProcess;
  85024. }
  85025. if (this._bloomEnabled || this._vlsEnabled || this._lensFlareEnabled || this._depthOfFieldEnabled || this._motionBlurEnabled) {
  85026. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  85027. }
  85028. this._currentDepthOfFieldSource = this.originalPostProcess;
  85029. if (this._bloomEnabled) {
  85030. // Create down sample X4 post-process
  85031. this._createDownSampleX4PostProcess(scene, ratio / 2);
  85032. // Create bright pass post-process
  85033. this._createBrightPassPostProcess(scene, ratio / 2);
  85034. // Create gaussian blur post-processes (down sampling blurs)
  85035. this._createBlurPostProcesses(scene, ratio / 4, 1);
  85036. // Create texture adder post-process
  85037. this._createTextureAdderPostProcess(scene, ratio);
  85038. // Create depth-of-field source post-process
  85039. 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);
  85040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  85041. }
  85042. if (this._vlsEnabled) {
  85043. // Create volumetric light
  85044. this._createVolumetricLightPostProcess(scene, ratio);
  85045. // Create volumetric light final post-process
  85046. 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);
  85047. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  85048. }
  85049. if (this._lensFlareEnabled) {
  85050. // Create lens flare post-process
  85051. this._createLensFlarePostProcess(scene, ratio);
  85052. // Create depth-of-field source post-process post lens-flare and disable it now
  85053. 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);
  85054. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  85055. }
  85056. if (this._hdrEnabled) {
  85057. // Create luminance
  85058. this._createLuminancePostProcesses(scene, this._floatTextureType);
  85059. // Create HDR
  85060. this._createHdrPostProcess(scene, ratio);
  85061. // Create depth-of-field source post-process post hdr and disable it now
  85062. 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);
  85063. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  85064. }
  85065. if (this._depthOfFieldEnabled) {
  85066. // Create gaussian blur used by depth-of-field
  85067. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  85068. // Create depth-of-field post-process
  85069. this._createDepthOfFieldPostProcess(scene, ratio);
  85070. }
  85071. if (this._motionBlurEnabled) {
  85072. // Create motion blur post-process
  85073. this._createMotionBlurPostProcess(scene, ratio);
  85074. }
  85075. if (this._fxaaEnabled) {
  85076. // Create fxaa post-process
  85077. this.fxaaPostProcess = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  85078. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRFxaa", function () { return _this.fxaaPostProcess; }, true));
  85079. }
  85080. if (this._cameras !== null) {
  85081. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  85082. }
  85083. if (!this._enableMSAAOnFirstPostProcess(this._samples) && this._samples > 1) {
  85084. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  85085. }
  85086. };
  85087. // Down Sample X4 Post-Processs
  85088. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  85089. var _this = this;
  85090. var downSampleX4Offsets = new Array(32);
  85091. 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);
  85092. this.downSampleX4PostProcess.onApply = function (effect) {
  85093. var id = 0;
  85094. var width = _this.downSampleX4PostProcess.width;
  85095. var height = _this.downSampleX4PostProcess.height;
  85096. for (var i = -2; i < 2; i++) {
  85097. for (var j = -2; j < 2; j++) {
  85098. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  85099. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  85100. id += 2;
  85101. }
  85102. }
  85103. effect.setArray2("dsOffsets", downSampleX4Offsets);
  85104. };
  85105. // Add to pipeline
  85106. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  85107. };
  85108. // Brightpass Post-Process
  85109. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  85110. var _this = this;
  85111. var brightOffsets = new Array(8);
  85112. 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);
  85113. this.brightPassPostProcess.onApply = function (effect) {
  85114. var sU = (1.0 / _this.brightPassPostProcess.width);
  85115. var sV = (1.0 / _this.brightPassPostProcess.height);
  85116. brightOffsets[0] = -0.5 * sU;
  85117. brightOffsets[1] = 0.5 * sV;
  85118. brightOffsets[2] = 0.5 * sU;
  85119. brightOffsets[3] = 0.5 * sV;
  85120. brightOffsets[4] = -0.5 * sU;
  85121. brightOffsets[5] = -0.5 * sV;
  85122. brightOffsets[6] = 0.5 * sU;
  85123. brightOffsets[7] = -0.5 * sV;
  85124. effect.setArray2("dsOffsets", brightOffsets);
  85125. effect.setFloat("brightThreshold", _this.brightThreshold);
  85126. };
  85127. // Add to pipeline
  85128. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  85129. };
  85130. // Create blur H&V post-processes
  85131. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  85132. var _this = this;
  85133. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  85134. var engine = scene.getEngine();
  85135. 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);
  85136. 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);
  85137. blurX.onActivateObservable.add(function () {
  85138. var dw = blurX.width / engine.getRenderWidth();
  85139. blurX.kernel = _this[blurWidthKey] * dw;
  85140. });
  85141. blurY.onActivateObservable.add(function () {
  85142. var dw = blurY.height / engine.getRenderHeight();
  85143. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  85144. });
  85145. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  85146. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  85147. this.blurHPostProcesses.push(blurX);
  85148. this.blurVPostProcesses.push(blurY);
  85149. };
  85150. // Create texture adder post-process
  85151. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  85152. var _this = this;
  85153. 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);
  85154. this.textureAdderPostProcess.onApply = function (effect) {
  85155. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  85156. effect.setTexture("lensSampler", _this.lensTexture);
  85157. effect.setFloat("exposure", _this.exposure);
  85158. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  85159. };
  85160. // Add to pipeline
  85161. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  85162. };
  85163. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  85164. var _this = this;
  85165. var geometryRenderer = scene.enableGeometryBufferRenderer();
  85166. geometryRenderer.enablePosition = true;
  85167. var geometry = geometryRenderer.getGBuffer();
  85168. // Base post-process
  85169. 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));
  85170. var depthValues = BABYLON.Vector2.Zero();
  85171. this.volumetricLightPostProcess.onApply = function (effect) {
  85172. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  85173. var generator = _this.sourceLight.getShadowGenerator();
  85174. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  85175. effect.setTexture("positionSampler", geometry.textures[2]);
  85176. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  85177. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  85178. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  85179. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  85180. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  85181. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  85182. depthValues.x = _this.sourceLight.getDepthMinZ(_this._scene.activeCamera);
  85183. depthValues.y = _this.sourceLight.getDepthMaxZ(_this._scene.activeCamera);
  85184. effect.setVector2("depthValues", depthValues);
  85185. }
  85186. };
  85187. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  85188. // Smooth
  85189. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  85190. // Merge
  85191. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  85192. this.volumetricLightMergePostProces.onApply = function (effect) {
  85193. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  85194. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  85195. };
  85196. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  85197. };
  85198. // Create luminance
  85199. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  85200. var _this = this;
  85201. // Create luminance
  85202. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  85203. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  85204. var offsets = [];
  85205. this.luminancePostProcess.onApply = function (effect) {
  85206. var sU = (1.0 / _this.luminancePostProcess.width);
  85207. var sV = (1.0 / _this.luminancePostProcess.height);
  85208. offsets[0] = -0.5 * sU;
  85209. offsets[1] = 0.5 * sV;
  85210. offsets[2] = 0.5 * sU;
  85211. offsets[3] = 0.5 * sV;
  85212. offsets[4] = -0.5 * sU;
  85213. offsets[5] = -0.5 * sV;
  85214. offsets[6] = 0.5 * sU;
  85215. offsets[7] = -0.5 * sV;
  85216. effect.setArray2("lumOffsets", offsets);
  85217. };
  85218. // Add to pipeline
  85219. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  85220. // Create down sample luminance
  85221. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  85222. var size = Math.pow(3, i);
  85223. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  85224. if (i === 0) {
  85225. defines += "#define FINAL_DOWN_SAMPLER";
  85226. }
  85227. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  85228. this.luminanceDownSamplePostProcesses.push(postProcess);
  85229. }
  85230. // Create callbacks and add effects
  85231. var lastLuminance = this.luminancePostProcess;
  85232. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  85233. var downSampleOffsets = new Array(18);
  85234. pp.onApply = function (effect) {
  85235. if (!lastLuminance) {
  85236. return;
  85237. }
  85238. var id = 0;
  85239. for (var x = -1; x < 2; x++) {
  85240. for (var y = -1; y < 2; y++) {
  85241. downSampleOffsets[id] = x / lastLuminance.width;
  85242. downSampleOffsets[id + 1] = y / lastLuminance.height;
  85243. id += 2;
  85244. }
  85245. }
  85246. effect.setArray2("dsOffsets", downSampleOffsets);
  85247. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  85248. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85249. lastLuminance = _this.luminancePostProcess;
  85250. }
  85251. else {
  85252. lastLuminance = pp;
  85253. }
  85254. };
  85255. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  85256. pp.onAfterRender = function (effect) {
  85257. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  85258. 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);
  85259. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  85260. };
  85261. }
  85262. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  85263. });
  85264. };
  85265. // Create HDR post-process
  85266. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  85267. var _this = this;
  85268. 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);
  85269. var outputLiminance = 1;
  85270. var time = 0;
  85271. var lastTime = 0;
  85272. this.hdrPostProcess.onApply = function (effect) {
  85273. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  85274. time += scene.getEngine().getDeltaTime();
  85275. if (outputLiminance < 0) {
  85276. outputLiminance = _this._hdrCurrentLuminance;
  85277. }
  85278. else {
  85279. var dt = (lastTime - time) / 1000.0;
  85280. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  85281. outputLiminance += _this.hdrDecreaseRate * dt;
  85282. }
  85283. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  85284. outputLiminance -= _this.hdrIncreaseRate * dt;
  85285. }
  85286. else {
  85287. outputLiminance = _this._hdrCurrentLuminance;
  85288. }
  85289. }
  85290. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  85291. effect.setFloat("averageLuminance", outputLiminance);
  85292. lastTime = time;
  85293. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  85294. };
  85295. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  85296. };
  85297. // Create lens flare post-process
  85298. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  85299. var _this = this;
  85300. 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);
  85301. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  85302. this._createBlurPostProcesses(scene, ratio / 4, 2);
  85303. 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);
  85304. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  85305. var resolution = new BABYLON.Vector2(0, 0);
  85306. // Lens flare
  85307. this.lensFlarePostProcess.onApply = function (effect) {
  85308. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  85309. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  85310. effect.setFloat("strength", _this.lensFlareStrength);
  85311. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  85312. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  85313. // Shift
  85314. resolution.x = _this.lensFlarePostProcess.width;
  85315. resolution.y = _this.lensFlarePostProcess.height;
  85316. effect.setVector2("resolution", resolution);
  85317. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  85318. };
  85319. // Compose
  85320. 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);
  85321. 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);
  85322. this.lensFlareComposePostProcess.onApply = function (effect) {
  85323. if (!_this._scene.activeCamera) {
  85324. return;
  85325. }
  85326. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85327. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  85328. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  85329. // Lens start rotation matrix
  85330. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  85331. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  85332. 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));
  85333. camRot *= 4.0;
  85334. 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);
  85335. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  85336. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  85337. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  85338. };
  85339. };
  85340. // Create depth-of-field post-process
  85341. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  85342. var _this = this;
  85343. 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);
  85344. this.depthOfFieldPostProcess.onApply = function (effect) {
  85345. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  85346. effect.setTexture("depthSampler", _this._getDepthTexture());
  85347. effect.setFloat("distance", _this.depthOfFieldDistance);
  85348. };
  85349. // Add to pipeline
  85350. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  85351. };
  85352. // Create motion blur post-process
  85353. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  85354. var _this = this;
  85355. 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);
  85356. var motionScale = 0;
  85357. var prevViewProjection = BABYLON.Matrix.Identity();
  85358. var invViewProjection = BABYLON.Matrix.Identity();
  85359. var viewProjection = BABYLON.Matrix.Identity();
  85360. var screenSize = BABYLON.Vector2.Zero();
  85361. this.motionBlurPostProcess.onApply = function (effect) {
  85362. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  85363. viewProjection.invertToRef(invViewProjection);
  85364. effect.setMatrix("inverseViewProjection", invViewProjection);
  85365. effect.setMatrix("prevViewProjection", prevViewProjection);
  85366. prevViewProjection = viewProjection;
  85367. screenSize.x = _this.motionBlurPostProcess.width;
  85368. screenSize.y = _this.motionBlurPostProcess.height;
  85369. effect.setVector2("screenSize", screenSize);
  85370. motionScale = scene.getEngine().getFps() / 60.0;
  85371. effect.setFloat("motionScale", motionScale);
  85372. effect.setFloat("motionStrength", _this.motionStrength);
  85373. effect.setTexture("depthSampler", _this._getDepthTexture());
  85374. };
  85375. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  85376. };
  85377. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  85378. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  85379. var renderer = this._scene.enableGeometryBufferRenderer();
  85380. return renderer.getGBuffer().textures[0];
  85381. }
  85382. return this._scene.enableDepthRenderer().getDepthMap();
  85383. };
  85384. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  85385. for (var i = 0; i < this._cameras.length; i++) {
  85386. var camera = this._cameras[i];
  85387. if (this.originalPostProcess) {
  85388. this.originalPostProcess.dispose(camera);
  85389. }
  85390. if (this.downSampleX4PostProcess) {
  85391. this.downSampleX4PostProcess.dispose(camera);
  85392. }
  85393. if (this.brightPassPostProcess) {
  85394. this.brightPassPostProcess.dispose(camera);
  85395. }
  85396. if (this.textureAdderPostProcess) {
  85397. this.textureAdderPostProcess.dispose(camera);
  85398. }
  85399. if (this.textureAdderFinalPostProcess) {
  85400. this.textureAdderFinalPostProcess.dispose(camera);
  85401. }
  85402. if (this.volumetricLightPostProcess) {
  85403. this.volumetricLightPostProcess.dispose(camera);
  85404. }
  85405. if (this.volumetricLightSmoothXPostProcess) {
  85406. this.volumetricLightSmoothXPostProcess.dispose(camera);
  85407. }
  85408. if (this.volumetricLightSmoothYPostProcess) {
  85409. this.volumetricLightSmoothYPostProcess.dispose(camera);
  85410. }
  85411. if (this.volumetricLightMergePostProces) {
  85412. this.volumetricLightMergePostProces.dispose(camera);
  85413. }
  85414. if (this.volumetricLightFinalPostProcess) {
  85415. this.volumetricLightFinalPostProcess.dispose(camera);
  85416. }
  85417. if (this.lensFlarePostProcess) {
  85418. this.lensFlarePostProcess.dispose(camera);
  85419. }
  85420. if (this.lensFlareComposePostProcess) {
  85421. this.lensFlareComposePostProcess.dispose(camera);
  85422. }
  85423. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  85424. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  85425. }
  85426. if (this.luminancePostProcess) {
  85427. this.luminancePostProcess.dispose(camera);
  85428. }
  85429. if (this.hdrPostProcess) {
  85430. this.hdrPostProcess.dispose(camera);
  85431. }
  85432. if (this.hdrFinalPostProcess) {
  85433. this.hdrFinalPostProcess.dispose(camera);
  85434. }
  85435. if (this.depthOfFieldPostProcess) {
  85436. this.depthOfFieldPostProcess.dispose(camera);
  85437. }
  85438. if (this.motionBlurPostProcess) {
  85439. this.motionBlurPostProcess.dispose(camera);
  85440. }
  85441. if (this.fxaaPostProcess) {
  85442. this.fxaaPostProcess.dispose(camera);
  85443. }
  85444. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  85445. this.blurHPostProcesses[j].dispose(camera);
  85446. }
  85447. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  85448. this.blurVPostProcesses[j].dispose(camera);
  85449. }
  85450. }
  85451. this.originalPostProcess = null;
  85452. this.downSampleX4PostProcess = null;
  85453. this.brightPassPostProcess = null;
  85454. this.textureAdderPostProcess = null;
  85455. this.textureAdderFinalPostProcess = null;
  85456. this.volumetricLightPostProcess = null;
  85457. this.volumetricLightSmoothXPostProcess = null;
  85458. this.volumetricLightSmoothYPostProcess = null;
  85459. this.volumetricLightMergePostProces = null;
  85460. this.volumetricLightFinalPostProcess = null;
  85461. this.lensFlarePostProcess = null;
  85462. this.lensFlareComposePostProcess = null;
  85463. this.luminancePostProcess = null;
  85464. this.hdrPostProcess = null;
  85465. this.hdrFinalPostProcess = null;
  85466. this.depthOfFieldPostProcess = null;
  85467. this.motionBlurPostProcess = null;
  85468. this.fxaaPostProcess = null;
  85469. this.luminanceDownSamplePostProcesses = [];
  85470. this.blurHPostProcesses = [];
  85471. this.blurVPostProcesses = [];
  85472. };
  85473. /**
  85474. * Dispose of the pipeline and stop all post processes
  85475. */
  85476. StandardRenderingPipeline.prototype.dispose = function () {
  85477. this._disposePostProcesses();
  85478. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  85479. _super.prototype.dispose.call(this);
  85480. };
  85481. /**
  85482. * Serialize the rendering pipeline (Used when exporting)
  85483. * @returns the serialized object
  85484. */
  85485. StandardRenderingPipeline.prototype.serialize = function () {
  85486. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  85487. if (this.sourceLight) {
  85488. serializationObject.sourceLightId = this.sourceLight.id;
  85489. }
  85490. serializationObject.customType = "StandardRenderingPipeline";
  85491. return serializationObject;
  85492. };
  85493. /**
  85494. * Parse the serialized pipeline
  85495. * @param source Source pipeline.
  85496. * @param scene The scene to load the pipeline to.
  85497. * @param rootUrl The URL of the serialized pipeline.
  85498. * @returns An instantiated pipeline from the serialized object.
  85499. */
  85500. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  85501. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  85502. if (source.sourceLightId) {
  85503. p.sourceLight = scene.getLightByID(source.sourceLightId);
  85504. }
  85505. return p;
  85506. };
  85507. /**
  85508. * Luminance steps
  85509. */
  85510. StandardRenderingPipeline.LuminanceSteps = 6;
  85511. __decorate([
  85512. BABYLON.serialize()
  85513. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  85514. __decorate([
  85515. BABYLON.serialize()
  85516. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  85517. __decorate([
  85518. BABYLON.serialize()
  85519. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  85520. __decorate([
  85521. BABYLON.serialize()
  85522. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  85523. __decorate([
  85524. BABYLON.serializeAsTexture("lensTexture")
  85525. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  85526. __decorate([
  85527. BABYLON.serialize()
  85528. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  85529. __decorate([
  85530. BABYLON.serialize()
  85531. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  85532. __decorate([
  85533. BABYLON.serialize()
  85534. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  85535. __decorate([
  85536. BABYLON.serialize()
  85537. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  85538. __decorate([
  85539. BABYLON.serialize()
  85540. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  85541. __decorate([
  85542. BABYLON.serialize()
  85543. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  85544. __decorate([
  85545. BABYLON.serializeAsTexture("lensColorTexture")
  85546. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  85547. __decorate([
  85548. BABYLON.serialize()
  85549. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  85550. __decorate([
  85551. BABYLON.serialize()
  85552. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  85553. __decorate([
  85554. BABYLON.serialize()
  85555. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  85556. __decorate([
  85557. BABYLON.serialize()
  85558. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  85559. __decorate([
  85560. BABYLON.serializeAsTexture("lensStarTexture")
  85561. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  85562. __decorate([
  85563. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  85564. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  85565. __decorate([
  85566. BABYLON.serialize()
  85567. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  85568. __decorate([
  85569. BABYLON.serialize()
  85570. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  85571. __decorate([
  85572. BABYLON.serialize()
  85573. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  85574. __decorate([
  85575. BABYLON.serialize()
  85576. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  85577. __decorate([
  85578. BABYLON.serialize()
  85579. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  85580. __decorate([
  85581. BABYLON.serialize()
  85582. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  85583. __decorate([
  85584. BABYLON.serialize()
  85585. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  85586. __decorate([
  85587. BABYLON.serialize()
  85588. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  85589. __decorate([
  85590. BABYLON.serialize()
  85591. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  85592. __decorate([
  85593. BABYLON.serialize()
  85594. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  85595. __decorate([
  85596. BABYLON.serialize()
  85597. ], StandardRenderingPipeline.prototype, "fxaaEnabled", null);
  85598. __decorate([
  85599. BABYLON.serialize()
  85600. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  85601. __decorate([
  85602. BABYLON.serialize()
  85603. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  85604. __decorate([
  85605. BABYLON.serialize()
  85606. ], StandardRenderingPipeline.prototype, "samples", null);
  85607. return StandardRenderingPipeline;
  85608. }(BABYLON.PostProcessRenderPipeline));
  85609. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  85610. })(BABYLON || (BABYLON = {}));
  85611. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  85612. var BABYLON;
  85613. (function (BABYLON) {
  85614. /**
  85615. * Fxaa post process
  85616. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#fxaa
  85617. */
  85618. var FxaaPostProcess = /** @class */ (function (_super) {
  85619. __extends(FxaaPostProcess, _super);
  85620. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  85621. if (camera === void 0) { camera = null; }
  85622. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85623. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  85624. var defines = _this._getDefines();
  85625. _this.updateEffect(defines);
  85626. _this.onApplyObservable.add(function (effect) {
  85627. var texelSize = _this.texelSize;
  85628. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  85629. });
  85630. return _this;
  85631. }
  85632. FxaaPostProcess.prototype._getDefines = function () {
  85633. var engine = this.getEngine();
  85634. if (!engine) {
  85635. return null;
  85636. }
  85637. var glInfo = engine.getGlInfo();
  85638. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  85639. return "#define MALI 1\n";
  85640. }
  85641. return null;
  85642. };
  85643. return FxaaPostProcess;
  85644. }(BABYLON.PostProcess));
  85645. BABYLON.FxaaPostProcess = FxaaPostProcess;
  85646. })(BABYLON || (BABYLON = {}));
  85647. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  85648. var BABYLON;
  85649. (function (BABYLON) {
  85650. /**
  85651. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  85652. */
  85653. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  85654. __extends(ChromaticAberrationPostProcess, _super);
  85655. /**
  85656. * Creates a new instance ChromaticAberrationPostProcess
  85657. * @param name The name of the effect.
  85658. * @param screenWidth The width of the screen to apply the effect on.
  85659. * @param screenHeight The height of the screen to apply the effect on.
  85660. * @param options The required width/height ratio to downsize to before computing the render pass.
  85661. * @param camera The camera to apply the render pass to.
  85662. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85663. * @param engine The engine which the post process will be applied. (default: current engine)
  85664. * @param reusable If the post process can be reused on the same frame. (default: false)
  85665. * @param textureType Type of textures used when performing the post process. (default: 0)
  85666. * @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)
  85667. */
  85668. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85669. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85670. if (blockCompilation === void 0) { blockCompilation = false; }
  85671. 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;
  85672. /**
  85673. * The amount of seperation of rgb channels (default: 30)
  85674. */
  85675. _this.aberrationAmount = 30;
  85676. /**
  85677. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  85678. */
  85679. _this.radialIntensity = 0;
  85680. /**
  85681. * 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))
  85682. */
  85683. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  85684. /**
  85685. * 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))
  85686. */
  85687. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  85688. _this.onApplyObservable.add(function (effect) {
  85689. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  85690. effect.setFloat('screen_width', screenWidth);
  85691. effect.setFloat('screen_height', screenHeight);
  85692. effect.setFloat('radialIntensity', _this.radialIntensity);
  85693. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  85694. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  85695. });
  85696. return _this;
  85697. }
  85698. return ChromaticAberrationPostProcess;
  85699. }(BABYLON.PostProcess));
  85700. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  85701. })(BABYLON || (BABYLON = {}));
  85702. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  85703. var BABYLON;
  85704. (function (BABYLON) {
  85705. /**
  85706. * The GrainPostProcess adds noise to the image at mid luminance levels
  85707. */
  85708. var GrainPostProcess = /** @class */ (function (_super) {
  85709. __extends(GrainPostProcess, _super);
  85710. /**
  85711. * Creates a new instance of @see GrainPostProcess
  85712. * @param name The name of the effect.
  85713. * @param options The required width/height ratio to downsize to before computing the render pass.
  85714. * @param camera The camera to apply the render pass to.
  85715. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85716. * @param engine The engine which the post process will be applied. (default: current engine)
  85717. * @param reusable If the post process can be reused on the same frame. (default: false)
  85718. * @param textureType Type of textures used when performing the post process. (default: 0)
  85719. * @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)
  85720. */
  85721. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85722. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85723. if (blockCompilation === void 0) { blockCompilation = false; }
  85724. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85725. /**
  85726. * The intensity of the grain added (default: 30)
  85727. */
  85728. _this.intensity = 30;
  85729. /**
  85730. * If the grain should be randomized on every frame
  85731. */
  85732. _this.animated = false;
  85733. _this.onApplyObservable.add(function (effect) {
  85734. effect.setFloat('intensity', _this.intensity);
  85735. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  85736. });
  85737. return _this;
  85738. }
  85739. return GrainPostProcess;
  85740. }(BABYLON.PostProcess));
  85741. BABYLON.GrainPostProcess = GrainPostProcess;
  85742. })(BABYLON || (BABYLON = {}));
  85743. //# sourceMappingURL=babylon.grainPostProcess.js.map
  85744. var BABYLON;
  85745. (function (BABYLON) {
  85746. /**
  85747. * The SharpenPostProcess applies a sharpen kernel to every pixel
  85748. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  85749. */
  85750. var SharpenPostProcess = /** @class */ (function (_super) {
  85751. __extends(SharpenPostProcess, _super);
  85752. /**
  85753. * Creates a new instance ConvolutionPostProcess
  85754. * @param name The name of the effect.
  85755. * @param options The required width/height ratio to downsize to before computing the render pass.
  85756. * @param camera The camera to apply the render pass to.
  85757. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85758. * @param engine The engine which the post process will be applied. (default: current engine)
  85759. * @param reusable If the post process can be reused on the same frame. (default: false)
  85760. * @param textureType Type of textures used when performing the post process. (default: 0)
  85761. * @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)
  85762. */
  85763. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  85764. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85765. if (blockCompilation === void 0) { blockCompilation = false; }
  85766. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  85767. /**
  85768. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  85769. */
  85770. _this.colorAmount = 1.0;
  85771. /**
  85772. * How much sharpness should be applied (default: 0.3)
  85773. */
  85774. _this.edgeAmount = 0.3;
  85775. _this.onApply = function (effect) {
  85776. effect.setFloat2("screenSize", _this.width, _this.height);
  85777. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  85778. };
  85779. return _this;
  85780. }
  85781. return SharpenPostProcess;
  85782. }(BABYLON.PostProcess));
  85783. BABYLON.SharpenPostProcess = SharpenPostProcess;
  85784. })(BABYLON || (BABYLON = {}));
  85785. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  85786. var BABYLON;
  85787. (function (BABYLON) {
  85788. /**
  85789. * The Blur Post Process which blurs an image based on a kernel and direction.
  85790. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  85791. */
  85792. var BlurPostProcess = /** @class */ (function (_super) {
  85793. __extends(BlurPostProcess, _super);
  85794. /**
  85795. * Creates a new instance BlurPostProcess
  85796. * @param name The name of the effect.
  85797. * @param direction The direction in which to blur the image.
  85798. * @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.
  85799. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  85800. * @param camera The camera to apply the render pass to.
  85801. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  85802. * @param engine The engine which the post process will be applied. (default: current engine)
  85803. * @param reusable If the post process can be reused on the same frame. (default: false)
  85804. * @param textureType Type of textures used when performing the post process. (default: 0)
  85805. * @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)
  85806. */
  85807. function BlurPostProcess(name,
  85808. /** The direction in which to blur the image. */
  85809. direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  85810. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  85811. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  85812. if (defines === void 0) { defines = ""; }
  85813. if (blockCompilation === void 0) { blockCompilation = false; }
  85814. 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;
  85815. _this.direction = direction;
  85816. _this.blockCompilation = blockCompilation;
  85817. _this._packedFloat = false;
  85818. _this._staticDefines = "";
  85819. _this._staticDefines = defines;
  85820. _this.onApplyObservable.add(function (effect) {
  85821. if (_this._outputTexture) {
  85822. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  85823. }
  85824. else {
  85825. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  85826. }
  85827. });
  85828. _this.kernel = kernel;
  85829. return _this;
  85830. }
  85831. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  85832. /**
  85833. * Gets the length in pixels of the blur sample region
  85834. */
  85835. get: function () {
  85836. return this._idealKernel;
  85837. },
  85838. /**
  85839. * Sets the length in pixels of the blur sample region
  85840. */
  85841. set: function (v) {
  85842. if (this._idealKernel === v) {
  85843. return;
  85844. }
  85845. v = Math.max(v, 1);
  85846. this._idealKernel = v;
  85847. this._kernel = this._nearestBestKernel(v);
  85848. if (!this.blockCompilation) {
  85849. this._updateParameters();
  85850. }
  85851. },
  85852. enumerable: true,
  85853. configurable: true
  85854. });
  85855. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  85856. /**
  85857. * Gets wether or not the blur is unpacking/repacking floats
  85858. */
  85859. get: function () {
  85860. return this._packedFloat;
  85861. },
  85862. /**
  85863. * Sets wether or not the blur needs to unpack/repack floats
  85864. */
  85865. set: function (v) {
  85866. if (this._packedFloat === v) {
  85867. return;
  85868. }
  85869. this._packedFloat = v;
  85870. if (!this.blockCompilation) {
  85871. this._updateParameters();
  85872. }
  85873. },
  85874. enumerable: true,
  85875. configurable: true
  85876. });
  85877. /**
  85878. * Updates the effect with the current post process compile time values and recompiles the shader.
  85879. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  85880. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  85881. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  85882. * @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
  85883. * @param onCompiled Called when the shader has been compiled.
  85884. * @param onError Called if there is an error when compiling a shader.
  85885. */
  85886. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  85887. if (defines === void 0) { defines = null; }
  85888. if (uniforms === void 0) { uniforms = null; }
  85889. if (samplers === void 0) { samplers = null; }
  85890. this._updateParameters(onCompiled, onError);
  85891. };
  85892. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  85893. // Generate sampling offsets and weights
  85894. var N = this._kernel;
  85895. var centerIndex = (N - 1) / 2;
  85896. // Generate Gaussian sampling weights over kernel
  85897. var offsets = [];
  85898. var weights = [];
  85899. var totalWeight = 0;
  85900. for (var i = 0; i < N; i++) {
  85901. var u = i / (N - 1);
  85902. var w = this._gaussianWeight(u * 2.0 - 1);
  85903. offsets[i] = (i - centerIndex);
  85904. weights[i] = w;
  85905. totalWeight += w;
  85906. }
  85907. // Normalize weights
  85908. for (var i = 0; i < weights.length; i++) {
  85909. weights[i] /= totalWeight;
  85910. }
  85911. // Optimize: combine samples to take advantage of hardware linear sampling
  85912. // Walk from left to center, combining pairs (symmetrically)
  85913. var linearSamplingWeights = [];
  85914. var linearSamplingOffsets = [];
  85915. var linearSamplingMap = [];
  85916. for (var i = 0; i <= centerIndex; i += 2) {
  85917. var j = Math.min(i + 1, Math.floor(centerIndex));
  85918. var singleCenterSample = i === j;
  85919. if (singleCenterSample) {
  85920. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  85921. }
  85922. else {
  85923. var sharedCell = j === centerIndex;
  85924. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  85925. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  85926. if (offsetLinear === 0) {
  85927. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  85928. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  85929. }
  85930. else {
  85931. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  85932. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  85933. }
  85934. }
  85935. }
  85936. for (var i = 0; i < linearSamplingMap.length; i++) {
  85937. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  85938. linearSamplingWeights[i] = linearSamplingMap[i].w;
  85939. }
  85940. // Replace with optimized
  85941. offsets = linearSamplingOffsets;
  85942. weights = linearSamplingWeights;
  85943. // Generate shaders
  85944. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  85945. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  85946. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  85947. var defines = "";
  85948. defines += this._staticDefines;
  85949. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  85950. if (this._staticDefines.indexOf("DOF") != -1) {
  85951. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  85952. varyingCount--;
  85953. }
  85954. for (var i = 0; i < varyingCount; i++) {
  85955. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  85956. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  85957. }
  85958. var depCount = 0;
  85959. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  85960. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  85961. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  85962. depCount++;
  85963. }
  85964. if (this.packedFloat) {
  85965. defines += "#define PACKEDFLOAT 1";
  85966. }
  85967. this.blockCompilation = false;
  85968. _super.prototype.updateEffect.call(this, defines, null, null, {
  85969. varyingCount: varyingCount,
  85970. depCount: depCount
  85971. }, onCompiled, onError);
  85972. };
  85973. /**
  85974. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  85975. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  85976. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  85977. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  85978. * The gaps between physical kernels are compensated for in the weighting of the samples
  85979. * @param idealKernel Ideal blur kernel.
  85980. * @return Nearest best kernel.
  85981. */
  85982. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  85983. var v = Math.round(idealKernel);
  85984. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  85985. var k = _a[_i];
  85986. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  85987. return Math.max(k, 3);
  85988. }
  85989. }
  85990. return Math.max(v, 3);
  85991. };
  85992. /**
  85993. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  85994. * @param x The point on the Gaussian distribution to sample.
  85995. * @return the value of the Gaussian function at x.
  85996. */
  85997. BlurPostProcess.prototype._gaussianWeight = function (x) {
  85998. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  85999. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  86000. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  86001. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  86002. // truncated at around 1.3% of peak strength.
  86003. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  86004. var sigma = (1 / 3);
  86005. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  86006. var exponent = -((x * x) / (2.0 * sigma * sigma));
  86007. var weight = (1.0 / denominator) * Math.exp(exponent);
  86008. return weight;
  86009. };
  86010. /**
  86011. * Generates a string that can be used as a floating point number in GLSL.
  86012. * @param x Value to print.
  86013. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  86014. * @return GLSL float string.
  86015. */
  86016. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  86017. if (decimalFigures === void 0) { decimalFigures = 8; }
  86018. return x.toFixed(decimalFigures).replace(/0+$/, '');
  86019. };
  86020. return BlurPostProcess;
  86021. }(BABYLON.PostProcess));
  86022. BABYLON.BlurPostProcess = BlurPostProcess;
  86023. })(BABYLON || (BABYLON = {}));
  86024. //# sourceMappingURL=babylon.blurPostProcess.js.map
  86025. var BABYLON;
  86026. (function (BABYLON) {
  86027. /**
  86028. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  86029. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  86030. * based on samples that have a large difference in distance than the center pixel.
  86031. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86032. */
  86033. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  86034. __extends(DepthOfFieldBlurPostProcess, _super);
  86035. /**
  86036. * Creates a new instance CircleOfConfusionPostProcess
  86037. * @param name The name of the effect.
  86038. * @param scene The scene the effect belongs to.
  86039. * @param direction The direction the blur should be applied.
  86040. * @param kernel The size of the kernel used to blur.
  86041. * @param options The required width/height ratio to downsize to before computing the render pass.
  86042. * @param camera The camera to apply the render pass to.
  86043. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  86044. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  86045. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86046. * @param engine The engine which the post process will be applied. (default: current engine)
  86047. * @param reusable If the post process can be reused on the same frame. (default: false)
  86048. * @param textureType Type of textures used when performing the post process. (default: 0)
  86049. * @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)
  86050. */
  86051. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  86052. if (imageToBlur === void 0) { imageToBlur = null; }
  86053. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  86054. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86055. if (blockCompilation === void 0) { blockCompilation = false; }
  86056. 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;
  86057. _this.direction = direction;
  86058. _this.onApplyObservable.add(function (effect) {
  86059. if (imageToBlur != null) {
  86060. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  86061. }
  86062. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86063. if (scene.activeCamera) {
  86064. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  86065. }
  86066. });
  86067. return _this;
  86068. }
  86069. return DepthOfFieldBlurPostProcess;
  86070. }(BABYLON.BlurPostProcess));
  86071. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  86072. })(BABYLON || (BABYLON = {}));
  86073. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  86074. var BABYLON;
  86075. (function (BABYLON) {
  86076. /**
  86077. * Options to be set when merging outputs from the default pipeline.
  86078. */
  86079. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  86080. function DepthOfFieldMergePostProcessOptions() {
  86081. }
  86082. return DepthOfFieldMergePostProcessOptions;
  86083. }());
  86084. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  86085. /**
  86086. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86087. */
  86088. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  86089. __extends(DepthOfFieldMergePostProcess, _super);
  86090. /**
  86091. * Creates a new instance of DepthOfFieldMergePostProcess
  86092. * @param name The name of the effect.
  86093. * @param originalFromInput Post process which's input will be used for the merge.
  86094. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  86095. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  86096. * @param options The required width/height ratio to downsize to before computing the render pass.
  86097. * @param camera The camera to apply the render pass to.
  86098. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86099. * @param engine The engine which the post process will be applied. (default: current engine)
  86100. * @param reusable If the post process can be reused on the same frame. (default: false)
  86101. * @param textureType Type of textures used when performing the post process. (default: 0)
  86102. * @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)
  86103. */
  86104. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86105. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86106. if (blockCompilation === void 0) { blockCompilation = false; }
  86107. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86108. _this.blurSteps = blurSteps;
  86109. _this.onApplyObservable.add(function (effect) {
  86110. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86111. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  86112. blurSteps.forEach(function (step, index) {
  86113. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  86114. });
  86115. });
  86116. if (!blockCompilation) {
  86117. _this.updateEffect();
  86118. }
  86119. return _this;
  86120. }
  86121. /**
  86122. * Updates the effect with the current post process compile time values and recompiles the shader.
  86123. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  86124. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  86125. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  86126. * @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
  86127. * @param onCompiled Called when the shader has been compiled.
  86128. * @param onError Called if there is an error when compiling a shader.
  86129. */
  86130. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  86131. if (defines === void 0) { defines = null; }
  86132. if (uniforms === void 0) { uniforms = null; }
  86133. if (samplers === void 0) { samplers = null; }
  86134. if (!defines) {
  86135. defines = "";
  86136. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  86137. }
  86138. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  86139. };
  86140. return DepthOfFieldMergePostProcess;
  86141. }(BABYLON.PostProcess));
  86142. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  86143. })(BABYLON || (BABYLON = {}));
  86144. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  86145. var BABYLON;
  86146. (function (BABYLON) {
  86147. /**
  86148. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  86149. */
  86150. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  86151. __extends(CircleOfConfusionPostProcess, _super);
  86152. /**
  86153. * Creates a new instance CircleOfConfusionPostProcess
  86154. * @param name The name of the effect.
  86155. * @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.
  86156. * @param options The required width/height ratio to downsize to before computing the render pass.
  86157. * @param camera The camera to apply the render pass to.
  86158. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86159. * @param engine The engine which the post process will be applied. (default: current engine)
  86160. * @param reusable If the post process can be reused on the same frame. (default: false)
  86161. * @param textureType Type of textures used when performing the post process. (default: 0)
  86162. * @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)
  86163. */
  86164. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86165. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86166. if (blockCompilation === void 0) { blockCompilation = false; }
  86167. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86168. /**
  86169. * 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.
  86170. */
  86171. _this.lensSize = 50;
  86172. /**
  86173. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86174. */
  86175. _this.fStop = 1.4;
  86176. /**
  86177. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86178. */
  86179. _this.focusDistance = 2000;
  86180. /**
  86181. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  86182. */
  86183. _this.focalLength = 50;
  86184. _this._depthTexture = null;
  86185. _this._depthTexture = depthTexture;
  86186. _this.onApplyObservable.add(function (effect) {
  86187. if (!_this._depthTexture) {
  86188. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  86189. return;
  86190. }
  86191. effect.setTexture("depthSampler", _this._depthTexture);
  86192. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  86193. var aperture = _this.lensSize / _this.fStop;
  86194. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  86195. effect.setFloat('focusDistance', _this.focusDistance);
  86196. effect.setFloat('cocPrecalculation', cocPrecalculation);
  86197. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  86198. });
  86199. return _this;
  86200. }
  86201. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  86202. /**
  86203. * 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.
  86204. */
  86205. set: function (value) {
  86206. this._depthTexture = value;
  86207. },
  86208. enumerable: true,
  86209. configurable: true
  86210. });
  86211. return CircleOfConfusionPostProcess;
  86212. }(BABYLON.PostProcess));
  86213. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  86214. })(BABYLON || (BABYLON = {}));
  86215. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  86216. var BABYLON;
  86217. (function (BABYLON) {
  86218. /**
  86219. * Specifies the level of max blur that should be applied when using the depth of field effect
  86220. */
  86221. var DepthOfFieldEffectBlurLevel;
  86222. (function (DepthOfFieldEffectBlurLevel) {
  86223. /**
  86224. * Subtle blur
  86225. */
  86226. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  86227. /**
  86228. * Medium blur
  86229. */
  86230. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  86231. /**
  86232. * Large blur
  86233. */
  86234. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  86235. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  86236. ;
  86237. /**
  86238. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  86239. */
  86240. var DepthOfFieldEffect = /** @class */ (function (_super) {
  86241. __extends(DepthOfFieldEffect, _super);
  86242. /**
  86243. * Creates a new instance DepthOfFieldEffect
  86244. * @param scene The scene the effect belongs to.
  86245. * @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.
  86246. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86247. * @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)
  86248. */
  86249. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  86250. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  86251. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86252. if (blockCompilation === void 0) { blockCompilation = false; }
  86253. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  86254. return _this._effects;
  86255. }, true) || this;
  86256. /**
  86257. * @hidden Internal post processes in depth of field effect
  86258. */
  86259. _this._effects = [];
  86260. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  86261. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86262. // 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)
  86263. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  86264. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  86265. _this._depthOfFieldBlurY = [];
  86266. _this._depthOfFieldBlurX = [];
  86267. var blurCount = 1;
  86268. var kernelSize = 15;
  86269. switch (blurLevel) {
  86270. case DepthOfFieldEffectBlurLevel.High: {
  86271. blurCount = 3;
  86272. kernelSize = 51;
  86273. break;
  86274. }
  86275. case DepthOfFieldEffectBlurLevel.Medium: {
  86276. blurCount = 2;
  86277. kernelSize = 31;
  86278. break;
  86279. }
  86280. default: {
  86281. kernelSize = 15;
  86282. blurCount = 1;
  86283. break;
  86284. }
  86285. }
  86286. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  86287. var ratio = 1.0;
  86288. for (var i = 0; i < blurCount; i++) {
  86289. 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);
  86290. blurY.autoClear = false;
  86291. ratio = 0.75 / Math.pow(2, i);
  86292. 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);
  86293. blurX.autoClear = false;
  86294. _this._depthOfFieldBlurY.push(blurY);
  86295. _this._depthOfFieldBlurX.push(blurX);
  86296. }
  86297. // Set all post processes on the effect.
  86298. _this._effects = [_this._circleOfConfusion];
  86299. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  86300. _this._effects.push(_this._depthOfFieldBlurY[i]);
  86301. _this._effects.push(_this._depthOfFieldBlurX[i]);
  86302. }
  86303. // Merge blurred images with original image based on circleOfConfusion
  86304. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86305. _this._dofMerge.autoClear = false;
  86306. _this._effects.push(_this._dofMerge);
  86307. return _this;
  86308. }
  86309. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  86310. get: function () {
  86311. return this._circleOfConfusion.focalLength;
  86312. },
  86313. /**
  86314. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  86315. */
  86316. set: function (value) {
  86317. this._circleOfConfusion.focalLength = value;
  86318. },
  86319. enumerable: true,
  86320. configurable: true
  86321. });
  86322. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  86323. get: function () {
  86324. return this._circleOfConfusion.fStop;
  86325. },
  86326. /**
  86327. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  86328. */
  86329. set: function (value) {
  86330. this._circleOfConfusion.fStop = value;
  86331. },
  86332. enumerable: true,
  86333. configurable: true
  86334. });
  86335. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  86336. get: function () {
  86337. return this._circleOfConfusion.focusDistance;
  86338. },
  86339. /**
  86340. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  86341. */
  86342. set: function (value) {
  86343. this._circleOfConfusion.focusDistance = value;
  86344. },
  86345. enumerable: true,
  86346. configurable: true
  86347. });
  86348. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  86349. get: function () {
  86350. return this._circleOfConfusion.lensSize;
  86351. },
  86352. /**
  86353. * 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.
  86354. */
  86355. set: function (value) {
  86356. this._circleOfConfusion.lensSize = value;
  86357. },
  86358. enumerable: true,
  86359. configurable: true
  86360. });
  86361. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  86362. /**
  86363. * 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.
  86364. */
  86365. set: function (value) {
  86366. this._circleOfConfusion.depthTexture = value;
  86367. },
  86368. enumerable: true,
  86369. configurable: true
  86370. });
  86371. /**
  86372. * Disposes each of the internal effects for a given camera.
  86373. * @param camera The camera to dispose the effect on.
  86374. */
  86375. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  86376. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86377. this._effects[effectIndex].dispose(camera);
  86378. }
  86379. };
  86380. /**
  86381. * @hidden Internal
  86382. */
  86383. DepthOfFieldEffect.prototype._updateEffects = function () {
  86384. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86385. this._effects[effectIndex].updateEffect();
  86386. }
  86387. };
  86388. /**
  86389. * Internal
  86390. * @returns if all the contained post processes are ready.
  86391. * @hidden
  86392. */
  86393. DepthOfFieldEffect.prototype._isReady = function () {
  86394. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86395. if (!this._effects[effectIndex].isReady()) {
  86396. return false;
  86397. }
  86398. }
  86399. return true;
  86400. };
  86401. return DepthOfFieldEffect;
  86402. }(BABYLON.PostProcessRenderEffect));
  86403. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  86404. })(BABYLON || (BABYLON = {}));
  86405. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  86406. var BABYLON;
  86407. (function (BABYLON) {
  86408. /**
  86409. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  86410. */
  86411. var BloomMergePostProcess = /** @class */ (function (_super) {
  86412. __extends(BloomMergePostProcess, _super);
  86413. /**
  86414. * Creates a new instance of @see BloomMergePostProcess
  86415. * @param name The name of the effect.
  86416. * @param originalFromInput Post process which's input will be used for the merge.
  86417. * @param blurred Blurred highlights post process which's output will be used.
  86418. * @param weight Weight of the bloom to be added to the original input.
  86419. * @param options The required width/height ratio to downsize to before computing the render pass.
  86420. * @param camera The camera to apply the render pass to.
  86421. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  86422. * @param engine The engine which the post process will be applied. (default: current engine)
  86423. * @param reusable If the post process can be reused on the same frame. (default: false)
  86424. * @param textureType Type of textures used when performing the post process. (default: 0)
  86425. * @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)
  86426. */
  86427. function BloomMergePostProcess(name, originalFromInput, blurred,
  86428. /** Weight of the bloom to be added to the original input. */
  86429. weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86430. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86431. if (blockCompilation === void 0) { blockCompilation = false; }
  86432. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  86433. _this.weight = weight;
  86434. _this.onApplyObservable.add(function (effect) {
  86435. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  86436. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  86437. effect.setFloat("bloomWeight", _this.weight);
  86438. });
  86439. if (!blockCompilation) {
  86440. _this.updateEffect();
  86441. }
  86442. return _this;
  86443. }
  86444. return BloomMergePostProcess;
  86445. }(BABYLON.PostProcess));
  86446. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  86447. })(BABYLON || (BABYLON = {}));
  86448. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  86449. var BABYLON;
  86450. (function (BABYLON) {
  86451. /**
  86452. * 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.
  86453. */
  86454. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  86455. __extends(ExtractHighlightsPostProcess, _super);
  86456. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  86457. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  86458. if (blockCompilation === void 0) { blockCompilation = false; }
  86459. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  86460. /**
  86461. * The luminance threshold, pixels below this value will be set to black.
  86462. */
  86463. _this.threshold = 0.9;
  86464. /** @hidden */
  86465. _this._exposure = 1;
  86466. /**
  86467. * Post process which has the input texture to be used when performing highlight extraction
  86468. * @hidden
  86469. */
  86470. _this._inputPostProcess = null;
  86471. _this.onApplyObservable.add(function (effect) {
  86472. if (_this._inputPostProcess) {
  86473. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  86474. }
  86475. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  86476. effect.setFloat('exposure', _this._exposure);
  86477. });
  86478. return _this;
  86479. }
  86480. return ExtractHighlightsPostProcess;
  86481. }(BABYLON.PostProcess));
  86482. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  86483. })(BABYLON || (BABYLON = {}));
  86484. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  86485. var BABYLON;
  86486. (function (BABYLON) {
  86487. /**
  86488. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  86489. */
  86490. var BloomEffect = /** @class */ (function (_super) {
  86491. __extends(BloomEffect, _super);
  86492. /**
  86493. * Creates a new instance of @see BloomEffect
  86494. * @param scene The scene the effect belongs to.
  86495. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  86496. * @param bloomKernel The size of the kernel to be used when applying the blur.
  86497. * @param bloomWeight The the strength of bloom.
  86498. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  86499. * @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)
  86500. */
  86501. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  86502. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  86503. if (blockCompilation === void 0) { blockCompilation = false; }
  86504. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  86505. return _this._effects;
  86506. }, true) || this;
  86507. _this.bloomScale = bloomScale;
  86508. /**
  86509. * @hidden Internal
  86510. */
  86511. _this._effects = [];
  86512. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86513. _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);
  86514. _this._blurX.alwaysForcePOT = true;
  86515. _this._blurX.autoClear = false;
  86516. _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);
  86517. _this._blurY.alwaysForcePOT = true;
  86518. _this._blurY.autoClear = false;
  86519. _this.kernel = bloomKernel;
  86520. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  86521. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  86522. _this._merge.autoClear = false;
  86523. _this._effects.push(_this._merge);
  86524. return _this;
  86525. }
  86526. Object.defineProperty(BloomEffect.prototype, "threshold", {
  86527. /**
  86528. * The luminance threshold to find bright areas of the image to bloom.
  86529. */
  86530. get: function () {
  86531. return this._downscale.threshold;
  86532. },
  86533. set: function (value) {
  86534. this._downscale.threshold = value;
  86535. },
  86536. enumerable: true,
  86537. configurable: true
  86538. });
  86539. Object.defineProperty(BloomEffect.prototype, "weight", {
  86540. /**
  86541. * The strength of the bloom.
  86542. */
  86543. get: function () {
  86544. return this._merge.weight;
  86545. },
  86546. set: function (value) {
  86547. this._merge.weight = value;
  86548. },
  86549. enumerable: true,
  86550. configurable: true
  86551. });
  86552. Object.defineProperty(BloomEffect.prototype, "kernel", {
  86553. /**
  86554. * Specifies the size of the bloom blur kernel, relative to the final output size
  86555. */
  86556. get: function () {
  86557. return this._blurX.kernel / this.bloomScale;
  86558. },
  86559. set: function (value) {
  86560. this._blurX.kernel = value * this.bloomScale;
  86561. this._blurY.kernel = value * this.bloomScale;
  86562. },
  86563. enumerable: true,
  86564. configurable: true
  86565. });
  86566. /**
  86567. * Disposes each of the internal effects for a given camera.
  86568. * @param camera The camera to dispose the effect on.
  86569. */
  86570. BloomEffect.prototype.disposeEffects = function (camera) {
  86571. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86572. this._effects[effectIndex].dispose(camera);
  86573. }
  86574. };
  86575. /**
  86576. * @hidden Internal
  86577. */
  86578. BloomEffect.prototype._updateEffects = function () {
  86579. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86580. this._effects[effectIndex].updateEffect();
  86581. }
  86582. };
  86583. /**
  86584. * Internal
  86585. * @returns if all the contained post processes are ready.
  86586. * @hidden
  86587. */
  86588. BloomEffect.prototype._isReady = function () {
  86589. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  86590. if (!this._effects[effectIndex].isReady()) {
  86591. return false;
  86592. }
  86593. }
  86594. return true;
  86595. };
  86596. return BloomEffect;
  86597. }(BABYLON.PostProcessRenderEffect));
  86598. BABYLON.BloomEffect = BloomEffect;
  86599. })(BABYLON || (BABYLON = {}));
  86600. //# sourceMappingURL=babylon.bloomEffect.js.map
  86601. var BABYLON;
  86602. (function (BABYLON) {
  86603. /**
  86604. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  86605. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  86606. */
  86607. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  86608. __extends(DefaultRenderingPipeline, _super);
  86609. /**
  86610. * @constructor
  86611. * @param name - The rendering pipeline name (default: "")
  86612. * @param hdr - If high dynamic range textures should be used (default: true)
  86613. * @param scene - The scene linked to this pipeline (default: the last created scene)
  86614. * @param cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  86615. * @param automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  86616. */
  86617. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  86618. if (name === void 0) { name = ""; }
  86619. if (hdr === void 0) { hdr = true; }
  86620. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  86621. if (automaticBuild === void 0) { automaticBuild = true; }
  86622. var _this = _super.call(this, scene.getEngine(), name) || this;
  86623. _this._camerasToBeAttached = [];
  86624. /**
  86625. * ID of the sharpen post process,
  86626. */
  86627. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  86628. /**
  86629. * @ignore
  86630. * ID of the image processing post process;
  86631. */
  86632. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  86633. /**
  86634. * @ignore
  86635. * ID of the Fast Approximate Anti-Aliasing post process;
  86636. */
  86637. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  86638. /**
  86639. * ID of the chromatic aberration post process,
  86640. */
  86641. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  86642. /**
  86643. * ID of the grain post process
  86644. */
  86645. _this.GrainPostProcessId = "GrainPostProcessEffect";
  86646. /**
  86647. * Glow post process which adds a glow to emmisive areas of the image
  86648. */
  86649. _this._glowLayer = null;
  86650. /**
  86651. * Animations which can be used to tweak settings over a period of time
  86652. */
  86653. _this.animations = [];
  86654. _this._imageProcessingConfigurationObserver = null;
  86655. // Values
  86656. _this._sharpenEnabled = false;
  86657. _this._bloomEnabled = false;
  86658. _this._depthOfFieldEnabled = false;
  86659. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  86660. _this._fxaaEnabled = false;
  86661. _this._imageProcessingEnabled = true;
  86662. _this._bloomScale = 0.5;
  86663. _this._chromaticAberrationEnabled = false;
  86664. _this._grainEnabled = false;
  86665. _this._buildAllowed = true;
  86666. _this._resizeObserver = null;
  86667. _this._hardwareScaleLevel = 1.0;
  86668. _this._bloomKernel = 64;
  86669. /**
  86670. * Specifies the weight of the bloom in the final rendering
  86671. */
  86672. _this._bloomWeight = 0.15;
  86673. /**
  86674. * Specifies the luma threshold for the area that will be blurred by the bloom
  86675. */
  86676. _this._bloomThreshold = 0.9;
  86677. _this._samples = 1;
  86678. _this._hasCleared = false;
  86679. _this._prevPostProcess = null;
  86680. _this._prevPrevPostProcess = null;
  86681. _this._depthOfFieldSceneObserver = null;
  86682. _this._cameras = cameras || scene.cameras;
  86683. _this._cameras = _this._cameras.slice();
  86684. _this._camerasToBeAttached = _this._cameras.slice();
  86685. _this._buildAllowed = automaticBuild;
  86686. // Initialize
  86687. _this._scene = scene;
  86688. var caps = _this._scene.getEngine().getCaps();
  86689. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  86690. // Misc
  86691. if (_this._hdr) {
  86692. if (caps.textureHalfFloatRender) {
  86693. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86694. }
  86695. else if (caps.textureFloatRender) {
  86696. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86697. }
  86698. }
  86699. else {
  86700. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86701. }
  86702. // Attach
  86703. scene.postProcessRenderPipelineManager.addPipeline(_this);
  86704. var engine = _this._scene.getEngine();
  86705. // Create post processes before hand so they can be modified before enabled.
  86706. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  86707. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86708. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  86709. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  86710. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  86711. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86712. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  86713. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  86714. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  86715. _this._resizeObserver = engine.onResizeObservable.add(function () {
  86716. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  86717. _this.bloomKernel = _this.bloomKernel;
  86718. });
  86719. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  86720. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  86721. });
  86722. _this._buildPipeline();
  86723. return _this;
  86724. }
  86725. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  86726. get: function () {
  86727. return this._sharpenEnabled;
  86728. },
  86729. /**
  86730. * Enable or disable the sharpen process from the pipeline
  86731. */
  86732. set: function (enabled) {
  86733. if (this._sharpenEnabled === enabled) {
  86734. return;
  86735. }
  86736. this._sharpenEnabled = enabled;
  86737. this._buildPipeline();
  86738. },
  86739. enumerable: true,
  86740. configurable: true
  86741. });
  86742. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  86743. /**
  86744. * Specifies the size of the bloom blur kernel, relative to the final output size
  86745. */
  86746. get: function () {
  86747. return this._bloomKernel;
  86748. },
  86749. set: function (value) {
  86750. this._bloomKernel = value;
  86751. this.bloom.kernel = value / this._hardwareScaleLevel;
  86752. },
  86753. enumerable: true,
  86754. configurable: true
  86755. });
  86756. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  86757. get: function () {
  86758. return this._bloomWeight;
  86759. },
  86760. /**
  86761. * The strength of the bloom.
  86762. */
  86763. set: function (value) {
  86764. if (this._bloomWeight === value) {
  86765. return;
  86766. }
  86767. this.bloom.weight = value;
  86768. this._bloomWeight = value;
  86769. },
  86770. enumerable: true,
  86771. configurable: true
  86772. });
  86773. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  86774. get: function () {
  86775. return this._bloomThreshold;
  86776. },
  86777. /**
  86778. * The strength of the bloom.
  86779. */
  86780. set: function (value) {
  86781. if (this._bloomThreshold === value) {
  86782. return;
  86783. }
  86784. this.bloom.threshold = value;
  86785. this._bloomThreshold = value;
  86786. },
  86787. enumerable: true,
  86788. configurable: true
  86789. });
  86790. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  86791. get: function () {
  86792. return this._bloomScale;
  86793. },
  86794. /**
  86795. * The scale of the bloom, lower value will provide better performance.
  86796. */
  86797. set: function (value) {
  86798. if (this._bloomScale === value) {
  86799. return;
  86800. }
  86801. this._bloomScale = value;
  86802. // recreate bloom and dispose old as this setting is not dynamic
  86803. this._rebuildBloom();
  86804. this._buildPipeline();
  86805. },
  86806. enumerable: true,
  86807. configurable: true
  86808. });
  86809. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  86810. get: function () {
  86811. return this._bloomEnabled;
  86812. },
  86813. /**
  86814. * Enable or disable the bloom from the pipeline
  86815. */
  86816. set: function (enabled) {
  86817. if (this._bloomEnabled === enabled) {
  86818. return;
  86819. }
  86820. this._bloomEnabled = enabled;
  86821. this._buildPipeline();
  86822. },
  86823. enumerable: true,
  86824. configurable: true
  86825. });
  86826. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  86827. // recreate bloom and dispose old as this setting is not dynamic
  86828. var oldBloom = this.bloom;
  86829. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  86830. this.bloom.threshold = oldBloom.threshold;
  86831. for (var i = 0; i < this._cameras.length; i++) {
  86832. oldBloom.disposeEffects(this._cameras[i]);
  86833. }
  86834. };
  86835. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  86836. /**
  86837. * If the depth of field is enabled.
  86838. */
  86839. get: function () {
  86840. return this._depthOfFieldEnabled;
  86841. },
  86842. set: function (enabled) {
  86843. if (this._depthOfFieldEnabled === enabled) {
  86844. return;
  86845. }
  86846. this._depthOfFieldEnabled = enabled;
  86847. this._buildPipeline();
  86848. },
  86849. enumerable: true,
  86850. configurable: true
  86851. });
  86852. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  86853. /**
  86854. * Blur level of the depth of field effect. (Higher blur will effect performance)
  86855. */
  86856. get: function () {
  86857. return this._depthOfFieldBlurLevel;
  86858. },
  86859. set: function (value) {
  86860. if (this._depthOfFieldBlurLevel === value) {
  86861. return;
  86862. }
  86863. this._depthOfFieldBlurLevel = value;
  86864. // recreate dof and dispose old as this setting is not dynamic
  86865. var oldDof = this.depthOfField;
  86866. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  86867. this.depthOfField.focalLength = oldDof.focalLength;
  86868. this.depthOfField.focusDistance = oldDof.focusDistance;
  86869. this.depthOfField.fStop = oldDof.fStop;
  86870. this.depthOfField.lensSize = oldDof.lensSize;
  86871. for (var i = 0; i < this._cameras.length; i++) {
  86872. oldDof.disposeEffects(this._cameras[i]);
  86873. }
  86874. this._buildPipeline();
  86875. },
  86876. enumerable: true,
  86877. configurable: true
  86878. });
  86879. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  86880. get: function () {
  86881. return this._fxaaEnabled;
  86882. },
  86883. /**
  86884. * If the anti aliasing is enabled.
  86885. */
  86886. set: function (enabled) {
  86887. if (this._fxaaEnabled === enabled) {
  86888. return;
  86889. }
  86890. this._fxaaEnabled = enabled;
  86891. this._buildPipeline();
  86892. },
  86893. enumerable: true,
  86894. configurable: true
  86895. });
  86896. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  86897. get: function () {
  86898. return this._samples;
  86899. },
  86900. /**
  86901. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  86902. */
  86903. set: function (sampleCount) {
  86904. if (this._samples === sampleCount) {
  86905. return;
  86906. }
  86907. this._samples = sampleCount;
  86908. this._buildPipeline();
  86909. },
  86910. enumerable: true,
  86911. configurable: true
  86912. });
  86913. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  86914. get: function () {
  86915. return this._imageProcessingEnabled;
  86916. },
  86917. /**
  86918. * If image processing is enabled.
  86919. */
  86920. set: function (enabled) {
  86921. if (this._imageProcessingEnabled === enabled) {
  86922. return;
  86923. }
  86924. this._imageProcessingEnabled = enabled;
  86925. this._buildPipeline();
  86926. },
  86927. enumerable: true,
  86928. configurable: true
  86929. });
  86930. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  86931. get: function () {
  86932. return this._glowLayer == null;
  86933. },
  86934. /**
  86935. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  86936. */
  86937. set: function (enabled) {
  86938. if (enabled && !this._glowLayer) {
  86939. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  86940. }
  86941. else if (!enabled && this._glowLayer) {
  86942. this._glowLayer.dispose();
  86943. this._glowLayer = null;
  86944. }
  86945. },
  86946. enumerable: true,
  86947. configurable: true
  86948. });
  86949. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  86950. get: function () {
  86951. return this._chromaticAberrationEnabled;
  86952. },
  86953. /**
  86954. * Enable or disable the chromaticAberration process from the pipeline
  86955. */
  86956. set: function (enabled) {
  86957. if (this._chromaticAberrationEnabled === enabled) {
  86958. return;
  86959. }
  86960. this._chromaticAberrationEnabled = enabled;
  86961. this._buildPipeline();
  86962. },
  86963. enumerable: true,
  86964. configurable: true
  86965. });
  86966. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  86967. get: function () {
  86968. return this._grainEnabled;
  86969. },
  86970. /**
  86971. * Enable or disable the grain process from the pipeline
  86972. */
  86973. set: function (enabled) {
  86974. if (this._grainEnabled === enabled) {
  86975. return;
  86976. }
  86977. this._grainEnabled = enabled;
  86978. this._buildPipeline();
  86979. },
  86980. enumerable: true,
  86981. configurable: true
  86982. });
  86983. /**
  86984. * Force the compilation of the entire pipeline.
  86985. */
  86986. DefaultRenderingPipeline.prototype.prepare = function () {
  86987. var previousState = this._buildAllowed;
  86988. this._buildAllowed = true;
  86989. this._buildPipeline();
  86990. this._buildAllowed = previousState;
  86991. };
  86992. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  86993. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  86994. if (this._hasCleared) {
  86995. postProcess.autoClear = false;
  86996. }
  86997. else {
  86998. postProcess.autoClear = true;
  86999. this._scene.autoClear = false;
  87000. this._hasCleared = true;
  87001. }
  87002. if (!skipTextureSharing) {
  87003. if (this._prevPrevPostProcess) {
  87004. postProcess.shareOutputWith(this._prevPrevPostProcess);
  87005. }
  87006. else {
  87007. postProcess.useOwnOutput();
  87008. }
  87009. if (this._prevPostProcess) {
  87010. this._prevPrevPostProcess = this._prevPostProcess;
  87011. }
  87012. this._prevPostProcess = postProcess;
  87013. }
  87014. };
  87015. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  87016. var _this = this;
  87017. if (!this._buildAllowed) {
  87018. return;
  87019. }
  87020. this._scene.autoClear = true;
  87021. var engine = this._scene.getEngine();
  87022. this._disposePostProcesses();
  87023. if (this._cameras !== null) {
  87024. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87025. // get back cameras to be used to reattach pipeline
  87026. this._cameras = this._camerasToBeAttached.slice();
  87027. }
  87028. this._reset();
  87029. this._prevPostProcess = null;
  87030. this._prevPrevPostProcess = null;
  87031. this._hasCleared = false;
  87032. if (this.depthOfFieldEnabled) {
  87033. // Multi camera suport
  87034. if (this._cameras.length > 1) {
  87035. for (var _i = 0, _a = this._cameras; _i < _a.length; _i++) {
  87036. var camera = _a[_i];
  87037. var depthRenderer = this._scene.enableDepthRenderer(camera);
  87038. depthRenderer.useOnlyInActiveCamera = true;
  87039. }
  87040. this._depthOfFieldSceneObserver = this._scene.onAfterRenderTargetsRenderObservable.add(function (scene) {
  87041. if (_this._cameras.indexOf(scene.activeCamera) > -1) {
  87042. _this.depthOfField.depthTexture = scene.enableDepthRenderer(scene.activeCamera).getDepthMap();
  87043. }
  87044. });
  87045. }
  87046. else {
  87047. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87048. var depthRenderer = this._scene.enableDepthRenderer(this._cameras[0]);
  87049. this.depthOfField.depthTexture = depthRenderer.getDepthMap();
  87050. }
  87051. if (!this.depthOfField._isReady()) {
  87052. this.depthOfField._updateEffects();
  87053. }
  87054. this.addEffect(this.depthOfField);
  87055. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  87056. }
  87057. else {
  87058. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87059. }
  87060. if (this.bloomEnabled) {
  87061. if (!this.bloom._isReady()) {
  87062. this.bloom._updateEffects();
  87063. }
  87064. this.addEffect(this.bloom);
  87065. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  87066. }
  87067. if (this._imageProcessingEnabled) {
  87068. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87069. if (this._hdr) {
  87070. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  87071. this._setAutoClearAndTextureSharing(this.imageProcessing);
  87072. }
  87073. else {
  87074. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  87075. }
  87076. }
  87077. if (this.sharpenEnabled) {
  87078. if (!this.sharpen.isReady()) {
  87079. this.sharpen.updateEffect();
  87080. }
  87081. this.addEffect(this._sharpenEffect);
  87082. this._setAutoClearAndTextureSharing(this.sharpen);
  87083. }
  87084. if (this.grainEnabled) {
  87085. if (!this.grain.isReady()) {
  87086. this.grain.updateEffect();
  87087. }
  87088. this.addEffect(this._grainEffect);
  87089. this._setAutoClearAndTextureSharing(this.grain);
  87090. }
  87091. if (this.chromaticAberrationEnabled) {
  87092. if (!this.chromaticAberration.isReady()) {
  87093. this.chromaticAberration.updateEffect();
  87094. }
  87095. this.addEffect(this._chromaticAberrationEffect);
  87096. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  87097. }
  87098. if (this.fxaaEnabled) {
  87099. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  87100. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  87101. this._setAutoClearAndTextureSharing(this.fxaa, true);
  87102. }
  87103. if (this._cameras !== null) {
  87104. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  87105. }
  87106. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  87107. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  87108. }
  87109. };
  87110. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  87111. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  87112. for (var i = 0; i < this._cameras.length; i++) {
  87113. var camera = this._cameras[i];
  87114. if (this.imageProcessing) {
  87115. this.imageProcessing.dispose(camera);
  87116. }
  87117. if (this.fxaa) {
  87118. this.fxaa.dispose(camera);
  87119. }
  87120. // These are created in the constructor and should not be disposed on every pipeline change
  87121. if (disposeNonRecreated) {
  87122. if (this.sharpen) {
  87123. this.sharpen.dispose(camera);
  87124. }
  87125. if (this.depthOfField) {
  87126. this._scene.onAfterRenderTargetsRenderObservable.remove(this._depthOfFieldSceneObserver);
  87127. this.depthOfField.disposeEffects(camera);
  87128. }
  87129. if (this.bloom) {
  87130. this.bloom.disposeEffects(camera);
  87131. }
  87132. if (this.chromaticAberration) {
  87133. this.chromaticAberration.dispose(camera);
  87134. }
  87135. if (this.grain) {
  87136. this.grain.dispose(camera);
  87137. }
  87138. if (this._glowLayer) {
  87139. this._glowLayer.dispose();
  87140. }
  87141. }
  87142. }
  87143. this.imageProcessing = null;
  87144. this.fxaa = null;
  87145. if (disposeNonRecreated) {
  87146. this.sharpen = null;
  87147. this._sharpenEffect = null;
  87148. this.depthOfField = null;
  87149. this.bloom = null;
  87150. this.chromaticAberration = null;
  87151. this._chromaticAberrationEffect = null;
  87152. this.grain = null;
  87153. this._grainEffect = null;
  87154. this._glowLayer = null;
  87155. }
  87156. };
  87157. /**
  87158. * Adds a camera to the pipeline
  87159. * @param camera the camera to be added
  87160. */
  87161. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  87162. this._camerasToBeAttached.push(camera);
  87163. this._buildPipeline();
  87164. };
  87165. /**
  87166. * Removes a camera from the pipeline
  87167. * @param camera the camera to remove
  87168. */
  87169. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  87170. var index = this._camerasToBeAttached.indexOf(camera);
  87171. this._camerasToBeAttached.splice(index, 1);
  87172. this._buildPipeline();
  87173. };
  87174. /**
  87175. * Dispose of the pipeline and stop all post processes
  87176. */
  87177. DefaultRenderingPipeline.prototype.dispose = function () {
  87178. this._disposePostProcesses(true);
  87179. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  87180. this._scene.autoClear = true;
  87181. if (this._resizeObserver) {
  87182. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  87183. this._resizeObserver = null;
  87184. }
  87185. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  87186. _super.prototype.dispose.call(this);
  87187. };
  87188. /**
  87189. * Serialize the rendering pipeline (Used when exporting)
  87190. * @returns the serialized object
  87191. */
  87192. DefaultRenderingPipeline.prototype.serialize = function () {
  87193. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  87194. serializationObject.customType = "DefaultRenderingPipeline";
  87195. return serializationObject;
  87196. };
  87197. /**
  87198. * Parse the serialized pipeline
  87199. * @param source Source pipeline.
  87200. * @param scene The scene to load the pipeline to.
  87201. * @param rootUrl The URL of the serialized pipeline.
  87202. * @returns An instantiated pipeline from the serialized object.
  87203. */
  87204. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  87205. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  87206. };
  87207. __decorate([
  87208. BABYLON.serialize()
  87209. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  87210. __decorate([
  87211. BABYLON.serialize()
  87212. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  87213. __decorate([
  87214. BABYLON.serialize()
  87215. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  87216. __decorate([
  87217. BABYLON.serialize()
  87218. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  87219. __decorate([
  87220. BABYLON.serialize()
  87221. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  87222. __decorate([
  87223. BABYLON.serialize()
  87224. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  87225. __decorate([
  87226. BABYLON.serialize()
  87227. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  87228. __decorate([
  87229. BABYLON.serialize()
  87230. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  87231. __decorate([
  87232. BABYLON.serialize()
  87233. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  87234. __decorate([
  87235. BABYLON.serialize()
  87236. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  87237. __decorate([
  87238. BABYLON.serialize()
  87239. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  87240. __decorate([
  87241. BABYLON.serialize()
  87242. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  87243. __decorate([
  87244. BABYLON.serialize()
  87245. ], DefaultRenderingPipeline.prototype, "samples", null);
  87246. __decorate([
  87247. BABYLON.serialize()
  87248. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  87249. __decorate([
  87250. BABYLON.serialize()
  87251. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  87252. __decorate([
  87253. BABYLON.serialize()
  87254. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  87255. __decorate([
  87256. BABYLON.serialize()
  87257. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  87258. return DefaultRenderingPipeline;
  87259. }(BABYLON.PostProcessRenderPipeline));
  87260. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  87261. })(BABYLON || (BABYLON = {}));
  87262. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  87263. var BABYLON;
  87264. (function (BABYLON) {
  87265. /**
  87266. * @hidden
  87267. */
  87268. var ImageProcessingConfigurationDefines = /** @class */ (function (_super) {
  87269. __extends(ImageProcessingConfigurationDefines, _super);
  87270. function ImageProcessingConfigurationDefines() {
  87271. var _this = _super.call(this) || this;
  87272. _this.IMAGEPROCESSING = false;
  87273. _this.VIGNETTE = false;
  87274. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  87275. _this.VIGNETTEBLENDMODEOPAQUE = false;
  87276. _this.TONEMAPPING = false;
  87277. _this.TONEMAPPING_ACES = false;
  87278. _this.CONTRAST = false;
  87279. _this.COLORCURVES = false;
  87280. _this.COLORGRADING = false;
  87281. _this.COLORGRADING3D = false;
  87282. _this.SAMPLER3DGREENDEPTH = false;
  87283. _this.SAMPLER3DBGRMAP = false;
  87284. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  87285. _this.EXPOSURE = false;
  87286. _this.rebuild();
  87287. return _this;
  87288. }
  87289. return ImageProcessingConfigurationDefines;
  87290. }(BABYLON.MaterialDefines));
  87291. BABYLON.ImageProcessingConfigurationDefines = ImageProcessingConfigurationDefines;
  87292. /**
  87293. * This groups together the common properties used for image processing either in direct forward pass
  87294. * or through post processing effect depending on the use of the image processing pipeline in your scene
  87295. * or not.
  87296. */
  87297. var ImageProcessingConfiguration = /** @class */ (function () {
  87298. function ImageProcessingConfiguration() {
  87299. /**
  87300. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  87301. */
  87302. this.colorCurves = new BABYLON.ColorCurves();
  87303. this._colorCurvesEnabled = false;
  87304. this._colorGradingEnabled = false;
  87305. this._colorGradingWithGreenDepth = true;
  87306. this._colorGradingBGR = true;
  87307. /** @hidden */
  87308. this._exposure = 1.0;
  87309. this._toneMappingEnabled = false;
  87310. this._toneMappingType = ImageProcessingConfiguration.TONEMAPPING_STANDARD;
  87311. this._contrast = 1.0;
  87312. /**
  87313. * Vignette stretch size.
  87314. */
  87315. this.vignetteStretch = 0;
  87316. /**
  87317. * Vignette centre X Offset.
  87318. */
  87319. this.vignetteCentreX = 0;
  87320. /**
  87321. * Vignette centre Y Offset.
  87322. */
  87323. this.vignetteCentreY = 0;
  87324. /**
  87325. * Vignette weight or intensity of the vignette effect.
  87326. */
  87327. this.vignetteWeight = 1.5;
  87328. /**
  87329. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  87330. * if vignetteEnabled is set to true.
  87331. */
  87332. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  87333. /**
  87334. * Camera field of view used by the Vignette effect.
  87335. */
  87336. this.vignetteCameraFov = 0.5;
  87337. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  87338. this._vignetteEnabled = false;
  87339. this._applyByPostProcess = false;
  87340. this._isEnabled = true;
  87341. /**
  87342. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  87343. */
  87344. this.onUpdateParameters = new BABYLON.Observable();
  87345. }
  87346. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  87347. /**
  87348. * Gets wether the color curves effect is enabled.
  87349. */
  87350. get: function () {
  87351. return this._colorCurvesEnabled;
  87352. },
  87353. /**
  87354. * Sets wether the color curves effect is enabled.
  87355. */
  87356. set: function (value) {
  87357. if (this._colorCurvesEnabled === value) {
  87358. return;
  87359. }
  87360. this._colorCurvesEnabled = value;
  87361. this._updateParameters();
  87362. },
  87363. enumerable: true,
  87364. configurable: true
  87365. });
  87366. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingTexture", {
  87367. /**
  87368. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87369. */
  87370. get: function () {
  87371. return this._colorGradingTexture;
  87372. },
  87373. /**
  87374. * Color grading LUT texture used in the effect if colorGradingEnabled is set to true
  87375. */
  87376. set: function (value) {
  87377. if (this._colorGradingTexture === value) {
  87378. return;
  87379. }
  87380. this._colorGradingTexture = value;
  87381. this._updateParameters();
  87382. },
  87383. enumerable: true,
  87384. configurable: true
  87385. });
  87386. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  87387. /**
  87388. * Gets wether the color grading effect is enabled.
  87389. */
  87390. get: function () {
  87391. return this._colorGradingEnabled;
  87392. },
  87393. /**
  87394. * Sets wether the color grading effect is enabled.
  87395. */
  87396. set: function (value) {
  87397. if (this._colorGradingEnabled === value) {
  87398. return;
  87399. }
  87400. this._colorGradingEnabled = value;
  87401. this._updateParameters();
  87402. },
  87403. enumerable: true,
  87404. configurable: true
  87405. });
  87406. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  87407. /**
  87408. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  87409. */
  87410. get: function () {
  87411. return this._colorGradingWithGreenDepth;
  87412. },
  87413. /**
  87414. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  87415. */
  87416. set: function (value) {
  87417. if (this._colorGradingWithGreenDepth === value) {
  87418. return;
  87419. }
  87420. this._colorGradingWithGreenDepth = value;
  87421. this._updateParameters();
  87422. },
  87423. enumerable: true,
  87424. configurable: true
  87425. });
  87426. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  87427. /**
  87428. * Gets wether the color grading texture contains BGR values.
  87429. */
  87430. get: function () {
  87431. return this._colorGradingBGR;
  87432. },
  87433. /**
  87434. * Sets wether the color grading texture contains BGR values.
  87435. */
  87436. set: function (value) {
  87437. if (this._colorGradingBGR === value) {
  87438. return;
  87439. }
  87440. this._colorGradingBGR = value;
  87441. this._updateParameters();
  87442. },
  87443. enumerable: true,
  87444. configurable: true
  87445. });
  87446. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  87447. /**
  87448. * Gets the Exposure used in the effect.
  87449. */
  87450. get: function () {
  87451. return this._exposure;
  87452. },
  87453. /**
  87454. * Sets the Exposure used in the effect.
  87455. */
  87456. set: function (value) {
  87457. if (this._exposure === value) {
  87458. return;
  87459. }
  87460. this._exposure = value;
  87461. this._updateParameters();
  87462. },
  87463. enumerable: true,
  87464. configurable: true
  87465. });
  87466. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  87467. /**
  87468. * Gets wether the tone mapping effect is enabled.
  87469. */
  87470. get: function () {
  87471. return this._toneMappingEnabled;
  87472. },
  87473. /**
  87474. * Sets wether the tone mapping effect is enabled.
  87475. */
  87476. set: function (value) {
  87477. if (this._toneMappingEnabled === value) {
  87478. return;
  87479. }
  87480. this._toneMappingEnabled = value;
  87481. this._updateParameters();
  87482. },
  87483. enumerable: true,
  87484. configurable: true
  87485. });
  87486. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingType", {
  87487. /**
  87488. * Gets the type of tone mapping effect.
  87489. */
  87490. get: function () {
  87491. return this._toneMappingType;
  87492. },
  87493. /**
  87494. * Sets the type of tone mapping effect used in BabylonJS.
  87495. */
  87496. set: function (value) {
  87497. if (this._toneMappingType === value) {
  87498. return;
  87499. }
  87500. this._toneMappingType = value;
  87501. this._updateParameters();
  87502. },
  87503. enumerable: true,
  87504. configurable: true
  87505. });
  87506. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  87507. /**
  87508. * Gets the contrast used in the effect.
  87509. */
  87510. get: function () {
  87511. return this._contrast;
  87512. },
  87513. /**
  87514. * Sets the contrast used in the effect.
  87515. */
  87516. set: function (value) {
  87517. if (this._contrast === value) {
  87518. return;
  87519. }
  87520. this._contrast = value;
  87521. this._updateParameters();
  87522. },
  87523. enumerable: true,
  87524. configurable: true
  87525. });
  87526. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  87527. /**
  87528. * Gets the vignette blend mode allowing different kind of effect.
  87529. */
  87530. get: function () {
  87531. return this._vignetteBlendMode;
  87532. },
  87533. /**
  87534. * Sets the vignette blend mode allowing different kind of effect.
  87535. */
  87536. set: function (value) {
  87537. if (this._vignetteBlendMode === value) {
  87538. return;
  87539. }
  87540. this._vignetteBlendMode = value;
  87541. this._updateParameters();
  87542. },
  87543. enumerable: true,
  87544. configurable: true
  87545. });
  87546. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  87547. /**
  87548. * Gets wether the vignette effect is enabled.
  87549. */
  87550. get: function () {
  87551. return this._vignetteEnabled;
  87552. },
  87553. /**
  87554. * Sets wether the vignette effect is enabled.
  87555. */
  87556. set: function (value) {
  87557. if (this._vignetteEnabled === value) {
  87558. return;
  87559. }
  87560. this._vignetteEnabled = value;
  87561. this._updateParameters();
  87562. },
  87563. enumerable: true,
  87564. configurable: true
  87565. });
  87566. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  87567. /**
  87568. * Gets wether the image processing is applied through a post process or not.
  87569. */
  87570. get: function () {
  87571. return this._applyByPostProcess;
  87572. },
  87573. /**
  87574. * Sets wether the image processing is applied through a post process or not.
  87575. */
  87576. set: function (value) {
  87577. if (this._applyByPostProcess === value) {
  87578. return;
  87579. }
  87580. this._applyByPostProcess = value;
  87581. this._updateParameters();
  87582. },
  87583. enumerable: true,
  87584. configurable: true
  87585. });
  87586. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  87587. /**
  87588. * Gets wether the image processing is enabled or not.
  87589. */
  87590. get: function () {
  87591. return this._isEnabled;
  87592. },
  87593. /**
  87594. * Sets wether the image processing is enabled or not.
  87595. */
  87596. set: function (value) {
  87597. if (this._isEnabled === value) {
  87598. return;
  87599. }
  87600. this._isEnabled = value;
  87601. this._updateParameters();
  87602. },
  87603. enumerable: true,
  87604. configurable: true
  87605. });
  87606. /**
  87607. * Method called each time the image processing information changes requires to recompile the effect.
  87608. */
  87609. ImageProcessingConfiguration.prototype._updateParameters = function () {
  87610. this.onUpdateParameters.notifyObservers(this);
  87611. };
  87612. /**
  87613. * Gets the current class name.
  87614. * @return "ImageProcessingConfiguration"
  87615. */
  87616. ImageProcessingConfiguration.prototype.getClassName = function () {
  87617. return "ImageProcessingConfiguration";
  87618. };
  87619. /**
  87620. * Prepare the list of uniforms associated with the Image Processing effects.
  87621. * @param uniforms The list of uniforms used in the effect
  87622. * @param defines the list of defines currently in use
  87623. */
  87624. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  87625. if (defines.EXPOSURE) {
  87626. uniforms.push("exposureLinear");
  87627. }
  87628. if (defines.CONTRAST) {
  87629. uniforms.push("contrast");
  87630. }
  87631. if (defines.COLORGRADING) {
  87632. uniforms.push("colorTransformSettings");
  87633. }
  87634. if (defines.VIGNETTE) {
  87635. uniforms.push("vInverseScreenSize");
  87636. uniforms.push("vignetteSettings1");
  87637. uniforms.push("vignetteSettings2");
  87638. }
  87639. if (defines.COLORCURVES) {
  87640. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  87641. }
  87642. };
  87643. /**
  87644. * Prepare the list of samplers associated with the Image Processing effects.
  87645. * @param samplersList The list of uniforms used in the effect
  87646. * @param defines the list of defines currently in use
  87647. */
  87648. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  87649. if (defines.COLORGRADING) {
  87650. samplersList.push("txColorTransform");
  87651. }
  87652. };
  87653. /**
  87654. * Prepare the list of defines associated to the shader.
  87655. * @param defines the list of defines to complete
  87656. * @param forPostProcess Define if we are currently in post process mode or not
  87657. */
  87658. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  87659. if (forPostProcess === void 0) { forPostProcess = false; }
  87660. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  87661. defines.VIGNETTE = false;
  87662. defines.TONEMAPPING = false;
  87663. defines.TONEMAPPING_ACES = false;
  87664. defines.CONTRAST = false;
  87665. defines.EXPOSURE = false;
  87666. defines.COLORCURVES = false;
  87667. defines.COLORGRADING = false;
  87668. defines.COLORGRADING3D = false;
  87669. defines.IMAGEPROCESSING = false;
  87670. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  87671. return;
  87672. }
  87673. defines.VIGNETTE = this.vignetteEnabled;
  87674. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  87675. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  87676. defines.TONEMAPPING = this.toneMappingEnabled;
  87677. switch (this._toneMappingType) {
  87678. case ImageProcessingConfiguration.TONEMAPPING_ACES:
  87679. defines.TONEMAPPING_ACES = true;
  87680. break;
  87681. }
  87682. defines.CONTRAST = (this.contrast !== 1.0);
  87683. defines.EXPOSURE = (this.exposure !== 1.0);
  87684. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  87685. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  87686. if (defines.COLORGRADING) {
  87687. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  87688. }
  87689. else {
  87690. defines.COLORGRADING3D = false;
  87691. }
  87692. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  87693. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  87694. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  87695. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  87696. };
  87697. /**
  87698. * Returns true if all the image processing information are ready.
  87699. * @returns True if ready, otherwise, false
  87700. */
  87701. ImageProcessingConfiguration.prototype.isReady = function () {
  87702. // Color Grading texure can not be none blocking.
  87703. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  87704. };
  87705. /**
  87706. * Binds the image processing to the shader.
  87707. * @param effect The effect to bind to
  87708. * @param aspectRatio Define the current aspect ratio of the effect
  87709. */
  87710. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  87711. if (aspectRatio === void 0) { aspectRatio = 1; }
  87712. // Color Curves
  87713. if (this._colorCurvesEnabled && this.colorCurves) {
  87714. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  87715. }
  87716. // Vignette
  87717. if (this._vignetteEnabled) {
  87718. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  87719. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  87720. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  87721. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  87722. var vignetteScaleX = vignetteScaleY * aspectRatio;
  87723. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  87724. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  87725. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  87726. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  87727. var vignettePower = -2.0 * this.vignetteWeight;
  87728. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  87729. }
  87730. // Exposure
  87731. effect.setFloat("exposureLinear", this.exposure);
  87732. // Contrast
  87733. effect.setFloat("contrast", this.contrast);
  87734. // Color transform settings
  87735. if (this.colorGradingTexture) {
  87736. effect.setTexture("txColorTransform", this.colorGradingTexture);
  87737. var textureSize = this.colorGradingTexture.getSize().height;
  87738. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  87739. 0.5 / textureSize, // textureOffset
  87740. textureSize, // textureSize
  87741. this.colorGradingTexture.level // weight
  87742. );
  87743. }
  87744. };
  87745. /**
  87746. * Clones the current image processing instance.
  87747. * @return The cloned image processing
  87748. */
  87749. ImageProcessingConfiguration.prototype.clone = function () {
  87750. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  87751. };
  87752. /**
  87753. * Serializes the current image processing instance to a json representation.
  87754. * @return a JSON representation
  87755. */
  87756. ImageProcessingConfiguration.prototype.serialize = function () {
  87757. return BABYLON.SerializationHelper.Serialize(this);
  87758. };
  87759. /**
  87760. * Parses the image processing from a json representation.
  87761. * @param source the JSON source to parse
  87762. * @return The parsed image processing
  87763. */
  87764. ImageProcessingConfiguration.Parse = function (source) {
  87765. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  87766. };
  87767. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  87768. /**
  87769. * Used to apply the vignette as a mix with the pixel color.
  87770. */
  87771. get: function () {
  87772. return this._VIGNETTEMODE_MULTIPLY;
  87773. },
  87774. enumerable: true,
  87775. configurable: true
  87776. });
  87777. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  87778. /**
  87779. * Used to apply the vignette as a replacement of the pixel color.
  87780. */
  87781. get: function () {
  87782. return this._VIGNETTEMODE_OPAQUE;
  87783. },
  87784. enumerable: true,
  87785. configurable: true
  87786. });
  87787. /**
  87788. * Default tone mapping applied in BabylonJS.
  87789. */
  87790. ImageProcessingConfiguration.TONEMAPPING_STANDARD = 0;
  87791. /**
  87792. * ACES Tone mapping (used by default in unreal and unity). This can help getting closer
  87793. * to other engines rendering to increase portability.
  87794. */
  87795. ImageProcessingConfiguration.TONEMAPPING_ACES = 1;
  87796. // Static constants associated to the image processing.
  87797. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  87798. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  87799. __decorate([
  87800. BABYLON.serializeAsColorCurves()
  87801. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  87802. __decorate([
  87803. BABYLON.serialize()
  87804. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  87805. __decorate([
  87806. BABYLON.serializeAsTexture("colorGradingTexture")
  87807. ], ImageProcessingConfiguration.prototype, "_colorGradingTexture", void 0);
  87808. __decorate([
  87809. BABYLON.serialize()
  87810. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  87811. __decorate([
  87812. BABYLON.serialize()
  87813. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  87814. __decorate([
  87815. BABYLON.serialize()
  87816. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  87817. __decorate([
  87818. BABYLON.serialize()
  87819. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  87820. __decorate([
  87821. BABYLON.serialize()
  87822. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  87823. __decorate([
  87824. BABYLON.serialize()
  87825. ], ImageProcessingConfiguration.prototype, "_toneMappingType", void 0);
  87826. __decorate([
  87827. BABYLON.serialize()
  87828. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  87829. __decorate([
  87830. BABYLON.serialize()
  87831. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  87832. __decorate([
  87833. BABYLON.serialize()
  87834. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  87835. __decorate([
  87836. BABYLON.serialize()
  87837. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  87838. __decorate([
  87839. BABYLON.serialize()
  87840. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  87841. __decorate([
  87842. BABYLON.serializeAsColor4()
  87843. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  87844. __decorate([
  87845. BABYLON.serialize()
  87846. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  87847. __decorate([
  87848. BABYLON.serialize()
  87849. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  87850. __decorate([
  87851. BABYLON.serialize()
  87852. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  87853. __decorate([
  87854. BABYLON.serialize()
  87855. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  87856. __decorate([
  87857. BABYLON.serialize()
  87858. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  87859. return ImageProcessingConfiguration;
  87860. }());
  87861. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  87862. })(BABYLON || (BABYLON = {}));
  87863. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  87864. var BABYLON;
  87865. (function (BABYLON) {
  87866. /**
  87867. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  87868. * It can help converting any input color in a desired output one. This can then be used to create effects
  87869. * from sepia, black and white to sixties or futuristic rendering...
  87870. *
  87871. * The only supported format is currently 3dl.
  87872. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table
  87873. */
  87874. var ColorGradingTexture = /** @class */ (function (_super) {
  87875. __extends(ColorGradingTexture, _super);
  87876. /**
  87877. * Instantiates a ColorGradingTexture from the following parameters.
  87878. *
  87879. * @param url The location of the color gradind data (currently only supporting 3dl)
  87880. * @param scene The scene the texture will be used in
  87881. */
  87882. function ColorGradingTexture(url, scene) {
  87883. var _this = _super.call(this, scene) || this;
  87884. if (!url) {
  87885. return _this;
  87886. }
  87887. _this._engine = scene.getEngine();
  87888. _this._textureMatrix = BABYLON.Matrix.Identity();
  87889. _this.name = url;
  87890. _this.url = url;
  87891. _this.hasAlpha = false;
  87892. _this.isCube = false;
  87893. _this.is3D = _this._engine.webGLVersion > 1;
  87894. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87895. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87896. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  87897. _this.anisotropicFilteringLevel = 1;
  87898. _this._texture = _this._getFromCache(url, true);
  87899. if (!_this._texture) {
  87900. if (!scene.useDelayedTextureLoading) {
  87901. _this.loadTexture();
  87902. }
  87903. else {
  87904. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  87905. }
  87906. }
  87907. return _this;
  87908. }
  87909. /**
  87910. * Returns the texture matrix used in most of the material.
  87911. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  87912. */
  87913. ColorGradingTexture.prototype.getTextureMatrix = function () {
  87914. return this._textureMatrix;
  87915. };
  87916. /**
  87917. * Occurs when the file being loaded is a .3dl LUT file.
  87918. */
  87919. ColorGradingTexture.prototype.load3dlTexture = function () {
  87920. var engine = this._engine;
  87921. var texture;
  87922. if (engine.webGLVersion === 1) {
  87923. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87924. }
  87925. else {
  87926. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  87927. }
  87928. this._texture = texture;
  87929. var callback = function (text) {
  87930. if (typeof text !== "string") {
  87931. return;
  87932. }
  87933. var data = null;
  87934. var tempData = null;
  87935. var line;
  87936. var lines = text.split('\n');
  87937. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  87938. var maxColor = 0;
  87939. for (var i = 0; i < lines.length; i++) {
  87940. line = lines[i];
  87941. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  87942. continue;
  87943. if (line.indexOf('#') === 0)
  87944. continue;
  87945. var words = line.split(" ");
  87946. if (size === 0) {
  87947. // Number of space + one
  87948. size = words.length;
  87949. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  87950. tempData = new Float32Array(size * size * size * 4);
  87951. continue;
  87952. }
  87953. if (size != 0) {
  87954. var r = Math.max(parseInt(words[0]), 0);
  87955. var g = Math.max(parseInt(words[1]), 0);
  87956. var b = Math.max(parseInt(words[2]), 0);
  87957. maxColor = Math.max(r, maxColor);
  87958. maxColor = Math.max(g, maxColor);
  87959. maxColor = Math.max(b, maxColor);
  87960. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  87961. if (tempData) {
  87962. tempData[pixelStorageIndex + 0] = r;
  87963. tempData[pixelStorageIndex + 1] = g;
  87964. tempData[pixelStorageIndex + 2] = b;
  87965. }
  87966. // Keep for reference in case of back compat problems.
  87967. // pixelIndexSlice++;
  87968. // if (pixelIndexSlice % size == 0) {
  87969. // pixelIndexH++;
  87970. // pixelIndexSlice = 0;
  87971. // if (pixelIndexH % size == 0) {
  87972. // pixelIndexW++;
  87973. // pixelIndexH = 0;
  87974. // }
  87975. // }
  87976. pixelIndexH++;
  87977. if (pixelIndexH % size == 0) {
  87978. pixelIndexSlice++;
  87979. pixelIndexH = 0;
  87980. if (pixelIndexSlice % size == 0) {
  87981. pixelIndexW++;
  87982. pixelIndexSlice = 0;
  87983. }
  87984. }
  87985. }
  87986. }
  87987. if (tempData && data) {
  87988. for (var i = 0; i < tempData.length; i++) {
  87989. if (i > 0 && (i + 1) % 4 === 0) {
  87990. data[i] = 255;
  87991. }
  87992. else {
  87993. var value = tempData[i];
  87994. data[i] = (value / maxColor * 255);
  87995. }
  87996. }
  87997. }
  87998. if (texture.is3D) {
  87999. texture.updateSize(size, size, size);
  88000. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88001. }
  88002. else {
  88003. texture.updateSize(size * size, size);
  88004. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  88005. }
  88006. };
  88007. var scene = this.getScene();
  88008. if (scene) {
  88009. scene._loadFile(this.url, callback);
  88010. }
  88011. else {
  88012. this._engine._loadFile(this.url, callback);
  88013. }
  88014. return this._texture;
  88015. };
  88016. /**
  88017. * Starts the loading process of the texture.
  88018. */
  88019. ColorGradingTexture.prototype.loadTexture = function () {
  88020. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  88021. this.load3dlTexture();
  88022. }
  88023. };
  88024. /**
  88025. * Clones the color gradind texture.
  88026. */
  88027. ColorGradingTexture.prototype.clone = function () {
  88028. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  88029. // Base texture
  88030. newTexture.level = this.level;
  88031. return newTexture;
  88032. };
  88033. /**
  88034. * Called during delayed load for textures.
  88035. */
  88036. ColorGradingTexture.prototype.delayLoad = function () {
  88037. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  88038. return;
  88039. }
  88040. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  88041. this._texture = this._getFromCache(this.url, true);
  88042. if (!this._texture) {
  88043. this.loadTexture();
  88044. }
  88045. };
  88046. /**
  88047. * Parses a color grading texture serialized by Babylon.
  88048. * @param parsedTexture The texture information being parsedTexture
  88049. * @param scene The scene to load the texture in
  88050. * @param rootUrl The root url of the data assets to load
  88051. * @return A color gradind texture
  88052. */
  88053. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  88054. var texture = null;
  88055. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  88056. texture = new ColorGradingTexture(parsedTexture.name, scene);
  88057. texture.name = parsedTexture.name;
  88058. texture.level = parsedTexture.level;
  88059. }
  88060. return texture;
  88061. };
  88062. /**
  88063. * Serializes the LUT texture to json format.
  88064. */
  88065. ColorGradingTexture.prototype.serialize = function () {
  88066. if (!this.name) {
  88067. return null;
  88068. }
  88069. var serializationObject = {};
  88070. serializationObject.name = this.name;
  88071. serializationObject.level = this.level;
  88072. serializationObject.customType = "BABYLON.ColorGradingTexture";
  88073. return serializationObject;
  88074. };
  88075. /**
  88076. * Empty line regex stored for GC.
  88077. */
  88078. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  88079. return ColorGradingTexture;
  88080. }(BABYLON.BaseTexture));
  88081. BABYLON.ColorGradingTexture = ColorGradingTexture;
  88082. })(BABYLON || (BABYLON = {}));
  88083. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  88084. var BABYLON;
  88085. (function (BABYLON) {
  88086. /**
  88087. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  88088. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  88089. * 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;
  88090. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  88091. */
  88092. var ColorCurves = /** @class */ (function () {
  88093. function ColorCurves() {
  88094. this._dirty = true;
  88095. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  88096. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  88097. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88098. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  88099. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  88100. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  88101. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  88102. this._globalHue = 30;
  88103. this._globalDensity = 0;
  88104. this._globalSaturation = 0;
  88105. this._globalExposure = 0;
  88106. this._highlightsHue = 30;
  88107. this._highlightsDensity = 0;
  88108. this._highlightsSaturation = 0;
  88109. this._highlightsExposure = 0;
  88110. this._midtonesHue = 30;
  88111. this._midtonesDensity = 0;
  88112. this._midtonesSaturation = 0;
  88113. this._midtonesExposure = 0;
  88114. this._shadowsHue = 30;
  88115. this._shadowsDensity = 0;
  88116. this._shadowsSaturation = 0;
  88117. this._shadowsExposure = 0;
  88118. }
  88119. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  88120. /**
  88121. * Gets the global Hue value.
  88122. * 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).
  88123. */
  88124. get: function () {
  88125. return this._globalHue;
  88126. },
  88127. /**
  88128. * Sets the global Hue value.
  88129. * 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).
  88130. */
  88131. set: function (value) {
  88132. this._globalHue = value;
  88133. this._dirty = true;
  88134. },
  88135. enumerable: true,
  88136. configurable: true
  88137. });
  88138. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  88139. /**
  88140. * Gets the global Density value.
  88141. * 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.
  88142. * Values less than zero provide a filter of opposite hue.
  88143. */
  88144. get: function () {
  88145. return this._globalDensity;
  88146. },
  88147. /**
  88148. * Sets the global Density value.
  88149. * 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.
  88150. * Values less than zero provide a filter of opposite hue.
  88151. */
  88152. set: function (value) {
  88153. this._globalDensity = value;
  88154. this._dirty = true;
  88155. },
  88156. enumerable: true,
  88157. configurable: true
  88158. });
  88159. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  88160. /**
  88161. * Gets the global Saturation value.
  88162. * 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.
  88163. */
  88164. get: function () {
  88165. return this._globalSaturation;
  88166. },
  88167. /**
  88168. * Sets the global Saturation value.
  88169. * 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.
  88170. */
  88171. set: function (value) {
  88172. this._globalSaturation = value;
  88173. this._dirty = true;
  88174. },
  88175. enumerable: true,
  88176. configurable: true
  88177. });
  88178. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  88179. /**
  88180. * Gets the global Exposure value.
  88181. * 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.
  88182. */
  88183. get: function () {
  88184. return this._globalExposure;
  88185. },
  88186. /**
  88187. * Sets the global Exposure value.
  88188. * 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.
  88189. */
  88190. set: function (value) {
  88191. this._globalExposure = value;
  88192. this._dirty = true;
  88193. },
  88194. enumerable: true,
  88195. configurable: true
  88196. });
  88197. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  88198. /**
  88199. * Gets the highlights Hue value.
  88200. * 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).
  88201. */
  88202. get: function () {
  88203. return this._highlightsHue;
  88204. },
  88205. /**
  88206. * Sets the highlights Hue value.
  88207. * 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).
  88208. */
  88209. set: function (value) {
  88210. this._highlightsHue = value;
  88211. this._dirty = true;
  88212. },
  88213. enumerable: true,
  88214. configurable: true
  88215. });
  88216. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  88217. /**
  88218. * Gets the highlights Density value.
  88219. * 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.
  88220. * Values less than zero provide a filter of opposite hue.
  88221. */
  88222. get: function () {
  88223. return this._highlightsDensity;
  88224. },
  88225. /**
  88226. * Sets the highlights Density value.
  88227. * 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.
  88228. * Values less than zero provide a filter of opposite hue.
  88229. */
  88230. set: function (value) {
  88231. this._highlightsDensity = value;
  88232. this._dirty = true;
  88233. },
  88234. enumerable: true,
  88235. configurable: true
  88236. });
  88237. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  88238. /**
  88239. * Gets the highlights Saturation value.
  88240. * 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.
  88241. */
  88242. get: function () {
  88243. return this._highlightsSaturation;
  88244. },
  88245. /**
  88246. * Sets the highlights Saturation value.
  88247. * 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.
  88248. */
  88249. set: function (value) {
  88250. this._highlightsSaturation = value;
  88251. this._dirty = true;
  88252. },
  88253. enumerable: true,
  88254. configurable: true
  88255. });
  88256. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  88257. /**
  88258. * Gets the highlights Exposure value.
  88259. * 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.
  88260. */
  88261. get: function () {
  88262. return this._highlightsExposure;
  88263. },
  88264. /**
  88265. * Sets the highlights Exposure value.
  88266. * 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.
  88267. */
  88268. set: function (value) {
  88269. this._highlightsExposure = value;
  88270. this._dirty = true;
  88271. },
  88272. enumerable: true,
  88273. configurable: true
  88274. });
  88275. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  88276. /**
  88277. * Gets the midtones Hue value.
  88278. * 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).
  88279. */
  88280. get: function () {
  88281. return this._midtonesHue;
  88282. },
  88283. /**
  88284. * Sets the midtones Hue value.
  88285. * 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).
  88286. */
  88287. set: function (value) {
  88288. this._midtonesHue = value;
  88289. this._dirty = true;
  88290. },
  88291. enumerable: true,
  88292. configurable: true
  88293. });
  88294. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  88295. /**
  88296. * Gets the midtones Density value.
  88297. * 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.
  88298. * Values less than zero provide a filter of opposite hue.
  88299. */
  88300. get: function () {
  88301. return this._midtonesDensity;
  88302. },
  88303. /**
  88304. * Sets the midtones Density value.
  88305. * 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.
  88306. * Values less than zero provide a filter of opposite hue.
  88307. */
  88308. set: function (value) {
  88309. this._midtonesDensity = value;
  88310. this._dirty = true;
  88311. },
  88312. enumerable: true,
  88313. configurable: true
  88314. });
  88315. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  88316. /**
  88317. * Gets the midtones Saturation value.
  88318. * 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.
  88319. */
  88320. get: function () {
  88321. return this._midtonesSaturation;
  88322. },
  88323. /**
  88324. * Sets the midtones Saturation value.
  88325. * 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.
  88326. */
  88327. set: function (value) {
  88328. this._midtonesSaturation = value;
  88329. this._dirty = true;
  88330. },
  88331. enumerable: true,
  88332. configurable: true
  88333. });
  88334. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  88335. /**
  88336. * Gets the midtones Exposure value.
  88337. * 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.
  88338. */
  88339. get: function () {
  88340. return this._midtonesExposure;
  88341. },
  88342. /**
  88343. * Sets the midtones Exposure value.
  88344. * 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.
  88345. */
  88346. set: function (value) {
  88347. this._midtonesExposure = value;
  88348. this._dirty = true;
  88349. },
  88350. enumerable: true,
  88351. configurable: true
  88352. });
  88353. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  88354. /**
  88355. * Gets the shadows Hue value.
  88356. * 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).
  88357. */
  88358. get: function () {
  88359. return this._shadowsHue;
  88360. },
  88361. /**
  88362. * Sets the shadows Hue value.
  88363. * 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).
  88364. */
  88365. set: function (value) {
  88366. this._shadowsHue = value;
  88367. this._dirty = true;
  88368. },
  88369. enumerable: true,
  88370. configurable: true
  88371. });
  88372. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  88373. /**
  88374. * Gets the shadows Density value.
  88375. * 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.
  88376. * Values less than zero provide a filter of opposite hue.
  88377. */
  88378. get: function () {
  88379. return this._shadowsDensity;
  88380. },
  88381. /**
  88382. * Sets the shadows Density value.
  88383. * 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.
  88384. * Values less than zero provide a filter of opposite hue.
  88385. */
  88386. set: function (value) {
  88387. this._shadowsDensity = value;
  88388. this._dirty = true;
  88389. },
  88390. enumerable: true,
  88391. configurable: true
  88392. });
  88393. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  88394. /**
  88395. * Gets the shadows Saturation value.
  88396. * 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.
  88397. */
  88398. get: function () {
  88399. return this._shadowsSaturation;
  88400. },
  88401. /**
  88402. * Sets the shadows Saturation value.
  88403. * 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.
  88404. */
  88405. set: function (value) {
  88406. this._shadowsSaturation = value;
  88407. this._dirty = true;
  88408. },
  88409. enumerable: true,
  88410. configurable: true
  88411. });
  88412. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  88413. /**
  88414. * Gets the shadows Exposure value.
  88415. * 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.
  88416. */
  88417. get: function () {
  88418. return this._shadowsExposure;
  88419. },
  88420. /**
  88421. * Sets the shadows Exposure value.
  88422. * 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.
  88423. */
  88424. set: function (value) {
  88425. this._shadowsExposure = value;
  88426. this._dirty = true;
  88427. },
  88428. enumerable: true,
  88429. configurable: true
  88430. });
  88431. /**
  88432. * Returns the class name
  88433. * @returns The class name
  88434. */
  88435. ColorCurves.prototype.getClassName = function () {
  88436. return "ColorCurves";
  88437. };
  88438. /**
  88439. * Binds the color curves to the shader.
  88440. * @param colorCurves The color curve to bind
  88441. * @param effect The effect to bind to
  88442. * @param positiveUniform The positive uniform shader parameter
  88443. * @param neutralUniform The neutral uniform shader parameter
  88444. * @param negativeUniform The negative uniform shader parameter
  88445. */
  88446. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  88447. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  88448. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  88449. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  88450. if (colorCurves._dirty) {
  88451. colorCurves._dirty = false;
  88452. // Fill in global info.
  88453. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  88454. // Compute highlights info.
  88455. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  88456. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  88457. // Compute midtones info.
  88458. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  88459. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  88460. // Compute shadows info.
  88461. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  88462. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  88463. // Compute deltas (neutral is midtones).
  88464. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  88465. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  88466. }
  88467. if (effect) {
  88468. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  88469. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  88470. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  88471. }
  88472. };
  88473. /**
  88474. * Prepare the list of uniforms associated with the ColorCurves effects.
  88475. * @param uniformsList The list of uniforms used in the effect
  88476. */
  88477. ColorCurves.PrepareUniforms = function (uniformsList) {
  88478. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  88479. };
  88480. /**
  88481. * Returns color grading data based on a hue, density, saturation and exposure value.
  88482. * @param filterHue The hue of the color filter.
  88483. * @param filterDensity The density of the color filter.
  88484. * @param saturation The saturation.
  88485. * @param exposure The exposure.
  88486. * @param result The result data container.
  88487. */
  88488. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  88489. if (hue == null) {
  88490. return;
  88491. }
  88492. hue = ColorCurves.clamp(hue, 0, 360);
  88493. density = ColorCurves.clamp(density, -100, 100);
  88494. saturation = ColorCurves.clamp(saturation, -100, 100);
  88495. exposure = ColorCurves.clamp(exposure, -100, 100);
  88496. // Remap the slider/config filter density with non-linear mapping and also scale by half
  88497. // so that the maximum filter density is only 50% control. This provides fine control
  88498. // for small values and reasonable range.
  88499. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  88500. density *= 0.5;
  88501. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  88502. if (density < 0) {
  88503. density *= -1;
  88504. hue = (hue + 180) % 360;
  88505. }
  88506. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  88507. result.scaleToRef(2, result);
  88508. result.a = 1 + 0.01 * saturation;
  88509. };
  88510. /**
  88511. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  88512. * @param value The input slider value in range [-100,100].
  88513. * @returns Adjusted value.
  88514. */
  88515. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  88516. value /= 100;
  88517. var x = Math.abs(value);
  88518. x = Math.pow(x, 2);
  88519. if (value < 0) {
  88520. x *= -1;
  88521. }
  88522. x *= 100;
  88523. return x;
  88524. };
  88525. /**
  88526. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  88527. * @param hue The hue (H) input.
  88528. * @param saturation The saturation (S) input.
  88529. * @param brightness The brightness (B) input.
  88530. * @result An RGBA color represented as Vector4.
  88531. */
  88532. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  88533. var h = ColorCurves.clamp(hue, 0, 360);
  88534. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  88535. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  88536. if (s === 0) {
  88537. result.r = v;
  88538. result.g = v;
  88539. result.b = v;
  88540. }
  88541. else {
  88542. // sector 0 to 5
  88543. h /= 60;
  88544. var i = Math.floor(h);
  88545. // fractional part of h
  88546. var f = h - i;
  88547. var p = v * (1 - s);
  88548. var q = v * (1 - s * f);
  88549. var t = v * (1 - s * (1 - f));
  88550. switch (i) {
  88551. case 0:
  88552. result.r = v;
  88553. result.g = t;
  88554. result.b = p;
  88555. break;
  88556. case 1:
  88557. result.r = q;
  88558. result.g = v;
  88559. result.b = p;
  88560. break;
  88561. case 2:
  88562. result.r = p;
  88563. result.g = v;
  88564. result.b = t;
  88565. break;
  88566. case 3:
  88567. result.r = p;
  88568. result.g = q;
  88569. result.b = v;
  88570. break;
  88571. case 4:
  88572. result.r = t;
  88573. result.g = p;
  88574. result.b = v;
  88575. break;
  88576. default: // case 5:
  88577. result.r = v;
  88578. result.g = p;
  88579. result.b = q;
  88580. break;
  88581. }
  88582. }
  88583. result.a = 1;
  88584. };
  88585. /**
  88586. * Returns a value clamped between min and max
  88587. * @param value The value to clamp
  88588. * @param min The minimum of value
  88589. * @param max The maximum of value
  88590. * @returns The clamped value.
  88591. */
  88592. ColorCurves.clamp = function (value, min, max) {
  88593. return Math.min(Math.max(value, min), max);
  88594. };
  88595. /**
  88596. * Clones the current color curve instance.
  88597. * @return The cloned curves
  88598. */
  88599. ColorCurves.prototype.clone = function () {
  88600. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  88601. };
  88602. /**
  88603. * Serializes the current color curve instance to a json representation.
  88604. * @return a JSON representation
  88605. */
  88606. ColorCurves.prototype.serialize = function () {
  88607. return BABYLON.SerializationHelper.Serialize(this);
  88608. };
  88609. /**
  88610. * Parses the color curve from a json representation.
  88611. * @param source the JSON source to parse
  88612. * @return The parsed curves
  88613. */
  88614. ColorCurves.Parse = function (source) {
  88615. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  88616. };
  88617. __decorate([
  88618. BABYLON.serialize()
  88619. ], ColorCurves.prototype, "_globalHue", void 0);
  88620. __decorate([
  88621. BABYLON.serialize()
  88622. ], ColorCurves.prototype, "_globalDensity", void 0);
  88623. __decorate([
  88624. BABYLON.serialize()
  88625. ], ColorCurves.prototype, "_globalSaturation", void 0);
  88626. __decorate([
  88627. BABYLON.serialize()
  88628. ], ColorCurves.prototype, "_globalExposure", void 0);
  88629. __decorate([
  88630. BABYLON.serialize()
  88631. ], ColorCurves.prototype, "_highlightsHue", void 0);
  88632. __decorate([
  88633. BABYLON.serialize()
  88634. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  88635. __decorate([
  88636. BABYLON.serialize()
  88637. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  88638. __decorate([
  88639. BABYLON.serialize()
  88640. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  88641. __decorate([
  88642. BABYLON.serialize()
  88643. ], ColorCurves.prototype, "_midtonesHue", void 0);
  88644. __decorate([
  88645. BABYLON.serialize()
  88646. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  88647. __decorate([
  88648. BABYLON.serialize()
  88649. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  88650. __decorate([
  88651. BABYLON.serialize()
  88652. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  88653. return ColorCurves;
  88654. }());
  88655. BABYLON.ColorCurves = ColorCurves;
  88656. })(BABYLON || (BABYLON = {}));
  88657. //# sourceMappingURL=babylon.colorCurves.js.map
  88658. var BABYLON;
  88659. (function (BABYLON) {
  88660. /**
  88661. * Post process which applies a refractin texture
  88662. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88663. */
  88664. var RefractionPostProcess = /** @class */ (function (_super) {
  88665. __extends(RefractionPostProcess, _super);
  88666. /**
  88667. * Initializes the RefractionPostProcess
  88668. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#refraction
  88669. * @param name The name of the effect.
  88670. * @param refractionTextureUrl Url of the refraction texture to use
  88671. * @param color the base color of the refraction (used to taint the rendering)
  88672. * @param depth simulated refraction depth
  88673. * @param colorLevel the coefficient of the base color (0 to remove base color tainting)
  88674. * @param camera The camera to apply the render pass to.
  88675. * @param options The required width/height ratio to downsize to before computing the render pass.
  88676. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88677. * @param engine The engine which the post process will be applied. (default: current engine)
  88678. * @param reusable If the post process can be reused on the same frame. (default: false)
  88679. */
  88680. function RefractionPostProcess(name, refractionTextureUrl,
  88681. /** the base color of the refraction (used to taint the rendering) */
  88682. color,
  88683. /** simulated refraction depth */
  88684. depth,
  88685. /** the coefficient of the base color (0 to remove base color tainting) */
  88686. colorLevel, options, camera, samplingMode, engine, reusable) {
  88687. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  88688. _this.color = color;
  88689. _this.depth = depth;
  88690. _this.colorLevel = colorLevel;
  88691. _this._ownRefractionTexture = true;
  88692. _this.onActivateObservable.add(function (cam) {
  88693. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  88694. });
  88695. _this.onApplyObservable.add(function (effect) {
  88696. effect.setColor3("baseColor", _this.color);
  88697. effect.setFloat("depth", _this.depth);
  88698. effect.setFloat("colorLevel", _this.colorLevel);
  88699. effect.setTexture("refractionSampler", _this._refTexture);
  88700. });
  88701. return _this;
  88702. }
  88703. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  88704. /**
  88705. * Gets or sets the refraction texture
  88706. * Please note that you are responsible for disposing the texture if you set it manually
  88707. */
  88708. get: function () {
  88709. return this._refTexture;
  88710. },
  88711. set: function (value) {
  88712. if (this._refTexture && this._ownRefractionTexture) {
  88713. this._refTexture.dispose();
  88714. }
  88715. this._refTexture = value;
  88716. this._ownRefractionTexture = false;
  88717. },
  88718. enumerable: true,
  88719. configurable: true
  88720. });
  88721. // Methods
  88722. /**
  88723. * Disposes of the post process
  88724. * @param camera Camera to dispose post process on
  88725. */
  88726. RefractionPostProcess.prototype.dispose = function (camera) {
  88727. if (this._refTexture && this._ownRefractionTexture) {
  88728. this._refTexture.dispose();
  88729. this._refTexture = null;
  88730. }
  88731. _super.prototype.dispose.call(this, camera);
  88732. };
  88733. return RefractionPostProcess;
  88734. }(BABYLON.PostProcess));
  88735. BABYLON.RefractionPostProcess = RefractionPostProcess;
  88736. })(BABYLON || (BABYLON = {}));
  88737. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  88738. var BABYLON;
  88739. (function (BABYLON) {
  88740. /**
  88741. * Post process used to render in black and white
  88742. */
  88743. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  88744. __extends(BlackAndWhitePostProcess, _super);
  88745. /**
  88746. * Creates a black and white post process
  88747. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#black-and-white
  88748. * @param name The name of the effect.
  88749. * @param options The required width/height ratio to downsize to before computing the render pass.
  88750. * @param camera The camera to apply the render pass to.
  88751. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88752. * @param engine The engine which the post process will be applied. (default: current engine)
  88753. * @param reusable If the post process can be reused on the same frame. (default: false)
  88754. */
  88755. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  88756. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  88757. /**
  88758. * Linear about to convert he result to black and white (default: 1)
  88759. */
  88760. _this.degree = 1;
  88761. _this.onApplyObservable.add(function (effect) {
  88762. effect.setFloat("degree", _this.degree);
  88763. });
  88764. return _this;
  88765. }
  88766. return BlackAndWhitePostProcess;
  88767. }(BABYLON.PostProcess));
  88768. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  88769. })(BABYLON || (BABYLON = {}));
  88770. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  88771. var BABYLON;
  88772. (function (BABYLON) {
  88773. /**
  88774. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  88775. * input texture to perform effects such as edge detection or sharpening
  88776. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  88777. */
  88778. var ConvolutionPostProcess = /** @class */ (function (_super) {
  88779. __extends(ConvolutionPostProcess, _super);
  88780. /**
  88781. * Creates a new instance ConvolutionPostProcess
  88782. * @param name The name of the effect.
  88783. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  88784. * @param options The required width/height ratio to downsize to before computing the render pass.
  88785. * @param camera The camera to apply the render pass to.
  88786. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88787. * @param engine The engine which the post process will be applied. (default: current engine)
  88788. * @param reusable If the post process can be reused on the same frame. (default: false)
  88789. * @param textureType Type of textures used when performing the post process. (default: 0)
  88790. */
  88791. function ConvolutionPostProcess(name,
  88792. /** Array of 9 values corrisponding to the 3x3 kernel to be applied */
  88793. kernel, options, camera, samplingMode, engine, reusable, textureType) {
  88794. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  88795. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  88796. _this.kernel = kernel;
  88797. _this.onApply = function (effect) {
  88798. effect.setFloat2("screenSize", _this.width, _this.height);
  88799. effect.setArray("kernel", _this.kernel);
  88800. };
  88801. return _this;
  88802. }
  88803. // Statics
  88804. /**
  88805. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88806. */
  88807. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  88808. /**
  88809. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88810. */
  88811. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  88812. /**
  88813. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88814. */
  88815. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  88816. /**
  88817. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88818. */
  88819. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  88820. /**
  88821. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88822. */
  88823. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  88824. /**
  88825. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  88826. */
  88827. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  88828. return ConvolutionPostProcess;
  88829. }(BABYLON.PostProcess));
  88830. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  88831. })(BABYLON || (BABYLON = {}));
  88832. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  88833. var BABYLON;
  88834. (function (BABYLON) {
  88835. /**
  88836. * Applies a kernel filter to the image
  88837. */
  88838. var FilterPostProcess = /** @class */ (function (_super) {
  88839. __extends(FilterPostProcess, _super);
  88840. /**
  88841. *
  88842. * @param name The name of the effect.
  88843. * @param kernelMatrix The matrix to be applied to the image
  88844. * @param options The required width/height ratio to downsize to before computing the render pass.
  88845. * @param camera The camera to apply the render pass to.
  88846. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  88847. * @param engine The engine which the post process will be applied. (default: current engine)
  88848. * @param reusable If the post process can be reused on the same frame. (default: false)
  88849. */
  88850. function FilterPostProcess(name,
  88851. /** The matrix to be applied to the image */
  88852. kernelMatrix, options, camera, samplingMode, engine, reusable) {
  88853. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  88854. _this.kernelMatrix = kernelMatrix;
  88855. _this.onApply = function (effect) {
  88856. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  88857. };
  88858. return _this;
  88859. }
  88860. return FilterPostProcess;
  88861. }(BABYLON.PostProcess));
  88862. BABYLON.FilterPostProcess = FilterPostProcess;
  88863. })(BABYLON || (BABYLON = {}));
  88864. //# sourceMappingURL=babylon.filterPostProcess.js.map
  88865. var BABYLON;
  88866. (function (BABYLON) {
  88867. /**
  88868. * Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  88869. */
  88870. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  88871. __extends(VolumetricLightScatteringPostProcess, _super);
  88872. /**
  88873. * @constructor
  88874. * @param name The post-process name
  88875. * @param 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)
  88876. * @param camera The camera that the post-process will be attached to
  88877. * @param mesh The mesh used to create the light scattering
  88878. * @param samples The post-process quality, default 100
  88879. * @param samplingModeThe post-process filtering mode
  88880. * @param engine The babylon engine
  88881. * @param reusable If the post-process is reusable
  88882. * @param scene The constructor needs a scene reference to initialize internal components. If "camera" is null a "scene" must be provided
  88883. */
  88884. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  88885. if (samples === void 0) { samples = 100; }
  88886. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  88887. 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;
  88888. _this._screenCoordinates = BABYLON.Vector2.Zero();
  88889. /**
  88890. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  88891. */
  88892. _this.customMeshPosition = BABYLON.Vector3.Zero();
  88893. /**
  88894. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  88895. */
  88896. _this.useCustomMeshPosition = false;
  88897. /**
  88898. * If the post-process should inverse the light scattering direction
  88899. */
  88900. _this.invert = true;
  88901. /**
  88902. * Array containing the excluded meshes not rendered in the internal pass
  88903. */
  88904. _this.excludedMeshes = new Array();
  88905. /**
  88906. * Controls the overall intensity of the post-process
  88907. */
  88908. _this.exposure = 0.3;
  88909. /**
  88910. * Dissipates each sample's contribution in range [0, 1]
  88911. */
  88912. _this.decay = 0.96815;
  88913. /**
  88914. * Controls the overall intensity of each sample
  88915. */
  88916. _this.weight = 0.58767;
  88917. /**
  88918. * Controls the density of each sample
  88919. */
  88920. _this.density = 0.926;
  88921. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  88922. engine = scene.getEngine();
  88923. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  88924. // Configure mesh
  88925. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  88926. // Configure
  88927. _this._createPass(scene, ratio.passRatio || ratio);
  88928. _this.onActivate = function (camera) {
  88929. if (!_this.isSupported) {
  88930. _this.dispose(camera);
  88931. }
  88932. _this.onActivate = null;
  88933. };
  88934. _this.onApplyObservable.add(function (effect) {
  88935. _this._updateMeshScreenCoordinates(scene);
  88936. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  88937. effect.setFloat("exposure", _this.exposure);
  88938. effect.setFloat("decay", _this.decay);
  88939. effect.setFloat("weight", _this.weight);
  88940. effect.setFloat("density", _this.density);
  88941. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  88942. });
  88943. return _this;
  88944. }
  88945. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  88946. /**
  88947. * @hidden
  88948. * VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead
  88949. */
  88950. get: function () {
  88951. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  88952. return false;
  88953. },
  88954. set: function (useDiffuseColor) {
  88955. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  88956. },
  88957. enumerable: true,
  88958. configurable: true
  88959. });
  88960. /**
  88961. * Returns the string "VolumetricLightScatteringPostProcess"
  88962. * @returns "VolumetricLightScatteringPostProcess"
  88963. */
  88964. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  88965. return "VolumetricLightScatteringPostProcess";
  88966. };
  88967. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  88968. var mesh = subMesh.getMesh();
  88969. // Render this.mesh as default
  88970. if (mesh === this.mesh && mesh.material) {
  88971. return mesh.material.isReady(mesh);
  88972. }
  88973. var defines = [];
  88974. var attribs = [BABYLON.VertexBuffer.PositionKind];
  88975. var material = subMesh.getMaterial();
  88976. // Alpha test
  88977. if (material) {
  88978. if (material.needAlphaTesting()) {
  88979. defines.push("#define ALPHATEST");
  88980. }
  88981. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  88982. attribs.push(BABYLON.VertexBuffer.UVKind);
  88983. defines.push("#define UV1");
  88984. }
  88985. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  88986. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  88987. defines.push("#define UV2");
  88988. }
  88989. }
  88990. // Bones
  88991. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  88992. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  88993. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  88994. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  88995. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  88996. }
  88997. else {
  88998. defines.push("#define NUM_BONE_INFLUENCERS 0");
  88999. }
  89000. // Instances
  89001. if (useInstances) {
  89002. defines.push("#define INSTANCES");
  89003. attribs.push("world0");
  89004. attribs.push("world1");
  89005. attribs.push("world2");
  89006. attribs.push("world3");
  89007. }
  89008. // Get correct effect
  89009. var join = defines.join("\n");
  89010. if (this._cachedDefines !== join) {
  89011. this._cachedDefines = join;
  89012. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  89013. }
  89014. return this._volumetricLightScatteringPass.isReady();
  89015. };
  89016. /**
  89017. * Sets the new light position for light scattering effect
  89018. * @param position The new custom light position
  89019. */
  89020. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  89021. this.customMeshPosition = position;
  89022. };
  89023. /**
  89024. * Returns the light position for light scattering effect
  89025. * @return Vector3 The custom light position
  89026. */
  89027. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  89028. return this.customMeshPosition;
  89029. };
  89030. /**
  89031. * Disposes the internal assets and detaches the post-process from the camera
  89032. */
  89033. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  89034. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  89035. if (rttIndex !== -1) {
  89036. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  89037. }
  89038. this._volumetricLightScatteringRTT.dispose();
  89039. _super.prototype.dispose.call(this, camera);
  89040. };
  89041. /**
  89042. * Returns the render target texture used by the post-process
  89043. * @return the render target texture used by the post-process
  89044. */
  89045. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  89046. return this._volumetricLightScatteringRTT;
  89047. };
  89048. // Private methods
  89049. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  89050. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  89051. return true;
  89052. }
  89053. return false;
  89054. };
  89055. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  89056. var _this = this;
  89057. var engine = scene.getEngine();
  89058. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  89059. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89060. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89061. this._volumetricLightScatteringRTT.renderList = null;
  89062. this._volumetricLightScatteringRTT.renderParticles = false;
  89063. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  89064. var camera = this.getCamera();
  89065. if (camera) {
  89066. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89067. }
  89068. else {
  89069. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  89070. }
  89071. // Custom render function for submeshes
  89072. var renderSubMesh = function (subMesh) {
  89073. var mesh = subMesh.getRenderingMesh();
  89074. if (_this._meshExcluded(mesh)) {
  89075. return;
  89076. }
  89077. var material = subMesh.getMaterial();
  89078. if (!material) {
  89079. return;
  89080. }
  89081. var scene = mesh.getScene();
  89082. var engine = scene.getEngine();
  89083. // Culling
  89084. engine.setState(material.backFaceCulling);
  89085. // Managing instances
  89086. var batch = mesh._getInstancesRenderList(subMesh._id);
  89087. if (batch.mustReturn) {
  89088. return;
  89089. }
  89090. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  89091. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  89092. var effect = _this._volumetricLightScatteringPass;
  89093. if (mesh === _this.mesh) {
  89094. if (subMesh.effect) {
  89095. effect = subMesh.effect;
  89096. }
  89097. else {
  89098. effect = material.getEffect();
  89099. }
  89100. }
  89101. engine.enableEffect(effect);
  89102. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  89103. if (mesh === _this.mesh) {
  89104. material.bind(mesh.getWorldMatrix(), mesh);
  89105. }
  89106. else {
  89107. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  89108. // Alpha test
  89109. if (material && material.needAlphaTesting()) {
  89110. var alphaTexture = material.getAlphaTestTexture();
  89111. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  89112. if (alphaTexture) {
  89113. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  89114. }
  89115. }
  89116. // Bones
  89117. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  89118. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  89119. }
  89120. }
  89121. // Draw
  89122. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  89123. }
  89124. };
  89125. // Render target texture callbacks
  89126. var savedSceneClearColor;
  89127. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  89128. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  89129. savedSceneClearColor = scene.clearColor;
  89130. scene.clearColor = sceneClearColor;
  89131. });
  89132. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  89133. scene.clearColor = savedSceneClearColor;
  89134. });
  89135. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  89136. var engine = scene.getEngine();
  89137. var index;
  89138. if (depthOnlySubMeshes.length) {
  89139. engine.setColorWrite(false);
  89140. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  89141. renderSubMesh(depthOnlySubMeshes.data[index]);
  89142. }
  89143. engine.setColorWrite(true);
  89144. }
  89145. for (index = 0; index < opaqueSubMeshes.length; index++) {
  89146. renderSubMesh(opaqueSubMeshes.data[index]);
  89147. }
  89148. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  89149. renderSubMesh(alphaTestSubMeshes.data[index]);
  89150. }
  89151. if (transparentSubMeshes.length) {
  89152. // Sort sub meshes
  89153. for (index = 0; index < transparentSubMeshes.length; index++) {
  89154. var submesh = transparentSubMeshes.data[index];
  89155. var boundingInfo = submesh.getBoundingInfo();
  89156. if (boundingInfo && scene.activeCamera) {
  89157. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  89158. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  89159. }
  89160. }
  89161. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  89162. sortedArray.sort(function (a, b) {
  89163. // Alpha index first
  89164. if (a._alphaIndex > b._alphaIndex) {
  89165. return 1;
  89166. }
  89167. if (a._alphaIndex < b._alphaIndex) {
  89168. return -1;
  89169. }
  89170. // Then distance to camera
  89171. if (a._distanceToCamera < b._distanceToCamera) {
  89172. return 1;
  89173. }
  89174. if (a._distanceToCamera > b._distanceToCamera) {
  89175. return -1;
  89176. }
  89177. return 0;
  89178. });
  89179. // Render sub meshes
  89180. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  89181. for (index = 0; index < sortedArray.length; index++) {
  89182. renderSubMesh(sortedArray[index]);
  89183. }
  89184. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  89185. }
  89186. };
  89187. };
  89188. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  89189. var transform = scene.getTransformMatrix();
  89190. var meshPosition;
  89191. if (this.useCustomMeshPosition) {
  89192. meshPosition = this.customMeshPosition;
  89193. }
  89194. else if (this.attachedNode) {
  89195. meshPosition = this.attachedNode.position;
  89196. }
  89197. else {
  89198. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  89199. }
  89200. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  89201. this._screenCoordinates.x = pos.x / this._viewPort.width;
  89202. this._screenCoordinates.y = pos.y / this._viewPort.height;
  89203. if (this.invert)
  89204. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  89205. };
  89206. // Static methods
  89207. /**
  89208. * Creates a default mesh for the Volumeric Light Scattering post-process
  89209. * @param name The mesh name
  89210. * @param scene The scene where to create the mesh
  89211. * @return the default mesh
  89212. */
  89213. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  89214. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  89215. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  89216. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  89217. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  89218. mesh.material = material;
  89219. return mesh;
  89220. };
  89221. __decorate([
  89222. BABYLON.serializeAsVector3()
  89223. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  89224. __decorate([
  89225. BABYLON.serialize()
  89226. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  89227. __decorate([
  89228. BABYLON.serialize()
  89229. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  89230. __decorate([
  89231. BABYLON.serializeAsMeshReference()
  89232. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  89233. __decorate([
  89234. BABYLON.serialize()
  89235. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  89236. __decorate([
  89237. BABYLON.serialize()
  89238. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  89239. __decorate([
  89240. BABYLON.serialize()
  89241. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  89242. __decorate([
  89243. BABYLON.serialize()
  89244. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  89245. __decorate([
  89246. BABYLON.serialize()
  89247. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  89248. return VolumetricLightScatteringPostProcess;
  89249. }(BABYLON.PostProcess));
  89250. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  89251. })(BABYLON || (BABYLON = {}));
  89252. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  89253. var BABYLON;
  89254. (function (BABYLON) {
  89255. /**
  89256. *
  89257. * This post-process allows the modification of rendered colors by using
  89258. * a 'look-up table' (LUT). This effect is also called Color Grading.
  89259. *
  89260. * The object needs to be provided an url to a texture containing the color
  89261. * look-up table: the texture must be 256 pixels wide and 16 pixels high.
  89262. * Use an image editing software to tweak the LUT to match your needs.
  89263. *
  89264. * For an example of a color LUT, see here:
  89265. * @see http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  89266. * For explanations on color grading, see here:
  89267. * @see http://udn.epicgames.com/Three/ColorGrading.html
  89268. *
  89269. */
  89270. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  89271. __extends(ColorCorrectionPostProcess, _super);
  89272. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  89273. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  89274. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  89275. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  89276. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89277. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  89278. _this.onApply = function (effect) {
  89279. effect.setTexture("colorTable", _this._colorTableTexture);
  89280. };
  89281. return _this;
  89282. }
  89283. return ColorCorrectionPostProcess;
  89284. }(BABYLON.PostProcess));
  89285. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  89286. })(BABYLON || (BABYLON = {}));
  89287. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  89288. var BABYLON;
  89289. (function (BABYLON) {
  89290. /** Defines operator used for tonemapping */
  89291. var TonemappingOperator;
  89292. (function (TonemappingOperator) {
  89293. /** Hable */
  89294. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  89295. /** Reinhard */
  89296. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  89297. /** HejiDawson */
  89298. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  89299. /** Photographic */
  89300. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  89301. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  89302. ;
  89303. /**
  89304. * Defines a post process to apply tone mapping
  89305. */
  89306. var TonemapPostProcess = /** @class */ (function (_super) {
  89307. __extends(TonemapPostProcess, _super);
  89308. /**
  89309. * Creates a new TonemapPostProcess
  89310. * @param name defines the name of the postprocess
  89311. * @param _operator defines the operator to use
  89312. * @param exposureAdjustment defines the required exposure adjustement
  89313. * @param camera defines the camera to use (can be null)
  89314. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  89315. * @param engine defines the hosting engine (can be ignore if camera is set)
  89316. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  89317. */
  89318. function TonemapPostProcess(name, _operator,
  89319. /** Defines the required exposure adjustement */
  89320. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  89321. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  89322. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89323. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  89324. _this._operator = _operator;
  89325. _this.exposureAdjustment = exposureAdjustment;
  89326. var defines = "#define ";
  89327. if (_this._operator === TonemappingOperator.Hable)
  89328. defines += "HABLE_TONEMAPPING";
  89329. else if (_this._operator === TonemappingOperator.Reinhard)
  89330. defines += "REINHARD_TONEMAPPING";
  89331. else if (_this._operator === TonemappingOperator.HejiDawson)
  89332. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  89333. else if (_this._operator === TonemappingOperator.Photographic)
  89334. defines += "PHOTOGRAPHIC_TONEMAPPING";
  89335. //sadly a second call to create the effect.
  89336. _this.updateEffect(defines);
  89337. _this.onApply = function (effect) {
  89338. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  89339. };
  89340. return _this;
  89341. }
  89342. return TonemapPostProcess;
  89343. }(BABYLON.PostProcess));
  89344. BABYLON.TonemapPostProcess = TonemapPostProcess;
  89345. })(BABYLON || (BABYLON = {}));
  89346. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  89347. var BABYLON;
  89348. (function (BABYLON) {
  89349. /**
  89350. * DisplayPassPostProcess which produces an output the same as it's input
  89351. */
  89352. var DisplayPassPostProcess = /** @class */ (function (_super) {
  89353. __extends(DisplayPassPostProcess, _super);
  89354. /**
  89355. * Creates the DisplayPassPostProcess
  89356. * @param name The name of the effect.
  89357. * @param options The required width/height ratio to downsize to before computing the render pass.
  89358. * @param camera The camera to apply the render pass to.
  89359. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89360. * @param engine The engine which the post process will be applied. (default: current engine)
  89361. * @param reusable If the post process can be reused on the same frame. (default: false)
  89362. */
  89363. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  89364. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  89365. }
  89366. return DisplayPassPostProcess;
  89367. }(BABYLON.PostProcess));
  89368. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  89369. })(BABYLON || (BABYLON = {}));
  89370. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  89371. var BABYLON;
  89372. (function (BABYLON) {
  89373. /**
  89374. * Extracts highlights from the image
  89375. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89376. */
  89377. var HighlightsPostProcess = /** @class */ (function (_super) {
  89378. __extends(HighlightsPostProcess, _super);
  89379. /**
  89380. * Extracts highlights from the image
  89381. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  89382. * @param name The name of the effect.
  89383. * @param options The required width/height ratio to downsize to before computing the render pass.
  89384. * @param camera The camera to apply the render pass to.
  89385. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  89386. * @param engine The engine which the post process will be applied. (default: current engine)
  89387. * @param reusable If the post process can be reused on the same frame. (default: false)
  89388. * @param textureType Type of texture for the post process (default: Engine.TEXTURETYPE_UNSIGNED_INT)
  89389. */
  89390. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  89391. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89392. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  89393. }
  89394. return HighlightsPostProcess;
  89395. }(BABYLON.PostProcess));
  89396. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  89397. })(BABYLON || (BABYLON = {}));
  89398. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  89399. var BABYLON;
  89400. (function (BABYLON) {
  89401. /**
  89402. * ImageProcessingPostProcess
  89403. * @see https://doc.babylonjs.com/how_to/how_to_use_postprocesses#imageprocessing
  89404. */
  89405. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  89406. __extends(ImageProcessingPostProcess, _super);
  89407. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  89408. if (camera === void 0) { camera = null; }
  89409. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  89410. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  89411. _this._fromLinearSpace = true;
  89412. /**
  89413. * Defines cache preventing GC.
  89414. */
  89415. _this._defines = {
  89416. IMAGEPROCESSING: false,
  89417. VIGNETTE: false,
  89418. VIGNETTEBLENDMODEMULTIPLY: false,
  89419. VIGNETTEBLENDMODEOPAQUE: false,
  89420. TONEMAPPING: false,
  89421. TONEMAPPING_ACES: false,
  89422. CONTRAST: false,
  89423. COLORCURVES: false,
  89424. COLORGRADING: false,
  89425. COLORGRADING3D: false,
  89426. FROMLINEARSPACE: false,
  89427. SAMPLER3DGREENDEPTH: false,
  89428. SAMPLER3DBGRMAP: false,
  89429. IMAGEPROCESSINGPOSTPROCESS: false,
  89430. EXPOSURE: false,
  89431. };
  89432. // Setup the configuration as forced by the constructor. This would then not force the
  89433. // scene materials output in linear space and let untouched the default forward pass.
  89434. if (imageProcessingConfiguration) {
  89435. imageProcessingConfiguration.applyByPostProcess = true;
  89436. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  89437. // This will cause the shader to be compiled
  89438. _this.fromLinearSpace = false;
  89439. }
  89440. // Setup the default processing configuration to the scene.
  89441. else {
  89442. _this._attachImageProcessingConfiguration(null, true);
  89443. _this.imageProcessingConfiguration.applyByPostProcess = true;
  89444. }
  89445. _this.onApply = function (effect) {
  89446. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  89447. };
  89448. return _this;
  89449. }
  89450. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  89451. /**
  89452. * Gets the image processing configuration used either in this material.
  89453. */
  89454. get: function () {
  89455. return this._imageProcessingConfiguration;
  89456. },
  89457. /**
  89458. * Sets the Default image processing configuration used either in the this material.
  89459. *
  89460. * If sets to null, the scene one is in use.
  89461. */
  89462. set: function (value) {
  89463. this._attachImageProcessingConfiguration(value);
  89464. },
  89465. enumerable: true,
  89466. configurable: true
  89467. });
  89468. /**
  89469. * Attaches a new image processing configuration to the PBR Material.
  89470. * @param configuration
  89471. */
  89472. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  89473. var _this = this;
  89474. if (doNotBuild === void 0) { doNotBuild = false; }
  89475. if (configuration === this._imageProcessingConfiguration) {
  89476. return;
  89477. }
  89478. // Detaches observer.
  89479. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89480. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89481. }
  89482. // Pick the scene configuration if needed.
  89483. if (!configuration) {
  89484. var scene = null;
  89485. var engine = this.getEngine();
  89486. var camera = this.getCamera();
  89487. if (camera) {
  89488. scene = camera.getScene();
  89489. }
  89490. else if (engine && engine.scenes) {
  89491. var scenes = engine.scenes;
  89492. scene = scenes[scenes.length - 1];
  89493. }
  89494. else {
  89495. scene = BABYLON.Engine.LastCreatedScene;
  89496. }
  89497. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  89498. }
  89499. else {
  89500. this._imageProcessingConfiguration = configuration;
  89501. }
  89502. // Attaches observer.
  89503. if (this._imageProcessingConfiguration) {
  89504. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  89505. _this._updateParameters();
  89506. });
  89507. }
  89508. // Ensure the effect will be rebuilt.
  89509. if (!doNotBuild) {
  89510. this._updateParameters();
  89511. }
  89512. };
  89513. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  89514. /**
  89515. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89516. */
  89517. get: function () {
  89518. return this.imageProcessingConfiguration.colorCurves;
  89519. },
  89520. /**
  89521. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  89522. */
  89523. set: function (value) {
  89524. this.imageProcessingConfiguration.colorCurves = value;
  89525. },
  89526. enumerable: true,
  89527. configurable: true
  89528. });
  89529. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  89530. /**
  89531. * Gets wether the color curves effect is enabled.
  89532. */
  89533. get: function () {
  89534. return this.imageProcessingConfiguration.colorCurvesEnabled;
  89535. },
  89536. /**
  89537. * Sets wether the color curves effect is enabled.
  89538. */
  89539. set: function (value) {
  89540. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  89541. },
  89542. enumerable: true,
  89543. configurable: true
  89544. });
  89545. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  89546. /**
  89547. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89548. */
  89549. get: function () {
  89550. return this.imageProcessingConfiguration.colorGradingTexture;
  89551. },
  89552. /**
  89553. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  89554. */
  89555. set: function (value) {
  89556. this.imageProcessingConfiguration.colorGradingTexture = value;
  89557. },
  89558. enumerable: true,
  89559. configurable: true
  89560. });
  89561. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  89562. /**
  89563. * Gets wether the color grading effect is enabled.
  89564. */
  89565. get: function () {
  89566. return this.imageProcessingConfiguration.colorGradingEnabled;
  89567. },
  89568. /**
  89569. * Gets wether the color grading effect is enabled.
  89570. */
  89571. set: function (value) {
  89572. this.imageProcessingConfiguration.colorGradingEnabled = value;
  89573. },
  89574. enumerable: true,
  89575. configurable: true
  89576. });
  89577. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  89578. /**
  89579. * Gets exposure used in the effect.
  89580. */
  89581. get: function () {
  89582. return this.imageProcessingConfiguration.exposure;
  89583. },
  89584. /**
  89585. * Sets exposure used in the effect.
  89586. */
  89587. set: function (value) {
  89588. this.imageProcessingConfiguration.exposure = value;
  89589. },
  89590. enumerable: true,
  89591. configurable: true
  89592. });
  89593. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  89594. /**
  89595. * Gets wether tonemapping is enabled or not.
  89596. */
  89597. get: function () {
  89598. return this._imageProcessingConfiguration.toneMappingEnabled;
  89599. },
  89600. /**
  89601. * Sets wether tonemapping is enabled or not
  89602. */
  89603. set: function (value) {
  89604. this._imageProcessingConfiguration.toneMappingEnabled = value;
  89605. },
  89606. enumerable: true,
  89607. configurable: true
  89608. });
  89609. ;
  89610. ;
  89611. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  89612. /**
  89613. * Gets contrast used in the effect.
  89614. */
  89615. get: function () {
  89616. return this.imageProcessingConfiguration.contrast;
  89617. },
  89618. /**
  89619. * Sets contrast used in the effect.
  89620. */
  89621. set: function (value) {
  89622. this.imageProcessingConfiguration.contrast = value;
  89623. },
  89624. enumerable: true,
  89625. configurable: true
  89626. });
  89627. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  89628. /**
  89629. * Gets Vignette stretch size.
  89630. */
  89631. get: function () {
  89632. return this.imageProcessingConfiguration.vignetteStretch;
  89633. },
  89634. /**
  89635. * Sets Vignette stretch size.
  89636. */
  89637. set: function (value) {
  89638. this.imageProcessingConfiguration.vignetteStretch = value;
  89639. },
  89640. enumerable: true,
  89641. configurable: true
  89642. });
  89643. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  89644. /**
  89645. * Gets Vignette centre X Offset.
  89646. */
  89647. get: function () {
  89648. return this.imageProcessingConfiguration.vignetteCentreX;
  89649. },
  89650. /**
  89651. * Sets Vignette centre X Offset.
  89652. */
  89653. set: function (value) {
  89654. this.imageProcessingConfiguration.vignetteCentreX = value;
  89655. },
  89656. enumerable: true,
  89657. configurable: true
  89658. });
  89659. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  89660. /**
  89661. * Gets Vignette centre Y Offset.
  89662. */
  89663. get: function () {
  89664. return this.imageProcessingConfiguration.vignetteCentreY;
  89665. },
  89666. /**
  89667. * Sets Vignette centre Y Offset.
  89668. */
  89669. set: function (value) {
  89670. this.imageProcessingConfiguration.vignetteCentreY = value;
  89671. },
  89672. enumerable: true,
  89673. configurable: true
  89674. });
  89675. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  89676. /**
  89677. * Gets Vignette weight or intensity of the vignette effect.
  89678. */
  89679. get: function () {
  89680. return this.imageProcessingConfiguration.vignetteWeight;
  89681. },
  89682. /**
  89683. * Sets Vignette weight or intensity of the vignette effect.
  89684. */
  89685. set: function (value) {
  89686. this.imageProcessingConfiguration.vignetteWeight = value;
  89687. },
  89688. enumerable: true,
  89689. configurable: true
  89690. });
  89691. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  89692. /**
  89693. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89694. * if vignetteEnabled is set to true.
  89695. */
  89696. get: function () {
  89697. return this.imageProcessingConfiguration.vignetteColor;
  89698. },
  89699. /**
  89700. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  89701. * if vignetteEnabled is set to true.
  89702. */
  89703. set: function (value) {
  89704. this.imageProcessingConfiguration.vignetteColor = value;
  89705. },
  89706. enumerable: true,
  89707. configurable: true
  89708. });
  89709. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  89710. /**
  89711. * Gets Camera field of view used by the Vignette effect.
  89712. */
  89713. get: function () {
  89714. return this.imageProcessingConfiguration.vignetteCameraFov;
  89715. },
  89716. /**
  89717. * Sets Camera field of view used by the Vignette effect.
  89718. */
  89719. set: function (value) {
  89720. this.imageProcessingConfiguration.vignetteCameraFov = value;
  89721. },
  89722. enumerable: true,
  89723. configurable: true
  89724. });
  89725. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  89726. /**
  89727. * Gets the vignette blend mode allowing different kind of effect.
  89728. */
  89729. get: function () {
  89730. return this.imageProcessingConfiguration.vignetteBlendMode;
  89731. },
  89732. /**
  89733. * Sets the vignette blend mode allowing different kind of effect.
  89734. */
  89735. set: function (value) {
  89736. this.imageProcessingConfiguration.vignetteBlendMode = value;
  89737. },
  89738. enumerable: true,
  89739. configurable: true
  89740. });
  89741. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  89742. /**
  89743. * Gets wether the vignette effect is enabled.
  89744. */
  89745. get: function () {
  89746. return this.imageProcessingConfiguration.vignetteEnabled;
  89747. },
  89748. /**
  89749. * Sets wether the vignette effect is enabled.
  89750. */
  89751. set: function (value) {
  89752. this.imageProcessingConfiguration.vignetteEnabled = value;
  89753. },
  89754. enumerable: true,
  89755. configurable: true
  89756. });
  89757. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  89758. /**
  89759. * Gets wether the input of the processing is in Gamma or Linear Space.
  89760. */
  89761. get: function () {
  89762. return this._fromLinearSpace;
  89763. },
  89764. /**
  89765. * Sets wether the input of the processing is in Gamma or Linear Space.
  89766. */
  89767. set: function (value) {
  89768. if (this._fromLinearSpace === value) {
  89769. return;
  89770. }
  89771. this._fromLinearSpace = value;
  89772. this._updateParameters();
  89773. },
  89774. enumerable: true,
  89775. configurable: true
  89776. });
  89777. /**
  89778. * "ImageProcessingPostProcess"
  89779. * @returns "ImageProcessingPostProcess"
  89780. */
  89781. ImageProcessingPostProcess.prototype.getClassName = function () {
  89782. return "ImageProcessingPostProcess";
  89783. };
  89784. ImageProcessingPostProcess.prototype._updateParameters = function () {
  89785. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  89786. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  89787. var defines = "";
  89788. for (var define in this._defines) {
  89789. if (this._defines[define]) {
  89790. defines += "#define " + define + ";\r\n";
  89791. }
  89792. }
  89793. var samplers = ["textureSampler"];
  89794. var uniforms = ["scale"];
  89795. if (BABYLON.ImageProcessingConfiguration) {
  89796. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  89797. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  89798. }
  89799. this.updateEffect(defines, uniforms, samplers);
  89800. };
  89801. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  89802. _super.prototype.dispose.call(this, camera);
  89803. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  89804. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  89805. }
  89806. if (this._imageProcessingConfiguration) {
  89807. this.imageProcessingConfiguration.applyByPostProcess = false;
  89808. }
  89809. };
  89810. __decorate([
  89811. BABYLON.serialize()
  89812. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  89813. return ImageProcessingPostProcess;
  89814. }(BABYLON.PostProcess));
  89815. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  89816. })(BABYLON || (BABYLON = {}));
  89817. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  89818. var BABYLON;
  89819. (function (BABYLON) {
  89820. /**
  89821. * Class used to store bone information
  89822. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  89823. */
  89824. var Bone = /** @class */ (function (_super) {
  89825. __extends(Bone, _super);
  89826. /**
  89827. * Create a new bone
  89828. * @param name defines the bone name
  89829. * @param skeleton defines the parent skeleton
  89830. * @param parentBone defines the parent (can be null if the bone is the root)
  89831. * @param localMatrix defines the local matrix
  89832. * @param restPose defines the rest pose matrix
  89833. * @param baseMatrix defines the base matrix
  89834. * @param index defines index of the bone in the hiearchy
  89835. */
  89836. function Bone(
  89837. /**
  89838. * defines the bone name
  89839. */
  89840. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  89841. if (parentBone === void 0) { parentBone = null; }
  89842. if (localMatrix === void 0) { localMatrix = null; }
  89843. if (restPose === void 0) { restPose = null; }
  89844. if (baseMatrix === void 0) { baseMatrix = null; }
  89845. if (index === void 0) { index = null; }
  89846. var _this = _super.call(this, name, skeleton.getScene()) || this;
  89847. _this.name = name;
  89848. /**
  89849. * Gets the list of child bones
  89850. */
  89851. _this.children = new Array();
  89852. /** Gets the animations associated with this bone */
  89853. _this.animations = new Array();
  89854. /**
  89855. * @hidden Internal only
  89856. * Set this value to map this bone to a different index in the transform matrices
  89857. * Set this value to -1 to exclude the bone from the transform matrices
  89858. */
  89859. _this._index = null;
  89860. _this._absoluteTransform = new BABYLON.Matrix();
  89861. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  89862. _this._scalingDeterminant = 1;
  89863. _this._worldTransform = new BABYLON.Matrix();
  89864. _this._needToDecompose = true;
  89865. _this._needToCompose = false;
  89866. _this._skeleton = skeleton;
  89867. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  89868. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  89869. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  89870. _this._index = index;
  89871. skeleton.bones.push(_this);
  89872. _this.setParent(parentBone, false);
  89873. if (baseMatrix || localMatrix) {
  89874. _this._updateDifferenceMatrix();
  89875. }
  89876. return _this;
  89877. }
  89878. Object.defineProperty(Bone.prototype, "_matrix", {
  89879. /** @hidden */
  89880. get: function () {
  89881. this._compose();
  89882. return this._localMatrix;
  89883. },
  89884. /** @hidden */
  89885. set: function (value) {
  89886. this._localMatrix.copyFrom(value);
  89887. this._needToDecompose = true;
  89888. },
  89889. enumerable: true,
  89890. configurable: true
  89891. });
  89892. // Members
  89893. /**
  89894. * Gets the parent skeleton
  89895. * @returns a skeleton
  89896. */
  89897. Bone.prototype.getSkeleton = function () {
  89898. return this._skeleton;
  89899. };
  89900. /**
  89901. * Gets parent bone
  89902. * @returns a bone or null if the bone is the root of the bone hierarchy
  89903. */
  89904. Bone.prototype.getParent = function () {
  89905. return this._parent;
  89906. };
  89907. /**
  89908. * Sets the parent bone
  89909. * @param parent defines the parent (can be null if the bone is the root)
  89910. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  89911. */
  89912. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  89913. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  89914. if (this._parent === parent) {
  89915. return;
  89916. }
  89917. if (this._parent) {
  89918. var index = this._parent.children.indexOf(this);
  89919. if (index !== -1) {
  89920. this._parent.children.splice(index, 1);
  89921. }
  89922. }
  89923. this._parent = parent;
  89924. if (this._parent) {
  89925. this._parent.children.push(this);
  89926. }
  89927. if (updateDifferenceMatrix) {
  89928. this._updateDifferenceMatrix();
  89929. }
  89930. this.markAsDirty();
  89931. };
  89932. /**
  89933. * Gets the local matrix
  89934. * @returns a matrix
  89935. */
  89936. Bone.prototype.getLocalMatrix = function () {
  89937. this._compose();
  89938. return this._localMatrix;
  89939. };
  89940. /**
  89941. * Gets the base matrix (initial matrix which remains unchanged)
  89942. * @returns a matrix
  89943. */
  89944. Bone.prototype.getBaseMatrix = function () {
  89945. return this._baseMatrix;
  89946. };
  89947. /**
  89948. * Gets the rest pose matrix
  89949. * @returns a matrix
  89950. */
  89951. Bone.prototype.getRestPose = function () {
  89952. return this._restPose;
  89953. };
  89954. /**
  89955. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  89956. */
  89957. Bone.prototype.getWorldMatrix = function () {
  89958. return this._worldTransform;
  89959. };
  89960. /**
  89961. * Sets the local matrix to rest pose matrix
  89962. */
  89963. Bone.prototype.returnToRest = function () {
  89964. this.updateMatrix(this._restPose.clone());
  89965. };
  89966. /**
  89967. * Gets the inverse of the absolute transform matrix.
  89968. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  89969. * @returns a matrix
  89970. */
  89971. Bone.prototype.getInvertedAbsoluteTransform = function () {
  89972. return this._invertedAbsoluteTransform;
  89973. };
  89974. /**
  89975. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  89976. * @returns a matrix
  89977. */
  89978. Bone.prototype.getAbsoluteTransform = function () {
  89979. return this._absoluteTransform;
  89980. };
  89981. Object.defineProperty(Bone.prototype, "position", {
  89982. // Properties (matches AbstractMesh properties)
  89983. /** Gets or sets current position (in local space) */
  89984. get: function () {
  89985. this._decompose();
  89986. return this._localPosition;
  89987. },
  89988. set: function (newPosition) {
  89989. this._decompose();
  89990. this._localPosition.copyFrom(newPosition);
  89991. this._markAsDirtyAndCompose();
  89992. },
  89993. enumerable: true,
  89994. configurable: true
  89995. });
  89996. Object.defineProperty(Bone.prototype, "rotation", {
  89997. /** Gets or sets current rotation (in local space) */
  89998. get: function () {
  89999. return this.getRotation();
  90000. },
  90001. set: function (newRotation) {
  90002. this.setRotation(newRotation);
  90003. },
  90004. enumerable: true,
  90005. configurable: true
  90006. });
  90007. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  90008. /** Gets or sets current rotation quaternion (in local space) */
  90009. get: function () {
  90010. this._decompose();
  90011. return this._localRotation;
  90012. },
  90013. set: function (newRotation) {
  90014. this.setRotationQuaternion(newRotation);
  90015. },
  90016. enumerable: true,
  90017. configurable: true
  90018. });
  90019. Object.defineProperty(Bone.prototype, "scaling", {
  90020. /** Gets or sets current scaling (in local space) */
  90021. get: function () {
  90022. return this.getScale();
  90023. },
  90024. set: function (newScaling) {
  90025. this.setScale(newScaling);
  90026. },
  90027. enumerable: true,
  90028. configurable: true
  90029. });
  90030. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  90031. /**
  90032. * Gets the animation properties override
  90033. */
  90034. get: function () {
  90035. return this._skeleton.animationPropertiesOverride;
  90036. },
  90037. enumerable: true,
  90038. configurable: true
  90039. });
  90040. // Methods
  90041. Bone.prototype._decompose = function () {
  90042. if (!this._needToDecompose) {
  90043. return;
  90044. }
  90045. this._needToDecompose = false;
  90046. if (!this._localScaling) {
  90047. this._localScaling = BABYLON.Vector3.Zero();
  90048. this._localRotation = BABYLON.Quaternion.Zero();
  90049. this._localPosition = BABYLON.Vector3.Zero();
  90050. }
  90051. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  90052. };
  90053. Bone.prototype._compose = function () {
  90054. if (!this._needToCompose) {
  90055. return;
  90056. }
  90057. this._needToCompose = false;
  90058. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  90059. };
  90060. /**
  90061. * Update the base and local matrices
  90062. * @param matrix defines the new base or local matrix
  90063. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  90064. * @param updateLocalMatrix defines if the local matrix should be updated
  90065. */
  90066. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  90067. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  90068. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  90069. this._baseMatrix.copyFrom(matrix);
  90070. if (updateDifferenceMatrix) {
  90071. this._updateDifferenceMatrix();
  90072. }
  90073. if (updateLocalMatrix) {
  90074. this._localMatrix.copyFrom(matrix);
  90075. this._markAsDirtyAndDecompose();
  90076. }
  90077. else {
  90078. this.markAsDirty();
  90079. }
  90080. };
  90081. /** @hidden */
  90082. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  90083. if (updateChildren === void 0) { updateChildren = true; }
  90084. if (!rootMatrix) {
  90085. rootMatrix = this._baseMatrix;
  90086. }
  90087. if (this._parent) {
  90088. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90089. }
  90090. else {
  90091. this._absoluteTransform.copyFrom(rootMatrix);
  90092. }
  90093. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  90094. if (updateChildren) {
  90095. for (var index = 0; index < this.children.length; index++) {
  90096. this.children[index]._updateDifferenceMatrix();
  90097. }
  90098. }
  90099. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  90100. };
  90101. /**
  90102. * Flag the bone as dirty (Forcing it to update everything)
  90103. */
  90104. Bone.prototype.markAsDirty = function () {
  90105. this._currentRenderId++;
  90106. this._childRenderId++;
  90107. this._skeleton._markAsDirty();
  90108. };
  90109. Bone.prototype._markAsDirtyAndCompose = function () {
  90110. this.markAsDirty();
  90111. this._needToCompose = true;
  90112. };
  90113. Bone.prototype._markAsDirtyAndDecompose = function () {
  90114. this.markAsDirty();
  90115. this._needToDecompose = true;
  90116. };
  90117. /**
  90118. * Copy an animation range from another bone
  90119. * @param source defines the source bone
  90120. * @param rangeName defines the range name to copy
  90121. * @param frameOffset defines the frame offset
  90122. * @param rescaleAsRequired defines if rescaling must be applied if required
  90123. * @param skelDimensionsRatio defines the scaling ratio
  90124. * @returns true if operation was successful
  90125. */
  90126. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  90127. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  90128. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  90129. // all animation may be coming from a library skeleton, so may need to create animation
  90130. if (this.animations.length === 0) {
  90131. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  90132. this.animations[0].setKeys([]);
  90133. }
  90134. // get animation info / verify there is such a range from the source bone
  90135. var sourceRange = source.animations[0].getRange(rangeName);
  90136. if (!sourceRange) {
  90137. return false;
  90138. }
  90139. var from = sourceRange.from;
  90140. var to = sourceRange.to;
  90141. var sourceKeys = source.animations[0].getKeys();
  90142. // rescaling prep
  90143. var sourceBoneLength = source.length;
  90144. var sourceParent = source.getParent();
  90145. var parent = this.getParent();
  90146. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  90147. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  90148. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  90149. var destKeys = this.animations[0].getKeys();
  90150. // loop vars declaration
  90151. var orig;
  90152. var origTranslation;
  90153. var mat;
  90154. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  90155. orig = sourceKeys[key];
  90156. if (orig.frame >= from && orig.frame <= to) {
  90157. if (rescaleAsRequired) {
  90158. mat = orig.value.clone();
  90159. // scale based on parent ratio, when bone has parent
  90160. if (parentScalingReqd) {
  90161. origTranslation = mat.getTranslation();
  90162. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  90163. // scale based on skeleton dimension ratio when root bone, and value is passed
  90164. }
  90165. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  90166. origTranslation = mat.getTranslation();
  90167. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  90168. // use original when root bone, and no data for skelDimensionsRatio
  90169. }
  90170. else {
  90171. mat = orig.value;
  90172. }
  90173. }
  90174. else {
  90175. mat = orig.value;
  90176. }
  90177. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  90178. }
  90179. }
  90180. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  90181. return true;
  90182. };
  90183. /**
  90184. * Translate the bone in local or world space
  90185. * @param vec The amount to translate the bone
  90186. * @param space The space that the translation is in
  90187. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90188. */
  90189. Bone.prototype.translate = function (vec, space, mesh) {
  90190. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90191. var lm = this.getLocalMatrix();
  90192. if (space == BABYLON.Space.LOCAL) {
  90193. lm.m[12] += vec.x;
  90194. lm.m[13] += vec.y;
  90195. lm.m[14] += vec.z;
  90196. }
  90197. else {
  90198. var wm = null;
  90199. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90200. if (mesh) {
  90201. wm = mesh.getWorldMatrix();
  90202. }
  90203. this._skeleton.computeAbsoluteTransforms();
  90204. var tmat = Bone._tmpMats[0];
  90205. var tvec = Bone._tmpVecs[0];
  90206. if (this._parent) {
  90207. if (mesh && wm) {
  90208. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90209. tmat.multiplyToRef(wm, tmat);
  90210. }
  90211. else {
  90212. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90213. }
  90214. }
  90215. tmat.m[12] = 0;
  90216. tmat.m[13] = 0;
  90217. tmat.m[14] = 0;
  90218. tmat.invert();
  90219. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  90220. lm.m[12] += tvec.x;
  90221. lm.m[13] += tvec.y;
  90222. lm.m[14] += tvec.z;
  90223. }
  90224. this._markAsDirtyAndDecompose();
  90225. };
  90226. /**
  90227. * Set the postion of the bone in local or world space
  90228. * @param position The position to set the bone
  90229. * @param space The space that the position is in
  90230. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90231. */
  90232. Bone.prototype.setPosition = function (position, space, mesh) {
  90233. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90234. var lm = this.getLocalMatrix();
  90235. if (space == BABYLON.Space.LOCAL) {
  90236. lm.m[12] = position.x;
  90237. lm.m[13] = position.y;
  90238. lm.m[14] = position.z;
  90239. }
  90240. else {
  90241. var wm = null;
  90242. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90243. if (mesh) {
  90244. wm = mesh.getWorldMatrix();
  90245. }
  90246. this._skeleton.computeAbsoluteTransforms();
  90247. var tmat = Bone._tmpMats[0];
  90248. var vec = Bone._tmpVecs[0];
  90249. if (this._parent) {
  90250. if (mesh && wm) {
  90251. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90252. tmat.multiplyToRef(wm, tmat);
  90253. }
  90254. else {
  90255. tmat.copyFrom(this._parent.getAbsoluteTransform());
  90256. }
  90257. }
  90258. tmat.invert();
  90259. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  90260. lm.m[12] = vec.x;
  90261. lm.m[13] = vec.y;
  90262. lm.m[14] = vec.z;
  90263. }
  90264. this._markAsDirtyAndDecompose();
  90265. };
  90266. /**
  90267. * Set the absolute position of the bone (world space)
  90268. * @param position The position to set the bone
  90269. * @param mesh The mesh that this bone is attached to
  90270. */
  90271. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  90272. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  90273. };
  90274. /**
  90275. * Scale the bone on the x, y and z axes (in local space)
  90276. * @param x The amount to scale the bone on the x axis
  90277. * @param y The amount to scale the bone on the y axis
  90278. * @param z The amount to scale the bone on the z axis
  90279. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  90280. */
  90281. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  90282. if (scaleChildren === void 0) { scaleChildren = false; }
  90283. var locMat = this.getLocalMatrix();
  90284. // Apply new scaling on top of current local matrix
  90285. var scaleMat = Bone._tmpMats[0];
  90286. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  90287. scaleMat.multiplyToRef(locMat, locMat);
  90288. // Invert scaling matrix and apply the inverse to all children
  90289. scaleMat.invert();
  90290. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  90291. var child = _a[_i];
  90292. var cm = child.getLocalMatrix();
  90293. cm.multiplyToRef(scaleMat, cm);
  90294. cm.m[12] *= x;
  90295. cm.m[13] *= y;
  90296. cm.m[14] *= z;
  90297. child._markAsDirtyAndDecompose();
  90298. }
  90299. this._markAsDirtyAndDecompose();
  90300. if (scaleChildren) {
  90301. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  90302. var child = _c[_b];
  90303. child.scale(x, y, z, scaleChildren);
  90304. }
  90305. }
  90306. };
  90307. /**
  90308. * Set the bone scaling in local space
  90309. * @param scale defines the scaling vector
  90310. */
  90311. Bone.prototype.setScale = function (scale) {
  90312. this._decompose();
  90313. this._localScaling.copyFrom(scale);
  90314. this._markAsDirtyAndCompose();
  90315. };
  90316. /**
  90317. * Gets the current scaling in local space
  90318. * @returns the current scaling vector
  90319. */
  90320. Bone.prototype.getScale = function () {
  90321. this._decompose();
  90322. return this._localScaling;
  90323. };
  90324. /**
  90325. * Gets the current scaling in local space and stores it in a target vector
  90326. * @param result defines the target vector
  90327. */
  90328. Bone.prototype.getScaleToRef = function (result) {
  90329. this._decompose();
  90330. result.copyFrom(this._localScaling);
  90331. };
  90332. /**
  90333. * Set the yaw, pitch, and roll of the bone in local or world space
  90334. * @param yaw The rotation of the bone on the y axis
  90335. * @param pitch The rotation of the bone on the x axis
  90336. * @param roll The rotation of the bone on the z axis
  90337. * @param space The space that the axes of rotation are in
  90338. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90339. */
  90340. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  90341. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90342. if (space === BABYLON.Space.LOCAL) {
  90343. var quat = Bone._tmpQuat;
  90344. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  90345. this.setRotationQuaternion(quat, space, mesh);
  90346. return;
  90347. }
  90348. var rotMatInv = Bone._tmpMats[0];
  90349. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90350. return;
  90351. }
  90352. var rotMat = Bone._tmpMats[1];
  90353. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  90354. rotMatInv.multiplyToRef(rotMat, rotMat);
  90355. this._rotateWithMatrix(rotMat, space, mesh);
  90356. };
  90357. /**
  90358. * Add a rotation to the bone on an axis in local or world space
  90359. * @param axis The axis to rotate the bone on
  90360. * @param amount The amount to rotate the bone
  90361. * @param space The space that the axis is in
  90362. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90363. */
  90364. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  90365. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90366. var rmat = Bone._tmpMats[0];
  90367. rmat.m[12] = 0;
  90368. rmat.m[13] = 0;
  90369. rmat.m[14] = 0;
  90370. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  90371. this._rotateWithMatrix(rmat, space, mesh);
  90372. };
  90373. /**
  90374. * Set the rotation of the bone to a particular axis angle in local or world space
  90375. * @param axis The axis to rotate the bone on
  90376. * @param angle The angle that the bone should be rotated to
  90377. * @param space The space that the axis is in
  90378. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90379. */
  90380. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  90381. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90382. if (space === BABYLON.Space.LOCAL) {
  90383. var quat = Bone._tmpQuat;
  90384. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  90385. this.setRotationQuaternion(quat, space, mesh);
  90386. return;
  90387. }
  90388. var rotMatInv = Bone._tmpMats[0];
  90389. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90390. return;
  90391. }
  90392. var rotMat = Bone._tmpMats[1];
  90393. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  90394. rotMatInv.multiplyToRef(rotMat, rotMat);
  90395. this._rotateWithMatrix(rotMat, space, mesh);
  90396. };
  90397. /**
  90398. * Set the euler rotation of the bone in local of world space
  90399. * @param rotation The euler rotation that the bone should be set to
  90400. * @param space The space that the rotation is in
  90401. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90402. */
  90403. Bone.prototype.setRotation = function (rotation, space, mesh) {
  90404. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90405. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  90406. };
  90407. /**
  90408. * Set the quaternion rotation of the bone in local of world space
  90409. * @param quat The quaternion rotation that the bone should be set to
  90410. * @param space The space that the rotation is in
  90411. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90412. */
  90413. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  90414. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90415. if (space === BABYLON.Space.LOCAL) {
  90416. this._decompose();
  90417. this._localRotation.copyFrom(quat);
  90418. this._markAsDirtyAndCompose();
  90419. return;
  90420. }
  90421. var rotMatInv = Bone._tmpMats[0];
  90422. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90423. return;
  90424. }
  90425. var rotMat = Bone._tmpMats[1];
  90426. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  90427. rotMatInv.multiplyToRef(rotMat, rotMat);
  90428. this._rotateWithMatrix(rotMat, space, mesh);
  90429. };
  90430. /**
  90431. * Set the rotation matrix of the bone in local of world space
  90432. * @param rotMat The rotation matrix that the bone should be set to
  90433. * @param space The space that the rotation is in
  90434. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90435. */
  90436. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  90437. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90438. if (space === BABYLON.Space.LOCAL) {
  90439. var quat = Bone._tmpQuat;
  90440. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  90441. this.setRotationQuaternion(quat, space, mesh);
  90442. return;
  90443. }
  90444. var rotMatInv = Bone._tmpMats[0];
  90445. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  90446. return;
  90447. }
  90448. var rotMat2 = Bone._tmpMats[1];
  90449. rotMat2.copyFrom(rotMat);
  90450. rotMatInv.multiplyToRef(rotMat, rotMat2);
  90451. this._rotateWithMatrix(rotMat2, space, mesh);
  90452. };
  90453. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  90454. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90455. var lmat = this.getLocalMatrix();
  90456. var lx = lmat.m[12];
  90457. var ly = lmat.m[13];
  90458. var lz = lmat.m[14];
  90459. var parent = this.getParent();
  90460. var parentScale = Bone._tmpMats[3];
  90461. var parentScaleInv = Bone._tmpMats[4];
  90462. if (parent && space == BABYLON.Space.WORLD) {
  90463. if (mesh) {
  90464. parentScale.copyFrom(mesh.getWorldMatrix());
  90465. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  90466. }
  90467. else {
  90468. parentScale.copyFrom(parent.getAbsoluteTransform());
  90469. }
  90470. parentScaleInv.copyFrom(parentScale);
  90471. parentScaleInv.invert();
  90472. lmat.multiplyToRef(parentScale, lmat);
  90473. lmat.multiplyToRef(rmat, lmat);
  90474. lmat.multiplyToRef(parentScaleInv, lmat);
  90475. }
  90476. else {
  90477. if (space == BABYLON.Space.WORLD && mesh) {
  90478. parentScale.copyFrom(mesh.getWorldMatrix());
  90479. parentScaleInv.copyFrom(parentScale);
  90480. parentScaleInv.invert();
  90481. lmat.multiplyToRef(parentScale, lmat);
  90482. lmat.multiplyToRef(rmat, lmat);
  90483. lmat.multiplyToRef(parentScaleInv, lmat);
  90484. }
  90485. else {
  90486. lmat.multiplyToRef(rmat, lmat);
  90487. }
  90488. }
  90489. lmat.m[12] = lx;
  90490. lmat.m[13] = ly;
  90491. lmat.m[14] = lz;
  90492. this.computeAbsoluteTransforms();
  90493. this._markAsDirtyAndDecompose();
  90494. };
  90495. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  90496. var scaleMatrix = Bone._tmpMats[2];
  90497. rotMatInv.copyFrom(this.getAbsoluteTransform());
  90498. if (mesh) {
  90499. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  90500. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  90501. }
  90502. rotMatInv.invert();
  90503. if (isNaN(rotMatInv.m[0])) {
  90504. // Matrix failed to invert.
  90505. // This can happen if scale is zero for example.
  90506. return false;
  90507. }
  90508. scaleMatrix.m[0] *= this._scalingDeterminant;
  90509. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  90510. return true;
  90511. };
  90512. /**
  90513. * Get the position of the bone in local or world space
  90514. * @param space The space that the returned position is in
  90515. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90516. * @returns The position of the bone
  90517. */
  90518. Bone.prototype.getPosition = function (space, mesh) {
  90519. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90520. if (mesh === void 0) { mesh = null; }
  90521. var pos = BABYLON.Vector3.Zero();
  90522. this.getPositionToRef(space, mesh, pos);
  90523. return pos;
  90524. };
  90525. /**
  90526. * Copy the position of the bone to a vector3 in local or world space
  90527. * @param space The space that the returned position is in
  90528. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90529. * @param result The vector3 to copy the position to
  90530. */
  90531. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  90532. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90533. if (space == BABYLON.Space.LOCAL) {
  90534. var lm = this.getLocalMatrix();
  90535. result.x = lm.m[12];
  90536. result.y = lm.m[13];
  90537. result.z = lm.m[14];
  90538. }
  90539. else {
  90540. var wm = null;
  90541. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90542. if (mesh) {
  90543. wm = mesh.getWorldMatrix();
  90544. }
  90545. this._skeleton.computeAbsoluteTransforms();
  90546. var tmat = Bone._tmpMats[0];
  90547. if (mesh && wm) {
  90548. tmat.copyFrom(this.getAbsoluteTransform());
  90549. tmat.multiplyToRef(wm, tmat);
  90550. }
  90551. else {
  90552. tmat = this.getAbsoluteTransform();
  90553. }
  90554. result.x = tmat.m[12];
  90555. result.y = tmat.m[13];
  90556. result.z = tmat.m[14];
  90557. }
  90558. };
  90559. /**
  90560. * Get the absolute position of the bone (world space)
  90561. * @param mesh The mesh that this bone is attached to
  90562. * @returns The absolute position of the bone
  90563. */
  90564. Bone.prototype.getAbsolutePosition = function (mesh) {
  90565. if (mesh === void 0) { mesh = null; }
  90566. var pos = BABYLON.Vector3.Zero();
  90567. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  90568. return pos;
  90569. };
  90570. /**
  90571. * Copy the absolute position of the bone (world space) to the result param
  90572. * @param mesh The mesh that this bone is attached to
  90573. * @param result The vector3 to copy the absolute position to
  90574. */
  90575. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  90576. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  90577. };
  90578. /**
  90579. * Compute the absolute transforms of this bone and its children
  90580. */
  90581. Bone.prototype.computeAbsoluteTransforms = function () {
  90582. this._compose();
  90583. if (this._parent) {
  90584. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  90585. }
  90586. else {
  90587. this._absoluteTransform.copyFrom(this._localMatrix);
  90588. var poseMatrix = this._skeleton.getPoseMatrix();
  90589. if (poseMatrix) {
  90590. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  90591. }
  90592. }
  90593. var children = this.children;
  90594. var len = children.length;
  90595. for (var i = 0; i < len; i++) {
  90596. children[i].computeAbsoluteTransforms();
  90597. }
  90598. };
  90599. /**
  90600. * Get the world direction from an axis that is in the local space of the bone
  90601. * @param localAxis The local direction that is used to compute the world direction
  90602. * @param mesh The mesh that this bone is attached to
  90603. * @returns The world direction
  90604. */
  90605. Bone.prototype.getDirection = function (localAxis, mesh) {
  90606. if (mesh === void 0) { mesh = null; }
  90607. var result = BABYLON.Vector3.Zero();
  90608. this.getDirectionToRef(localAxis, mesh, result);
  90609. return result;
  90610. };
  90611. /**
  90612. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  90613. * @param localAxis The local direction that is used to compute the world direction
  90614. * @param mesh The mesh that this bone is attached to
  90615. * @param result The vector3 that the world direction will be copied to
  90616. */
  90617. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  90618. if (mesh === void 0) { mesh = null; }
  90619. var wm = null;
  90620. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90621. if (mesh) {
  90622. wm = mesh.getWorldMatrix();
  90623. }
  90624. this._skeleton.computeAbsoluteTransforms();
  90625. var mat = Bone._tmpMats[0];
  90626. mat.copyFrom(this.getAbsoluteTransform());
  90627. if (mesh && wm) {
  90628. mat.multiplyToRef(wm, mat);
  90629. }
  90630. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  90631. result.normalize();
  90632. };
  90633. /**
  90634. * Get the euler rotation of the bone in local or world space
  90635. * @param space The space that the rotation should be in
  90636. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90637. * @returns The euler rotation
  90638. */
  90639. Bone.prototype.getRotation = function (space, mesh) {
  90640. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90641. if (mesh === void 0) { mesh = null; }
  90642. var result = BABYLON.Vector3.Zero();
  90643. this.getRotationToRef(space, mesh, result);
  90644. return result;
  90645. };
  90646. /**
  90647. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  90648. * @param space The space that the rotation should be in
  90649. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90650. * @param result The vector3 that the rotation should be copied to
  90651. */
  90652. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  90653. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90654. if (mesh === void 0) { mesh = null; }
  90655. var quat = Bone._tmpQuat;
  90656. this.getRotationQuaternionToRef(space, mesh, quat);
  90657. quat.toEulerAnglesToRef(result);
  90658. };
  90659. /**
  90660. * Get the quaternion rotation of the bone in either local or world space
  90661. * @param space The space that the rotation should be in
  90662. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90663. * @returns The quaternion rotation
  90664. */
  90665. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  90666. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90667. if (mesh === void 0) { mesh = null; }
  90668. var result = BABYLON.Quaternion.Identity();
  90669. this.getRotationQuaternionToRef(space, mesh, result);
  90670. return result;
  90671. };
  90672. /**
  90673. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  90674. * @param space The space that the rotation should be in
  90675. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90676. * @param result The quaternion that the rotation should be copied to
  90677. */
  90678. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  90679. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90680. if (mesh === void 0) { mesh = null; }
  90681. if (space == BABYLON.Space.LOCAL) {
  90682. this._decompose();
  90683. result.copyFrom(this._localRotation);
  90684. }
  90685. else {
  90686. var mat = Bone._tmpMats[0];
  90687. var amat = this.getAbsoluteTransform();
  90688. if (mesh) {
  90689. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90690. }
  90691. else {
  90692. mat.copyFrom(amat);
  90693. }
  90694. mat.m[0] *= this._scalingDeterminant;
  90695. mat.m[1] *= this._scalingDeterminant;
  90696. mat.m[2] *= this._scalingDeterminant;
  90697. mat.decompose(undefined, result, undefined);
  90698. }
  90699. };
  90700. /**
  90701. * Get the rotation matrix of the bone in local or world space
  90702. * @param space The space that the rotation should be in
  90703. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90704. * @returns The rotation matrix
  90705. */
  90706. Bone.prototype.getRotationMatrix = function (space, mesh) {
  90707. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90708. var result = BABYLON.Matrix.Identity();
  90709. this.getRotationMatrixToRef(space, mesh, result);
  90710. return result;
  90711. };
  90712. /**
  90713. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  90714. * @param space The space that the rotation should be in
  90715. * @param mesh The mesh that this bone is attached to. This is only used in world space
  90716. * @param result The quaternion that the rotation should be copied to
  90717. */
  90718. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  90719. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  90720. if (space == BABYLON.Space.LOCAL) {
  90721. this.getLocalMatrix().getRotationMatrixToRef(result);
  90722. }
  90723. else {
  90724. var mat = Bone._tmpMats[0];
  90725. var amat = this.getAbsoluteTransform();
  90726. if (mesh) {
  90727. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  90728. }
  90729. else {
  90730. mat.copyFrom(amat);
  90731. }
  90732. mat.m[0] *= this._scalingDeterminant;
  90733. mat.m[1] *= this._scalingDeterminant;
  90734. mat.m[2] *= this._scalingDeterminant;
  90735. mat.getRotationMatrixToRef(result);
  90736. }
  90737. };
  90738. /**
  90739. * Get the world position of a point that is in the local space of the bone
  90740. * @param position The local position
  90741. * @param mesh The mesh that this bone is attached to
  90742. * @returns The world position
  90743. */
  90744. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  90745. if (mesh === void 0) { mesh = null; }
  90746. var result = BABYLON.Vector3.Zero();
  90747. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  90748. return result;
  90749. };
  90750. /**
  90751. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  90752. * @param position The local position
  90753. * @param mesh The mesh that this bone is attached to
  90754. * @param result The vector3 that the world position should be copied to
  90755. */
  90756. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  90757. if (mesh === void 0) { mesh = null; }
  90758. var wm = null;
  90759. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90760. if (mesh) {
  90761. wm = mesh.getWorldMatrix();
  90762. }
  90763. this._skeleton.computeAbsoluteTransforms();
  90764. var tmat = Bone._tmpMats[0];
  90765. if (mesh && wm) {
  90766. tmat.copyFrom(this.getAbsoluteTransform());
  90767. tmat.multiplyToRef(wm, tmat);
  90768. }
  90769. else {
  90770. tmat = this.getAbsoluteTransform();
  90771. }
  90772. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  90773. };
  90774. /**
  90775. * Get the local position of a point that is in world space
  90776. * @param position The world position
  90777. * @param mesh The mesh that this bone is attached to
  90778. * @returns The local position
  90779. */
  90780. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  90781. if (mesh === void 0) { mesh = null; }
  90782. var result = BABYLON.Vector3.Zero();
  90783. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  90784. return result;
  90785. };
  90786. /**
  90787. * Get the local position of a point that is in world space and copy it to the result param
  90788. * @param position The world position
  90789. * @param mesh The mesh that this bone is attached to
  90790. * @param result The vector3 that the local position should be copied to
  90791. */
  90792. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  90793. if (mesh === void 0) { mesh = null; }
  90794. var wm = null;
  90795. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  90796. if (mesh) {
  90797. wm = mesh.getWorldMatrix();
  90798. }
  90799. this._skeleton.computeAbsoluteTransforms();
  90800. var tmat = Bone._tmpMats[0];
  90801. tmat.copyFrom(this.getAbsoluteTransform());
  90802. if (mesh && wm) {
  90803. tmat.multiplyToRef(wm, tmat);
  90804. }
  90805. tmat.invert();
  90806. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  90807. };
  90808. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  90809. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  90810. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  90811. return Bone;
  90812. }(BABYLON.Node));
  90813. BABYLON.Bone = Bone;
  90814. })(BABYLON || (BABYLON = {}));
  90815. //# sourceMappingURL=babylon.bone.js.map
  90816. var BABYLON;
  90817. (function (BABYLON) {
  90818. /**
  90819. * Class used to apply inverse kinematics to bones
  90820. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  90821. */
  90822. var BoneIKController = /** @class */ (function () {
  90823. /**
  90824. * Creates a new BoneIKController
  90825. * @param mesh defines the mesh to control
  90826. * @param bone defines the bone to control
  90827. * @param options defines options to set up the controller
  90828. */
  90829. function BoneIKController(mesh, bone, options) {
  90830. /**
  90831. * Gets or sets the target position
  90832. */
  90833. this.targetPosition = BABYLON.Vector3.Zero();
  90834. /**
  90835. * Gets or sets the pole target position
  90836. */
  90837. this.poleTargetPosition = BABYLON.Vector3.Zero();
  90838. /**
  90839. * Gets or sets the pole target local offset
  90840. */
  90841. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  90842. /**
  90843. * Gets or sets the pole angle
  90844. */
  90845. this.poleAngle = 0;
  90846. /**
  90847. * 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)
  90848. */
  90849. this.slerpAmount = 1;
  90850. this._bone1Quat = BABYLON.Quaternion.Identity();
  90851. this._bone1Mat = BABYLON.Matrix.Identity();
  90852. this._bone2Ang = Math.PI;
  90853. this._maxAngle = Math.PI;
  90854. this._rightHandedSystem = false;
  90855. this._bendAxis = BABYLON.Vector3.Right();
  90856. this._slerping = false;
  90857. this._adjustRoll = 0;
  90858. this._bone2 = bone;
  90859. this._bone1 = bone.getParent();
  90860. if (!this._bone1) {
  90861. return;
  90862. }
  90863. this.mesh = mesh;
  90864. var bonePos = bone.getPosition();
  90865. if (bone.getAbsoluteTransform().determinant() > 0) {
  90866. this._rightHandedSystem = true;
  90867. this._bendAxis.x = 0;
  90868. this._bendAxis.y = 0;
  90869. this._bendAxis.z = -1;
  90870. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  90871. this._adjustRoll = Math.PI * .5;
  90872. this._bendAxis.z = 1;
  90873. }
  90874. }
  90875. if (this._bone1.length) {
  90876. var boneScale1 = this._bone1.getScale();
  90877. var boneScale2 = this._bone2.getScale();
  90878. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  90879. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  90880. }
  90881. else if (this._bone1.children[0]) {
  90882. mesh.computeWorldMatrix(true);
  90883. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  90884. var pos2 = this._bone2.getAbsolutePosition(mesh);
  90885. var pos3 = this._bone1.getAbsolutePosition(mesh);
  90886. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  90887. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  90888. }
  90889. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  90890. this.maxAngle = Math.PI;
  90891. if (options) {
  90892. if (options.targetMesh) {
  90893. this.targetMesh = options.targetMesh;
  90894. this.targetMesh.computeWorldMatrix(true);
  90895. }
  90896. if (options.poleTargetMesh) {
  90897. this.poleTargetMesh = options.poleTargetMesh;
  90898. this.poleTargetMesh.computeWorldMatrix(true);
  90899. }
  90900. else if (options.poleTargetBone) {
  90901. this.poleTargetBone = options.poleTargetBone;
  90902. }
  90903. else if (this._bone1.getParent()) {
  90904. this.poleTargetBone = this._bone1.getParent();
  90905. }
  90906. if (options.poleTargetLocalOffset) {
  90907. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  90908. }
  90909. if (options.poleAngle) {
  90910. this.poleAngle = options.poleAngle;
  90911. }
  90912. if (options.bendAxis) {
  90913. this._bendAxis.copyFrom(options.bendAxis);
  90914. }
  90915. if (options.maxAngle) {
  90916. this.maxAngle = options.maxAngle;
  90917. }
  90918. if (options.slerpAmount) {
  90919. this.slerpAmount = options.slerpAmount;
  90920. }
  90921. }
  90922. }
  90923. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  90924. /**
  90925. * Gets or sets maximum allowed angle
  90926. */
  90927. get: function () {
  90928. return this._maxAngle;
  90929. },
  90930. set: function (value) {
  90931. this._setMaxAngle(value);
  90932. },
  90933. enumerable: true,
  90934. configurable: true
  90935. });
  90936. BoneIKController.prototype._setMaxAngle = function (ang) {
  90937. if (ang < 0) {
  90938. ang = 0;
  90939. }
  90940. if (ang > Math.PI || ang == undefined) {
  90941. ang = Math.PI;
  90942. }
  90943. this._maxAngle = ang;
  90944. var a = this._bone1Length;
  90945. var b = this._bone2Length;
  90946. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  90947. };
  90948. /**
  90949. * Force the controller to update the bones
  90950. */
  90951. BoneIKController.prototype.update = function () {
  90952. var bone1 = this._bone1;
  90953. if (!bone1) {
  90954. return;
  90955. }
  90956. var target = this.targetPosition;
  90957. var poleTarget = this.poleTargetPosition;
  90958. var mat1 = BoneIKController._tmpMats[0];
  90959. var mat2 = BoneIKController._tmpMats[1];
  90960. if (this.targetMesh) {
  90961. target.copyFrom(this.targetMesh.getAbsolutePosition());
  90962. }
  90963. if (this.poleTargetBone) {
  90964. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  90965. }
  90966. else if (this.poleTargetMesh) {
  90967. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  90968. }
  90969. var bonePos = BoneIKController._tmpVecs[0];
  90970. var zaxis = BoneIKController._tmpVecs[1];
  90971. var xaxis = BoneIKController._tmpVecs[2];
  90972. var yaxis = BoneIKController._tmpVecs[3];
  90973. var upAxis = BoneIKController._tmpVecs[4];
  90974. var _tmpQuat = BoneIKController._tmpQuat;
  90975. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  90976. poleTarget.subtractToRef(bonePos, upAxis);
  90977. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  90978. upAxis.y = 1;
  90979. }
  90980. else {
  90981. upAxis.normalize();
  90982. }
  90983. target.subtractToRef(bonePos, yaxis);
  90984. yaxis.normalize();
  90985. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  90986. zaxis.normalize();
  90987. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  90988. xaxis.normalize();
  90989. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  90990. var a = this._bone1Length;
  90991. var b = this._bone2Length;
  90992. var c = BABYLON.Vector3.Distance(bonePos, target);
  90993. if (this._maxReach > 0) {
  90994. c = Math.min(this._maxReach, c);
  90995. }
  90996. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  90997. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  90998. if (acosa > 1) {
  90999. acosa = 1;
  91000. }
  91001. if (acosb > 1) {
  91002. acosb = 1;
  91003. }
  91004. if (acosa < -1) {
  91005. acosa = -1;
  91006. }
  91007. if (acosb < -1) {
  91008. acosb = -1;
  91009. }
  91010. var angA = Math.acos(acosa);
  91011. var angB = Math.acos(acosb);
  91012. var angC = -angA - angB;
  91013. if (this._rightHandedSystem) {
  91014. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  91015. mat2.multiplyToRef(mat1, mat1);
  91016. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  91017. mat2.multiplyToRef(mat1, mat1);
  91018. }
  91019. else {
  91020. var _tmpVec = BoneIKController._tmpVecs[5];
  91021. _tmpVec.copyFrom(this._bendAxis);
  91022. _tmpVec.x *= -1;
  91023. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  91024. mat2.multiplyToRef(mat1, mat1);
  91025. }
  91026. if (this.poleAngle) {
  91027. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  91028. mat1.multiplyToRef(mat2, mat1);
  91029. }
  91030. if (this._bone1) {
  91031. if (this.slerpAmount < 1) {
  91032. if (!this._slerping) {
  91033. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  91034. }
  91035. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  91036. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  91037. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  91038. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  91039. this._slerping = true;
  91040. }
  91041. else {
  91042. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  91043. this._bone1Mat.copyFrom(mat1);
  91044. this._slerping = false;
  91045. }
  91046. }
  91047. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  91048. this._bone2Ang = angC;
  91049. };
  91050. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  91051. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  91052. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91053. return BoneIKController;
  91054. }());
  91055. BABYLON.BoneIKController = BoneIKController;
  91056. })(BABYLON || (BABYLON = {}));
  91057. //# sourceMappingURL=babylon.boneIKController.js.map
  91058. var BABYLON;
  91059. (function (BABYLON) {
  91060. /**
  91061. * Class used to make a bone look toward a point in space
  91062. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  91063. */
  91064. var BoneLookController = /** @class */ (function () {
  91065. /**
  91066. * Create a BoneLookController
  91067. * @param mesh the mesh that the bone belongs to
  91068. * @param bone the bone that will be looking to the target
  91069. * @param target the target Vector3 to look at
  91070. * @param settings optional settings:
  91071. * * maxYaw: the maximum angle the bone will yaw to
  91072. * * minYaw: the minimum angle the bone will yaw to
  91073. * * maxPitch: the maximum angle the bone will pitch to
  91074. * * minPitch: the minimum angle the bone will yaw to
  91075. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  91076. * * upAxis: the up axis of the coordinate system
  91077. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  91078. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  91079. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  91080. * * adjustYaw: used to make an adjustment to the yaw of the bone
  91081. * * adjustPitch: used to make an adjustment to the pitch of the bone
  91082. * * adjustRoll: used to make an adjustment to the roll of the bone
  91083. **/
  91084. function BoneLookController(mesh, bone, target, options) {
  91085. /**
  91086. * The up axis of the coordinate system that is used when the bone is rotated
  91087. */
  91088. this.upAxis = BABYLON.Vector3.Up();
  91089. /**
  91090. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  91091. */
  91092. this.upAxisSpace = BABYLON.Space.LOCAL;
  91093. /**
  91094. * Used to make an adjustment to the yaw of the bone
  91095. */
  91096. this.adjustYaw = 0;
  91097. /**
  91098. * Used to make an adjustment to the pitch of the bone
  91099. */
  91100. this.adjustPitch = 0;
  91101. /**
  91102. * Used to make an adjustment to the roll of the bone
  91103. */
  91104. this.adjustRoll = 0;
  91105. /**
  91106. * 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)
  91107. */
  91108. this.slerpAmount = 1;
  91109. this._boneQuat = BABYLON.Quaternion.Identity();
  91110. this._slerping = false;
  91111. this._firstFrameSkipped = false;
  91112. this._fowardAxis = BABYLON.Vector3.Forward();
  91113. this.mesh = mesh;
  91114. this.bone = bone;
  91115. this.target = target;
  91116. if (options) {
  91117. if (options.adjustYaw) {
  91118. this.adjustYaw = options.adjustYaw;
  91119. }
  91120. if (options.adjustPitch) {
  91121. this.adjustPitch = options.adjustPitch;
  91122. }
  91123. if (options.adjustRoll) {
  91124. this.adjustRoll = options.adjustRoll;
  91125. }
  91126. if (options.maxYaw != null) {
  91127. this.maxYaw = options.maxYaw;
  91128. }
  91129. else {
  91130. this.maxYaw = Math.PI;
  91131. }
  91132. if (options.minYaw != null) {
  91133. this.minYaw = options.minYaw;
  91134. }
  91135. else {
  91136. this.minYaw = -Math.PI;
  91137. }
  91138. if (options.maxPitch != null) {
  91139. this.maxPitch = options.maxPitch;
  91140. }
  91141. else {
  91142. this.maxPitch = Math.PI;
  91143. }
  91144. if (options.minPitch != null) {
  91145. this.minPitch = options.minPitch;
  91146. }
  91147. else {
  91148. this.minPitch = -Math.PI;
  91149. }
  91150. if (options.slerpAmount != null) {
  91151. this.slerpAmount = options.slerpAmount;
  91152. }
  91153. if (options.upAxis != null) {
  91154. this.upAxis = options.upAxis;
  91155. }
  91156. if (options.upAxisSpace != null) {
  91157. this.upAxisSpace = options.upAxisSpace;
  91158. }
  91159. if (options.yawAxis != null || options.pitchAxis != null) {
  91160. var newYawAxis = BABYLON.Axis.Y;
  91161. var newPitchAxis = BABYLON.Axis.X;
  91162. if (options.yawAxis != null) {
  91163. newYawAxis = options.yawAxis.clone();
  91164. newYawAxis.normalize();
  91165. }
  91166. if (options.pitchAxis != null) {
  91167. newPitchAxis = options.pitchAxis.clone();
  91168. newPitchAxis.normalize();
  91169. }
  91170. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  91171. this._transformYawPitch = BABYLON.Matrix.Identity();
  91172. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  91173. this._transformYawPitchInv = this._transformYawPitch.clone();
  91174. this._transformYawPitch.invert();
  91175. }
  91176. }
  91177. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  91178. this.upAxisSpace = BABYLON.Space.LOCAL;
  91179. }
  91180. }
  91181. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  91182. /**
  91183. * Gets or sets the minimum yaw angle that the bone can look to
  91184. */
  91185. get: function () {
  91186. return this._minYaw;
  91187. },
  91188. set: function (value) {
  91189. this._minYaw = value;
  91190. this._minYawSin = Math.sin(value);
  91191. this._minYawCos = Math.cos(value);
  91192. if (this._maxYaw != null) {
  91193. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91194. this._yawRange = this._maxYaw - this._minYaw;
  91195. }
  91196. },
  91197. enumerable: true,
  91198. configurable: true
  91199. });
  91200. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  91201. /**
  91202. * Gets or sets the maximum yaw angle that the bone can look to
  91203. */
  91204. get: function () {
  91205. return this._maxYaw;
  91206. },
  91207. set: function (value) {
  91208. this._maxYaw = value;
  91209. this._maxYawSin = Math.sin(value);
  91210. this._maxYawCos = Math.cos(value);
  91211. if (this._minYaw != null) {
  91212. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  91213. this._yawRange = this._maxYaw - this._minYaw;
  91214. }
  91215. },
  91216. enumerable: true,
  91217. configurable: true
  91218. });
  91219. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  91220. /**
  91221. * Gets or sets the minimum pitch angle that the bone can look to
  91222. */
  91223. get: function () {
  91224. return this._minPitch;
  91225. },
  91226. set: function (value) {
  91227. this._minPitch = value;
  91228. this._minPitchTan = Math.tan(value);
  91229. },
  91230. enumerable: true,
  91231. configurable: true
  91232. });
  91233. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  91234. /**
  91235. * Gets or sets the maximum pitch angle that the bone can look to
  91236. */
  91237. get: function () {
  91238. return this._maxPitch;
  91239. },
  91240. set: function (value) {
  91241. this._maxPitch = value;
  91242. this._maxPitchTan = Math.tan(value);
  91243. },
  91244. enumerable: true,
  91245. configurable: true
  91246. });
  91247. /**
  91248. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  91249. */
  91250. BoneLookController.prototype.update = function () {
  91251. //skip the first frame when slerping so that the mesh rotation is correct
  91252. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  91253. this._firstFrameSkipped = true;
  91254. return;
  91255. }
  91256. var bone = this.bone;
  91257. var bonePos = BoneLookController._tmpVecs[0];
  91258. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  91259. var target = this.target;
  91260. var _tmpMat1 = BoneLookController._tmpMats[0];
  91261. var _tmpMat2 = BoneLookController._tmpMats[1];
  91262. var mesh = this.mesh;
  91263. var parentBone = bone.getParent();
  91264. var upAxis = BoneLookController._tmpVecs[1];
  91265. upAxis.copyFrom(this.upAxis);
  91266. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  91267. if (this._transformYawPitch) {
  91268. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  91269. }
  91270. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  91271. }
  91272. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  91273. mesh.getDirectionToRef(upAxis, upAxis);
  91274. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  91275. upAxis.normalize();
  91276. }
  91277. }
  91278. var checkYaw = false;
  91279. var checkPitch = false;
  91280. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  91281. checkYaw = true;
  91282. }
  91283. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  91284. checkPitch = true;
  91285. }
  91286. if (checkYaw || checkPitch) {
  91287. var spaceMat = BoneLookController._tmpMats[2];
  91288. var spaceMatInv = BoneLookController._tmpMats[3];
  91289. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  91290. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  91291. }
  91292. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  91293. spaceMat.copyFrom(mesh.getWorldMatrix());
  91294. }
  91295. else {
  91296. var forwardAxis = BoneLookController._tmpVecs[2];
  91297. forwardAxis.copyFrom(this._fowardAxis);
  91298. if (this._transformYawPitch) {
  91299. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  91300. }
  91301. if (parentBone) {
  91302. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  91303. }
  91304. else {
  91305. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  91306. }
  91307. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  91308. rightAxis.normalize();
  91309. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  91310. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  91311. }
  91312. spaceMat.invertToRef(spaceMatInv);
  91313. var xzlen = null;
  91314. if (checkPitch) {
  91315. var localTarget = BoneLookController._tmpVecs[3];
  91316. target.subtractToRef(bonePos, localTarget);
  91317. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91318. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91319. var pitch = Math.atan2(localTarget.y, xzlen);
  91320. var newPitch = pitch;
  91321. if (pitch > this._maxPitch) {
  91322. localTarget.y = this._maxPitchTan * xzlen;
  91323. newPitch = this._maxPitch;
  91324. }
  91325. else if (pitch < this._minPitch) {
  91326. localTarget.y = this._minPitchTan * xzlen;
  91327. newPitch = this._minPitch;
  91328. }
  91329. if (pitch != newPitch) {
  91330. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91331. localTarget.addInPlace(bonePos);
  91332. target = localTarget;
  91333. }
  91334. }
  91335. if (checkYaw) {
  91336. var localTarget = BoneLookController._tmpVecs[4];
  91337. target.subtractToRef(bonePos, localTarget);
  91338. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  91339. var yaw = Math.atan2(localTarget.x, localTarget.z);
  91340. var newYaw = yaw;
  91341. if (yaw > this._maxYaw || yaw < this._minYaw) {
  91342. if (xzlen == null) {
  91343. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91344. }
  91345. if (this._yawRange > Math.PI) {
  91346. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  91347. localTarget.z = this._maxYawCos * xzlen;
  91348. localTarget.x = this._maxYawSin * xzlen;
  91349. newYaw = this._maxYaw;
  91350. }
  91351. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  91352. localTarget.z = this._minYawCos * xzlen;
  91353. localTarget.x = this._minYawSin * xzlen;
  91354. newYaw = this._minYaw;
  91355. }
  91356. }
  91357. else {
  91358. if (yaw > this._maxYaw) {
  91359. localTarget.z = this._maxYawCos * xzlen;
  91360. localTarget.x = this._maxYawSin * xzlen;
  91361. newYaw = this._maxYaw;
  91362. }
  91363. else if (yaw < this._minYaw) {
  91364. localTarget.z = this._minYawCos * xzlen;
  91365. localTarget.x = this._minYawSin * xzlen;
  91366. newYaw = this._minYaw;
  91367. }
  91368. }
  91369. }
  91370. if (this._slerping && this._yawRange > Math.PI) {
  91371. //are we going to be crossing into the min/max region?
  91372. var boneFwd = BoneLookController._tmpVecs[8];
  91373. boneFwd.copyFrom(BABYLON.Axis.Z);
  91374. if (this._transformYawPitch) {
  91375. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  91376. }
  91377. var boneRotMat = BoneLookController._tmpMats[4];
  91378. this._boneQuat.toRotationMatrix(boneRotMat);
  91379. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  91380. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  91381. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  91382. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  91383. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  91384. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  91385. if (angBtwTar > angBtwMidYaw) {
  91386. if (xzlen == null) {
  91387. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  91388. }
  91389. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  91390. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  91391. if (angBtwMin < angBtwMax) {
  91392. newYaw = boneYaw + Math.PI * .75;
  91393. localTarget.z = Math.cos(newYaw) * xzlen;
  91394. localTarget.x = Math.sin(newYaw) * xzlen;
  91395. }
  91396. else {
  91397. newYaw = boneYaw - Math.PI * .75;
  91398. localTarget.z = Math.cos(newYaw) * xzlen;
  91399. localTarget.x = Math.sin(newYaw) * xzlen;
  91400. }
  91401. }
  91402. }
  91403. if (yaw != newYaw) {
  91404. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  91405. localTarget.addInPlace(bonePos);
  91406. target = localTarget;
  91407. }
  91408. }
  91409. }
  91410. var zaxis = BoneLookController._tmpVecs[5];
  91411. var xaxis = BoneLookController._tmpVecs[6];
  91412. var yaxis = BoneLookController._tmpVecs[7];
  91413. var _tmpQuat = BoneLookController._tmpQuat;
  91414. target.subtractToRef(bonePos, zaxis);
  91415. zaxis.normalize();
  91416. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  91417. xaxis.normalize();
  91418. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  91419. yaxis.normalize();
  91420. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  91421. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  91422. return;
  91423. }
  91424. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  91425. return;
  91426. }
  91427. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  91428. return;
  91429. }
  91430. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  91431. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  91432. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  91433. }
  91434. if (this.slerpAmount < 1) {
  91435. if (!this._slerping) {
  91436. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  91437. }
  91438. if (this._transformYawPitch) {
  91439. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91440. }
  91441. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  91442. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  91443. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  91444. this._slerping = true;
  91445. }
  91446. else {
  91447. if (this._transformYawPitch) {
  91448. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  91449. }
  91450. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  91451. this._slerping = false;
  91452. }
  91453. };
  91454. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  91455. var angDiff = ang2 - ang1;
  91456. angDiff %= Math.PI * 2;
  91457. if (angDiff > Math.PI) {
  91458. angDiff -= Math.PI * 2;
  91459. }
  91460. else if (angDiff < -Math.PI) {
  91461. angDiff += Math.PI * 2;
  91462. }
  91463. return angDiff;
  91464. };
  91465. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  91466. ang1 %= (2 * Math.PI);
  91467. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91468. ang2 %= (2 * Math.PI);
  91469. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91470. var ab = 0;
  91471. if (ang1 < ang2) {
  91472. ab = ang2 - ang1;
  91473. }
  91474. else {
  91475. ab = ang1 - ang2;
  91476. }
  91477. if (ab > Math.PI) {
  91478. ab = Math.PI * 2 - ab;
  91479. }
  91480. return ab;
  91481. };
  91482. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  91483. ang %= (2 * Math.PI);
  91484. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  91485. ang1 %= (2 * Math.PI);
  91486. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  91487. ang2 %= (2 * Math.PI);
  91488. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  91489. if (ang1 < ang2) {
  91490. if (ang > ang1 && ang < ang2) {
  91491. return true;
  91492. }
  91493. }
  91494. else {
  91495. if (ang > ang2 && ang < ang1) {
  91496. return true;
  91497. }
  91498. }
  91499. return false;
  91500. };
  91501. 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()];
  91502. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  91503. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  91504. return BoneLookController;
  91505. }());
  91506. BABYLON.BoneLookController = BoneLookController;
  91507. })(BABYLON || (BABYLON = {}));
  91508. //# sourceMappingURL=babylon.boneLookController.js.map
  91509. var BABYLON;
  91510. (function (BABYLON) {
  91511. /**
  91512. * Class used to handle skinning animations
  91513. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  91514. */
  91515. var Skeleton = /** @class */ (function () {
  91516. /**
  91517. * Creates a new skeleton
  91518. * @param name defines the skeleton name
  91519. * @param id defines the skeleton Id
  91520. * @param scene defines the hosting scene
  91521. */
  91522. function Skeleton(
  91523. /** defines the skeleton name */
  91524. name,
  91525. /** defines the skeleton Id */
  91526. id, scene) {
  91527. this.name = name;
  91528. this.id = id;
  91529. /**
  91530. * Gets the list of child bones
  91531. */
  91532. this.bones = new Array();
  91533. /**
  91534. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  91535. */
  91536. this.needInitialSkinMatrix = false;
  91537. this._isDirty = true;
  91538. this._meshesWithPoseMatrix = new Array();
  91539. this._identity = BABYLON.Matrix.Identity();
  91540. this._ranges = {};
  91541. this._lastAbsoluteTransformsUpdateId = -1;
  91542. /**
  91543. * Specifies if the skeleton should be serialized
  91544. */
  91545. this.doNotSerialize = false;
  91546. this._animationPropertiesOverride = null;
  91547. // Events
  91548. /**
  91549. * An observable triggered before computing the skeleton's matrices
  91550. */
  91551. this.onBeforeComputeObservable = new BABYLON.Observable();
  91552. this.bones = [];
  91553. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91554. scene.skeletons.push(this);
  91555. //make sure it will recalculate the matrix next time prepare is called.
  91556. this._isDirty = true;
  91557. }
  91558. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  91559. /**
  91560. * Gets or sets the animation properties override
  91561. */
  91562. get: function () {
  91563. if (!this._animationPropertiesOverride) {
  91564. return this._scene.animationPropertiesOverride;
  91565. }
  91566. return this._animationPropertiesOverride;
  91567. },
  91568. set: function (value) {
  91569. this._animationPropertiesOverride = value;
  91570. },
  91571. enumerable: true,
  91572. configurable: true
  91573. });
  91574. // Members
  91575. /**
  91576. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  91577. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  91578. * @returns a Float32Array containing matrices data
  91579. */
  91580. Skeleton.prototype.getTransformMatrices = function (mesh) {
  91581. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  91582. return mesh._bonesTransformMatrices;
  91583. }
  91584. if (!this._transformMatrices) {
  91585. this.prepare();
  91586. }
  91587. return this._transformMatrices;
  91588. };
  91589. /**
  91590. * Gets the current hosting scene
  91591. * @returns a scene object
  91592. */
  91593. Skeleton.prototype.getScene = function () {
  91594. return this._scene;
  91595. };
  91596. // Methods
  91597. /**
  91598. * Gets a string representing the current skeleton data
  91599. * @param fullDetails defines a boolean indicating if we want a verbose version
  91600. * @returns a string representing the current skeleton data
  91601. */
  91602. Skeleton.prototype.toString = function (fullDetails) {
  91603. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  91604. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  91605. if (fullDetails) {
  91606. ret += ", Ranges: {";
  91607. var first = true;
  91608. for (var name_1 in this._ranges) {
  91609. if (first) {
  91610. ret += ", ";
  91611. first = false;
  91612. }
  91613. ret += name_1;
  91614. }
  91615. ret += "}";
  91616. }
  91617. return ret;
  91618. };
  91619. /**
  91620. * Get bone's index searching by name
  91621. * @param name defines bone's name to search for
  91622. * @return the indice of the bone. Returns -1 if not found
  91623. */
  91624. Skeleton.prototype.getBoneIndexByName = function (name) {
  91625. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  91626. if (this.bones[boneIndex].name === name) {
  91627. return boneIndex;
  91628. }
  91629. }
  91630. return -1;
  91631. };
  91632. /**
  91633. * Creater a new animation range
  91634. * @param name defines the name of the range
  91635. * @param from defines the start key
  91636. * @param to defines the end key
  91637. */
  91638. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  91639. // check name not already in use
  91640. if (!this._ranges[name]) {
  91641. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  91642. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91643. if (this.bones[i].animations[0]) {
  91644. this.bones[i].animations[0].createRange(name, from, to);
  91645. }
  91646. }
  91647. }
  91648. };
  91649. /**
  91650. * Delete a specific animation range
  91651. * @param name defines the name of the range
  91652. * @param deleteFrames defines if frames must be removed as well
  91653. */
  91654. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  91655. if (deleteFrames === void 0) { deleteFrames = true; }
  91656. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91657. if (this.bones[i].animations[0]) {
  91658. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  91659. }
  91660. }
  91661. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  91662. };
  91663. /**
  91664. * Gets a specific animation range
  91665. * @param name defines the name of the range to look for
  91666. * @returns the requested animation range or null if not found
  91667. */
  91668. Skeleton.prototype.getAnimationRange = function (name) {
  91669. return this._ranges[name];
  91670. };
  91671. /**
  91672. * Gets the list of all animation ranges defined on this skeleton
  91673. * @returns an array
  91674. */
  91675. Skeleton.prototype.getAnimationRanges = function () {
  91676. var animationRanges = [];
  91677. var name;
  91678. var i = 0;
  91679. for (name in this._ranges) {
  91680. animationRanges[i] = this._ranges[name];
  91681. i++;
  91682. }
  91683. return animationRanges;
  91684. };
  91685. /**
  91686. * Copy animation range from a source skeleton.
  91687. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  91688. * @param source defines the source skeleton
  91689. * @param name defines the name of the range to copy
  91690. * @param rescaleAsRequired defines if rescaling must be applied if required
  91691. * @returns true if operation was successful
  91692. */
  91693. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  91694. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  91695. if (this._ranges[name] || !source.getAnimationRange(name)) {
  91696. return false;
  91697. }
  91698. var ret = true;
  91699. var frameOffset = this._getHighestAnimationFrame() + 1;
  91700. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  91701. var boneDict = {};
  91702. var sourceBones = source.bones;
  91703. var nBones;
  91704. var i;
  91705. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  91706. boneDict[sourceBones[i].name] = sourceBones[i];
  91707. }
  91708. if (this.bones.length !== sourceBones.length) {
  91709. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  91710. ret = false;
  91711. }
  91712. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  91713. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  91714. var boneName = this.bones[i].name;
  91715. var sourceBone = boneDict[boneName];
  91716. if (sourceBone) {
  91717. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  91718. }
  91719. else {
  91720. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  91721. ret = false;
  91722. }
  91723. }
  91724. // do not call createAnimationRange(), since it also is done to bones, which was already done
  91725. var range = source.getAnimationRange(name);
  91726. if (range) {
  91727. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  91728. }
  91729. return ret;
  91730. };
  91731. /**
  91732. * Forces the skeleton to go to rest pose
  91733. */
  91734. Skeleton.prototype.returnToRest = function () {
  91735. for (var index = 0; index < this.bones.length; index++) {
  91736. this.bones[index].returnToRest();
  91737. }
  91738. };
  91739. Skeleton.prototype._getHighestAnimationFrame = function () {
  91740. var ret = 0;
  91741. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  91742. if (this.bones[i].animations[0]) {
  91743. var highest = this.bones[i].animations[0].getHighestFrame();
  91744. if (ret < highest) {
  91745. ret = highest;
  91746. }
  91747. }
  91748. }
  91749. return ret;
  91750. };
  91751. /**
  91752. * Begin a specific animation range
  91753. * @param name defines the name of the range to start
  91754. * @param loop defines if looping must be turned on (false by default)
  91755. * @param speedRatio defines the speed ratio to apply (1 by default)
  91756. * @param onAnimationEnd defines a callback which will be called when animation will end
  91757. * @returns a new animatable
  91758. */
  91759. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  91760. var range = this.getAnimationRange(name);
  91761. if (!range) {
  91762. return null;
  91763. }
  91764. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  91765. };
  91766. /** @hidden */
  91767. Skeleton.prototype._markAsDirty = function () {
  91768. this._isDirty = true;
  91769. };
  91770. /** @hidden */
  91771. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  91772. this._meshesWithPoseMatrix.push(mesh);
  91773. };
  91774. /** @hidden */
  91775. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  91776. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  91777. if (index > -1) {
  91778. this._meshesWithPoseMatrix.splice(index, 1);
  91779. }
  91780. };
  91781. /** @hidden */
  91782. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  91783. this.onBeforeComputeObservable.notifyObservers(this);
  91784. for (var index = 0; index < this.bones.length; index++) {
  91785. var bone = this.bones[index];
  91786. var parentBone = bone.getParent();
  91787. if (parentBone) {
  91788. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  91789. }
  91790. else {
  91791. if (initialSkinMatrix) {
  91792. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  91793. }
  91794. else {
  91795. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  91796. }
  91797. }
  91798. if (bone._index !== -1) {
  91799. var mappedIndex = bone._index === null ? index : bone._index;
  91800. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  91801. }
  91802. }
  91803. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  91804. };
  91805. /**
  91806. * Build all resources required to render a skeleton
  91807. */
  91808. Skeleton.prototype.prepare = function () {
  91809. if (!this._isDirty) {
  91810. return;
  91811. }
  91812. if (this.needInitialSkinMatrix) {
  91813. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  91814. var mesh = this._meshesWithPoseMatrix[index];
  91815. var poseMatrix = mesh.getPoseMatrix();
  91816. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  91817. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  91818. }
  91819. if (this._synchronizedWithMesh !== mesh) {
  91820. this._synchronizedWithMesh = mesh;
  91821. // Prepare bones
  91822. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  91823. var bone = this.bones[boneIndex];
  91824. if (!bone.getParent()) {
  91825. var matrix = bone.getBaseMatrix();
  91826. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  91827. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  91828. }
  91829. }
  91830. }
  91831. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  91832. }
  91833. }
  91834. else {
  91835. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  91836. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  91837. }
  91838. this._computeTransformMatrices(this._transformMatrices, null);
  91839. }
  91840. this._isDirty = false;
  91841. this._scene._activeBones.addCount(this.bones.length, false);
  91842. };
  91843. /**
  91844. * Gets the list of animatables currently running for this skeleton
  91845. * @returns an array of animatables
  91846. */
  91847. Skeleton.prototype.getAnimatables = function () {
  91848. if (!this._animatables || this._animatables.length !== this.bones.length) {
  91849. this._animatables = [];
  91850. for (var index = 0; index < this.bones.length; index++) {
  91851. this._animatables.push(this.bones[index]);
  91852. }
  91853. }
  91854. return this._animatables;
  91855. };
  91856. /**
  91857. * Clone the current skeleton
  91858. * @param name defines the name of the new skeleton
  91859. * @param id defines the id of the enw skeleton
  91860. * @returns the new skeleton
  91861. */
  91862. Skeleton.prototype.clone = function (name, id) {
  91863. var result = new Skeleton(name, id || name, this._scene);
  91864. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  91865. for (var index = 0; index < this.bones.length; index++) {
  91866. var source = this.bones[index];
  91867. var parentBone = null;
  91868. var parent_1 = source.getParent();
  91869. if (parent_1) {
  91870. var parentIndex = this.bones.indexOf(parent_1);
  91871. parentBone = result.bones[parentIndex];
  91872. }
  91873. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  91874. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  91875. }
  91876. if (this._ranges) {
  91877. result._ranges = {};
  91878. for (var rangeName in this._ranges) {
  91879. var range = this._ranges[rangeName];
  91880. if (range) {
  91881. result._ranges[rangeName] = range.clone();
  91882. }
  91883. }
  91884. }
  91885. this._isDirty = true;
  91886. return result;
  91887. };
  91888. /**
  91889. * Enable animation blending for this skeleton
  91890. * @param blendingSpeed defines the blending speed to apply
  91891. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  91892. */
  91893. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  91894. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  91895. this.bones.forEach(function (bone) {
  91896. bone.animations.forEach(function (animation) {
  91897. animation.enableBlending = true;
  91898. animation.blendingSpeed = blendingSpeed;
  91899. });
  91900. });
  91901. };
  91902. /**
  91903. * Releases all resources associated with the current skeleton
  91904. */
  91905. Skeleton.prototype.dispose = function () {
  91906. this._meshesWithPoseMatrix = [];
  91907. // Animations
  91908. this.getScene().stopAnimation(this);
  91909. // Remove from scene
  91910. this.getScene().removeSkeleton(this);
  91911. };
  91912. /**
  91913. * Serialize the skeleton in a JSON object
  91914. * @returns a JSON object
  91915. */
  91916. Skeleton.prototype.serialize = function () {
  91917. var serializationObject = {};
  91918. serializationObject.name = this.name;
  91919. serializationObject.id = this.id;
  91920. if (this.dimensionsAtRest) {
  91921. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  91922. }
  91923. serializationObject.bones = [];
  91924. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  91925. for (var index = 0; index < this.bones.length; index++) {
  91926. var bone = this.bones[index];
  91927. var parent_2 = bone.getParent();
  91928. var serializedBone = {
  91929. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  91930. name: bone.name,
  91931. matrix: bone.getBaseMatrix().toArray(),
  91932. rest: bone.getRestPose().toArray()
  91933. };
  91934. serializationObject.bones.push(serializedBone);
  91935. if (bone.length) {
  91936. serializedBone.length = bone.length;
  91937. }
  91938. if (bone.metadata) {
  91939. serializedBone.metadata = bone.metadata;
  91940. }
  91941. if (bone.animations && bone.animations.length > 0) {
  91942. serializedBone.animation = bone.animations[0].serialize();
  91943. }
  91944. serializationObject.ranges = [];
  91945. for (var name in this._ranges) {
  91946. var source = this._ranges[name];
  91947. if (!source) {
  91948. continue;
  91949. }
  91950. var range = {};
  91951. range.name = name;
  91952. range.from = source.from;
  91953. range.to = source.to;
  91954. serializationObject.ranges.push(range);
  91955. }
  91956. }
  91957. return serializationObject;
  91958. };
  91959. /**
  91960. * Creates a new skeleton from serialized data
  91961. * @param parsedSkeleton defines the serialized data
  91962. * @param scene defines the hosting scene
  91963. * @returns a new skeleton
  91964. */
  91965. Skeleton.Parse = function (parsedSkeleton, scene) {
  91966. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  91967. if (parsedSkeleton.dimensionsAtRest) {
  91968. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  91969. }
  91970. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  91971. var index;
  91972. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  91973. var parsedBone = parsedSkeleton.bones[index];
  91974. var parentBone = null;
  91975. if (parsedBone.parentBoneIndex > -1) {
  91976. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  91977. }
  91978. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  91979. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  91980. if (parsedBone.id !== undefined && parsedBone.id !== null) {
  91981. bone.id = parsedBone.id;
  91982. }
  91983. if (parsedBone.length) {
  91984. bone.length = parsedBone.length;
  91985. }
  91986. if (parsedBone.metadata) {
  91987. bone.metadata = parsedBone.metadata;
  91988. }
  91989. if (parsedBone.animation) {
  91990. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  91991. }
  91992. }
  91993. // placed after bones, so createAnimationRange can cascade down
  91994. if (parsedSkeleton.ranges) {
  91995. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  91996. var data = parsedSkeleton.ranges[index];
  91997. skeleton.createAnimationRange(data.name, data.from, data.to);
  91998. }
  91999. }
  92000. return skeleton;
  92001. };
  92002. /**
  92003. * Compute all node absolute transforms
  92004. * @param forceUpdate defines if computation must be done even if cache is up to date
  92005. */
  92006. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  92007. if (forceUpdate === void 0) { forceUpdate = false; }
  92008. var renderId = this._scene.getRenderId();
  92009. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  92010. this.bones[0].computeAbsoluteTransforms();
  92011. this._lastAbsoluteTransformsUpdateId = renderId;
  92012. }
  92013. };
  92014. /**
  92015. * Gets the root pose matrix
  92016. * @returns a matrix
  92017. */
  92018. Skeleton.prototype.getPoseMatrix = function () {
  92019. var poseMatrix = null;
  92020. if (this._meshesWithPoseMatrix.length > 0) {
  92021. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  92022. }
  92023. return poseMatrix;
  92024. };
  92025. /**
  92026. * Sorts bones per internal index
  92027. */
  92028. Skeleton.prototype.sortBones = function () {
  92029. var bones = new Array();
  92030. var visited = new Array(this.bones.length);
  92031. for (var index = 0; index < this.bones.length; index++) {
  92032. this._sortBones(index, bones, visited);
  92033. }
  92034. this.bones = bones;
  92035. };
  92036. Skeleton.prototype._sortBones = function (index, bones, visited) {
  92037. if (visited[index]) {
  92038. return;
  92039. }
  92040. visited[index] = true;
  92041. var bone = this.bones[index];
  92042. if (bone._index === undefined) {
  92043. bone._index = index;
  92044. }
  92045. var parentBone = bone.getParent();
  92046. if (parentBone) {
  92047. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  92048. }
  92049. bones.push(bone);
  92050. };
  92051. return Skeleton;
  92052. }());
  92053. BABYLON.Skeleton = Skeleton;
  92054. })(BABYLON || (BABYLON = {}));
  92055. //# sourceMappingURL=babylon.skeleton.js.map
  92056. var BABYLON;
  92057. (function (BABYLON) {
  92058. ;
  92059. /**
  92060. * This groups tools to convert HDR texture to native colors array.
  92061. */
  92062. var HDRTools = /** @class */ (function () {
  92063. function HDRTools() {
  92064. }
  92065. HDRTools.Ldexp = function (mantissa, exponent) {
  92066. if (exponent > 1023) {
  92067. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  92068. }
  92069. if (exponent < -1074) {
  92070. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  92071. }
  92072. return mantissa * Math.pow(2, exponent);
  92073. };
  92074. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  92075. if (exponent > 0) { /*nonzero pixel*/
  92076. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  92077. float32array[index + 0] = red * exponent;
  92078. float32array[index + 1] = green * exponent;
  92079. float32array[index + 2] = blue * exponent;
  92080. }
  92081. else {
  92082. float32array[index + 0] = 0;
  92083. float32array[index + 1] = 0;
  92084. float32array[index + 2] = 0;
  92085. }
  92086. };
  92087. HDRTools.readStringLine = function (uint8array, startIndex) {
  92088. var line = "";
  92089. var character = "";
  92090. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  92091. character = String.fromCharCode(uint8array[i]);
  92092. if (character == "\n") {
  92093. break;
  92094. }
  92095. line += character;
  92096. }
  92097. return line;
  92098. };
  92099. /**
  92100. * Reads header information from an RGBE texture stored in a native array.
  92101. * More information on this format are available here:
  92102. * https://en.wikipedia.org/wiki/RGBE_image_format
  92103. *
  92104. * @param uint8array The binary file stored in native array.
  92105. * @return The header information.
  92106. */
  92107. HDRTools.RGBE_ReadHeader = function (uint8array) {
  92108. var height = 0;
  92109. var width = 0;
  92110. var line = this.readStringLine(uint8array, 0);
  92111. if (line[0] != '#' || line[1] != '?') {
  92112. throw "Bad HDR Format.";
  92113. }
  92114. var endOfHeader = false;
  92115. var findFormat = false;
  92116. var lineIndex = 0;
  92117. do {
  92118. lineIndex += (line.length + 1);
  92119. line = this.readStringLine(uint8array, lineIndex);
  92120. if (line == "FORMAT=32-bit_rle_rgbe") {
  92121. findFormat = true;
  92122. }
  92123. else if (line.length == 0) {
  92124. endOfHeader = true;
  92125. }
  92126. } while (!endOfHeader);
  92127. if (!findFormat) {
  92128. throw "HDR Bad header format, unsupported FORMAT";
  92129. }
  92130. lineIndex += (line.length + 1);
  92131. line = this.readStringLine(uint8array, lineIndex);
  92132. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  92133. var match = sizeRegexp.exec(line);
  92134. // TODO. Support +Y and -X if needed.
  92135. if (!match || match.length < 3) {
  92136. throw "HDR Bad header format, no size";
  92137. }
  92138. width = parseInt(match[2]);
  92139. height = parseInt(match[1]);
  92140. if (width < 8 || width > 0x7fff) {
  92141. throw "HDR Bad header format, unsupported size";
  92142. }
  92143. lineIndex += (line.length + 1);
  92144. return {
  92145. height: height,
  92146. width: width,
  92147. dataPosition: lineIndex
  92148. };
  92149. };
  92150. /**
  92151. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  92152. * This RGBE texture needs to store the information as a panorama.
  92153. *
  92154. * More information on this format are available here:
  92155. * https://en.wikipedia.org/wiki/RGBE_image_format
  92156. *
  92157. * @param buffer The binary file stored in an array buffer.
  92158. * @param size The expected size of the extracted cubemap.
  92159. * @return The Cube Map information.
  92160. */
  92161. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  92162. var uint8array = new Uint8Array(buffer);
  92163. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  92164. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92165. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  92166. return cubeMapData;
  92167. };
  92168. /**
  92169. * Returns the pixels data extracted from an RGBE texture.
  92170. * This pixels will be stored left to right up to down in the R G B order in one array.
  92171. *
  92172. * More information on this format are available here:
  92173. * https://en.wikipedia.org/wiki/RGBE_image_format
  92174. *
  92175. * @param uint8array The binary file stored in an array buffer.
  92176. * @param hdrInfo The header information of the file.
  92177. * @return The pixels data in RGB right to left up to down order.
  92178. */
  92179. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  92180. // Keep for multi format supports.
  92181. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  92182. };
  92183. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  92184. var num_scanlines = hdrInfo.height;
  92185. var scanline_width = hdrInfo.width;
  92186. var a, b, c, d, count;
  92187. var dataIndex = hdrInfo.dataPosition;
  92188. var index = 0, endIndex = 0, i = 0;
  92189. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  92190. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  92191. // 3 channels of 4 bytes per pixel in float.
  92192. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  92193. var resultArray = new Float32Array(resultBuffer);
  92194. // read in each successive scanline
  92195. while (num_scanlines > 0) {
  92196. a = uint8array[dataIndex++];
  92197. b = uint8array[dataIndex++];
  92198. c = uint8array[dataIndex++];
  92199. d = uint8array[dataIndex++];
  92200. if (a != 2 || b != 2 || (c & 0x80)) {
  92201. // this file is not run length encoded
  92202. throw "HDR Bad header format, not RLE";
  92203. }
  92204. if (((c << 8) | d) != scanline_width) {
  92205. throw "HDR Bad header format, wrong scan line width";
  92206. }
  92207. index = 0;
  92208. // read each of the four channels for the scanline into the buffer
  92209. for (i = 0; i < 4; i++) {
  92210. endIndex = (i + 1) * scanline_width;
  92211. while (index < endIndex) {
  92212. a = uint8array[dataIndex++];
  92213. b = uint8array[dataIndex++];
  92214. if (a > 128) {
  92215. // a run of the same value
  92216. count = a - 128;
  92217. if ((count == 0) || (count > endIndex - index)) {
  92218. throw "HDR Bad Format, bad scanline data (run)";
  92219. }
  92220. while (count-- > 0) {
  92221. scanLineArray[index++] = b;
  92222. }
  92223. }
  92224. else {
  92225. // a non-run
  92226. count = a;
  92227. if ((count == 0) || (count > endIndex - index)) {
  92228. throw "HDR Bad Format, bad scanline data (non-run)";
  92229. }
  92230. scanLineArray[index++] = b;
  92231. if (--count > 0) {
  92232. for (var j = 0; j < count; j++) {
  92233. scanLineArray[index++] = uint8array[dataIndex++];
  92234. }
  92235. }
  92236. }
  92237. }
  92238. }
  92239. // now convert data from buffer into floats
  92240. for (i = 0; i < scanline_width; i++) {
  92241. a = scanLineArray[i];
  92242. b = scanLineArray[i + scanline_width];
  92243. c = scanLineArray[i + 2 * scanline_width];
  92244. d = scanLineArray[i + 3 * scanline_width];
  92245. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  92246. }
  92247. num_scanlines--;
  92248. }
  92249. return resultArray;
  92250. };
  92251. return HDRTools;
  92252. }());
  92253. BABYLON.HDRTools = HDRTools;
  92254. })(BABYLON || (BABYLON = {}));
  92255. //# sourceMappingURL=babylon.hdr.js.map
  92256. var BABYLON;
  92257. (function (BABYLON) {
  92258. /**
  92259. * This represents a texture coming from an HDR input.
  92260. *
  92261. * The only supported format is currently panorama picture stored in RGBE format.
  92262. * Example of such files can be found on HDRLib: http://hdrlib.com/
  92263. */
  92264. var HDRCubeTexture = /** @class */ (function (_super) {
  92265. __extends(HDRCubeTexture, _super);
  92266. /**
  92267. * Instantiates an HDRTexture from the following parameters.
  92268. *
  92269. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  92270. * @param scene The scene the texture will be used in
  92271. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  92272. * @param noMipmap Forces to not generate the mipmap if true
  92273. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  92274. * @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)
  92275. * @param reserved Reserved flag for internal use.
  92276. */
  92277. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  92278. if (noMipmap === void 0) { noMipmap = false; }
  92279. if (generateHarmonics === void 0) { generateHarmonics = true; }
  92280. if (gammaSpace === void 0) { gammaSpace = false; }
  92281. if (reserved === void 0) { reserved = false; }
  92282. if (onLoad === void 0) { onLoad = null; }
  92283. if (onError === void 0) { onError = null; }
  92284. var _this = _super.call(this, scene) || this;
  92285. _this._generateHarmonics = true;
  92286. _this._onLoad = null;
  92287. _this._onError = null;
  92288. /**
  92289. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  92290. */
  92291. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  92292. _this._isBlocking = true;
  92293. _this._rotationY = 0;
  92294. /**
  92295. * Gets or sets the center of the bounding box associated with the cube texture
  92296. * It must define where the camera used to render the texture was set
  92297. */
  92298. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  92299. if (!url) {
  92300. return _this;
  92301. }
  92302. _this.name = url;
  92303. _this.url = url;
  92304. _this.hasAlpha = false;
  92305. _this.isCube = true;
  92306. _this._textureMatrix = BABYLON.Matrix.Identity();
  92307. _this._onLoad = onLoad;
  92308. _this._onError = onError;
  92309. _this.gammaSpace = gammaSpace;
  92310. _this._noMipmap = noMipmap;
  92311. _this._size = size;
  92312. _this._texture = _this._getFromCache(url, _this._noMipmap);
  92313. if (!_this._texture) {
  92314. if (!scene.useDelayedTextureLoading) {
  92315. _this.loadTexture();
  92316. }
  92317. else {
  92318. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  92319. }
  92320. }
  92321. return _this;
  92322. }
  92323. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  92324. /**
  92325. * Gets wether or not the texture is blocking during loading.
  92326. */
  92327. get: function () {
  92328. return this._isBlocking;
  92329. },
  92330. /**
  92331. * Sets wether or not the texture is blocking during loading.
  92332. */
  92333. set: function (value) {
  92334. this._isBlocking = value;
  92335. },
  92336. enumerable: true,
  92337. configurable: true
  92338. });
  92339. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  92340. /**
  92341. * Gets texture matrix rotation angle around Y axis radians.
  92342. */
  92343. get: function () {
  92344. return this._rotationY;
  92345. },
  92346. /**
  92347. * Sets texture matrix rotation angle around Y axis in radians.
  92348. */
  92349. set: function (value) {
  92350. this._rotationY = value;
  92351. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  92352. },
  92353. enumerable: true,
  92354. configurable: true
  92355. });
  92356. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  92357. get: function () {
  92358. return this._boundingBoxSize;
  92359. },
  92360. /**
  92361. * Gets or sets the size of the bounding box associated with the cube texture
  92362. * When defined, the cubemap will switch to local mode
  92363. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  92364. * @example https://www.babylonjs-playground.com/#RNASML
  92365. */
  92366. set: function (value) {
  92367. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  92368. return;
  92369. }
  92370. this._boundingBoxSize = value;
  92371. var scene = this.getScene();
  92372. if (scene) {
  92373. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  92374. }
  92375. },
  92376. enumerable: true,
  92377. configurable: true
  92378. });
  92379. /**
  92380. * Occurs when the file is raw .hdr file.
  92381. */
  92382. HDRCubeTexture.prototype.loadTexture = function () {
  92383. var _this = this;
  92384. var callback = function (buffer) {
  92385. _this.lodGenerationOffset = 0.0;
  92386. _this.lodGenerationScale = 0.8;
  92387. var scene = _this.getScene();
  92388. if (!scene) {
  92389. return null;
  92390. }
  92391. // Extract the raw linear data.
  92392. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  92393. // Generate harmonics if needed.
  92394. if (_this._generateHarmonics) {
  92395. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  92396. _this.sphericalPolynomial = sphericalPolynomial;
  92397. }
  92398. var results = [];
  92399. var byteArray = null;
  92400. // Push each faces.
  92401. for (var j = 0; j < 6; j++) {
  92402. // Create uintarray fallback.
  92403. if (!scene.getEngine().getCaps().textureFloat) {
  92404. // 3 channels of 1 bytes per pixel in bytes.
  92405. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  92406. byteArray = new Uint8Array(byteBuffer);
  92407. }
  92408. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  92409. // If special cases.
  92410. if (_this.gammaSpace || byteArray) {
  92411. for (var i = 0; i < _this._size * _this._size; i++) {
  92412. // Put in gamma space if requested.
  92413. if (_this.gammaSpace) {
  92414. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  92415. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  92416. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  92417. }
  92418. // Convert to int texture for fallback.
  92419. if (byteArray) {
  92420. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  92421. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  92422. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  92423. // May use luminance instead if the result is not accurate.
  92424. var max = Math.max(Math.max(r, g), b);
  92425. if (max > 255) {
  92426. var scale = 255 / max;
  92427. r *= scale;
  92428. g *= scale;
  92429. b *= scale;
  92430. }
  92431. byteArray[(i * 3) + 0] = r;
  92432. byteArray[(i * 3) + 1] = g;
  92433. byteArray[(i * 3) + 2] = b;
  92434. }
  92435. }
  92436. }
  92437. if (byteArray) {
  92438. results.push(byteArray);
  92439. }
  92440. else {
  92441. results.push(dataFace);
  92442. }
  92443. }
  92444. return results;
  92445. };
  92446. var scene = this.getScene();
  92447. if (scene) {
  92448. 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);
  92449. }
  92450. };
  92451. HDRCubeTexture.prototype.clone = function () {
  92452. var scene = this.getScene();
  92453. if (!scene) {
  92454. return this;
  92455. }
  92456. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  92457. // Base texture
  92458. newTexture.level = this.level;
  92459. newTexture.wrapU = this.wrapU;
  92460. newTexture.wrapV = this.wrapV;
  92461. newTexture.coordinatesIndex = this.coordinatesIndex;
  92462. newTexture.coordinatesMode = this.coordinatesMode;
  92463. return newTexture;
  92464. };
  92465. // Methods
  92466. HDRCubeTexture.prototype.delayLoad = function () {
  92467. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  92468. return;
  92469. }
  92470. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  92471. this._texture = this._getFromCache(this.url, this._noMipmap);
  92472. if (!this._texture) {
  92473. this.loadTexture();
  92474. }
  92475. };
  92476. /**
  92477. * Get the texture reflection matrix used to rotate/transform the reflection.
  92478. * @returns the reflection matrix
  92479. */
  92480. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  92481. return this._textureMatrix;
  92482. };
  92483. /**
  92484. * Set the texture reflection matrix used to rotate/transform the reflection.
  92485. * @param value Define the reflection matrix to set
  92486. */
  92487. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  92488. this._textureMatrix = value;
  92489. };
  92490. /**
  92491. * Parses a JSON representation of an HDR Texture in order to create the texture
  92492. * @param parsedTexture Define the JSON representation
  92493. * @param scene Define the scene the texture should be created in
  92494. * @param rootUrl Define the root url in case we need to load relative dependencies
  92495. * @returns the newly created texture after parsing
  92496. */
  92497. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  92498. var texture = null;
  92499. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  92500. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  92501. texture.name = parsedTexture.name;
  92502. texture.hasAlpha = parsedTexture.hasAlpha;
  92503. texture.level = parsedTexture.level;
  92504. texture.coordinatesMode = parsedTexture.coordinatesMode;
  92505. texture.isBlocking = parsedTexture.isBlocking;
  92506. }
  92507. if (texture) {
  92508. if (parsedTexture.boundingBoxPosition) {
  92509. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  92510. }
  92511. if (parsedTexture.boundingBoxSize) {
  92512. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  92513. }
  92514. if (parsedTexture.rotationY) {
  92515. texture.rotationY = parsedTexture.rotationY;
  92516. }
  92517. }
  92518. return texture;
  92519. };
  92520. HDRCubeTexture.prototype.serialize = function () {
  92521. if (!this.name) {
  92522. return null;
  92523. }
  92524. var serializationObject = {};
  92525. serializationObject.name = this.name;
  92526. serializationObject.hasAlpha = this.hasAlpha;
  92527. serializationObject.isCube = true;
  92528. serializationObject.level = this.level;
  92529. serializationObject.size = this._size;
  92530. serializationObject.coordinatesMode = this.coordinatesMode;
  92531. serializationObject.useInGammaSpace = this.gammaSpace;
  92532. serializationObject.generateHarmonics = this._generateHarmonics;
  92533. serializationObject.customType = "BABYLON.HDRCubeTexture";
  92534. serializationObject.noMipmap = this._noMipmap;
  92535. serializationObject.isBlocking = this._isBlocking;
  92536. serializationObject.rotationY = this._rotationY;
  92537. return serializationObject;
  92538. };
  92539. HDRCubeTexture._facesMapping = [
  92540. "right",
  92541. "left",
  92542. "up",
  92543. "down",
  92544. "front",
  92545. "back"
  92546. ];
  92547. return HDRCubeTexture;
  92548. }(BABYLON.BaseTexture));
  92549. BABYLON.HDRCubeTexture = HDRCubeTexture;
  92550. })(BABYLON || (BABYLON = {}));
  92551. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  92552. var BABYLON;
  92553. (function (BABYLON) {
  92554. /**
  92555. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  92556. */
  92557. var PanoramaToCubeMapTools = /** @class */ (function () {
  92558. function PanoramaToCubeMapTools() {
  92559. }
  92560. /**
  92561. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  92562. *
  92563. * @param float32Array The source data.
  92564. * @param inputWidth The width of the input panorama.
  92565. * @param inputHeight The height of the input panorama.
  92566. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  92567. * @return The cubemap data
  92568. */
  92569. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  92570. if (!float32Array) {
  92571. throw "ConvertPanoramaToCubemap: input cannot be null";
  92572. }
  92573. if (float32Array.length != inputWidth * inputHeight * 3) {
  92574. throw "ConvertPanoramaToCubemap: input size is wrong";
  92575. }
  92576. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  92577. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  92578. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  92579. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  92580. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  92581. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  92582. return {
  92583. front: textureFront,
  92584. back: textureBack,
  92585. left: textureLeft,
  92586. right: textureRight,
  92587. up: textureUp,
  92588. down: textureDown,
  92589. size: size,
  92590. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  92591. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  92592. gammaSpace: false,
  92593. };
  92594. };
  92595. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  92596. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  92597. var textureArray = new Float32Array(buffer);
  92598. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  92599. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  92600. var dy = 1 / texSize;
  92601. var fy = 0;
  92602. for (var y = 0; y < texSize; y++) {
  92603. var xv1 = faceData[0];
  92604. var xv2 = faceData[2];
  92605. for (var x = 0; x < texSize; x++) {
  92606. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  92607. v.normalize();
  92608. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  92609. // 3 channels per pixels
  92610. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  92611. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  92612. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  92613. xv1 = xv1.add(rotDX1);
  92614. xv2 = xv2.add(rotDX2);
  92615. }
  92616. fy += dy;
  92617. }
  92618. return textureArray;
  92619. };
  92620. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  92621. var theta = Math.atan2(vDir.z, vDir.x);
  92622. var phi = Math.acos(vDir.y);
  92623. while (theta < -Math.PI)
  92624. theta += 2 * Math.PI;
  92625. while (theta > Math.PI)
  92626. theta -= 2 * Math.PI;
  92627. var dx = theta / Math.PI;
  92628. var dy = phi / Math.PI;
  92629. // recenter.
  92630. dx = dx * 0.5 + 0.5;
  92631. var px = Math.round(dx * inputWidth);
  92632. if (px < 0)
  92633. px = 0;
  92634. else if (px >= inputWidth)
  92635. px = inputWidth - 1;
  92636. var py = Math.round(dy * inputHeight);
  92637. if (py < 0)
  92638. py = 0;
  92639. else if (py >= inputHeight)
  92640. py = inputHeight - 1;
  92641. var inputY = (inputHeight - py - 1);
  92642. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  92643. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  92644. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  92645. return {
  92646. r: r,
  92647. g: g,
  92648. b: b
  92649. };
  92650. };
  92651. PanoramaToCubeMapTools.FACE_FRONT = [
  92652. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92653. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92654. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92655. new BABYLON.Vector3(1.0, 1.0, -1.0)
  92656. ];
  92657. PanoramaToCubeMapTools.FACE_BACK = [
  92658. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92659. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92660. new BABYLON.Vector3(1.0, 1.0, 1.0),
  92661. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  92662. ];
  92663. PanoramaToCubeMapTools.FACE_RIGHT = [
  92664. new BABYLON.Vector3(1.0, -1.0, -1.0),
  92665. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92666. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92667. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92668. ];
  92669. PanoramaToCubeMapTools.FACE_LEFT = [
  92670. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92671. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92672. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92673. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  92674. ];
  92675. PanoramaToCubeMapTools.FACE_DOWN = [
  92676. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  92677. new BABYLON.Vector3(1.0, 1.0, -1.0),
  92678. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  92679. new BABYLON.Vector3(1.0, 1.0, 1.0)
  92680. ];
  92681. PanoramaToCubeMapTools.FACE_UP = [
  92682. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  92683. new BABYLON.Vector3(1.0, -1.0, 1.0),
  92684. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  92685. new BABYLON.Vector3(1.0, -1.0, -1.0)
  92686. ];
  92687. return PanoramaToCubeMapTools;
  92688. }());
  92689. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  92690. })(BABYLON || (BABYLON = {}));
  92691. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  92692. var BABYLON;
  92693. (function (BABYLON) {
  92694. /**
  92695. * Vector2 wth index property
  92696. */
  92697. var IndexedVector2 = /** @class */ (function (_super) {
  92698. __extends(IndexedVector2, _super);
  92699. function IndexedVector2(original,
  92700. /** Index of the vector2 */
  92701. index) {
  92702. var _this = _super.call(this, original.x, original.y) || this;
  92703. _this.index = index;
  92704. return _this;
  92705. }
  92706. return IndexedVector2;
  92707. }(BABYLON.Vector2));
  92708. /**
  92709. * Defines points to create a polygon
  92710. */
  92711. var PolygonPoints = /** @class */ (function () {
  92712. function PolygonPoints() {
  92713. this.elements = new Array();
  92714. }
  92715. PolygonPoints.prototype.add = function (originalPoints) {
  92716. var _this = this;
  92717. var result = new Array();
  92718. originalPoints.forEach(function (point) {
  92719. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  92720. var newPoint = new IndexedVector2(point, _this.elements.length);
  92721. result.push(newPoint);
  92722. _this.elements.push(newPoint);
  92723. }
  92724. });
  92725. return result;
  92726. };
  92727. PolygonPoints.prototype.computeBounds = function () {
  92728. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92729. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  92730. this.elements.forEach(function (point) {
  92731. // x
  92732. if (point.x < lmin.x) {
  92733. lmin.x = point.x;
  92734. }
  92735. else if (point.x > lmax.x) {
  92736. lmax.x = point.x;
  92737. }
  92738. // y
  92739. if (point.y < lmin.y) {
  92740. lmin.y = point.y;
  92741. }
  92742. else if (point.y > lmax.y) {
  92743. lmax.y = point.y;
  92744. }
  92745. });
  92746. return {
  92747. min: lmin,
  92748. max: lmax,
  92749. width: lmax.x - lmin.x,
  92750. height: lmax.y - lmin.y
  92751. };
  92752. };
  92753. return PolygonPoints;
  92754. }());
  92755. /**
  92756. * Polygon
  92757. * @see https://doc.babylonjs.com/how_to/parametric_shapes#non-regular-polygon
  92758. */
  92759. var Polygon = /** @class */ (function () {
  92760. function Polygon() {
  92761. }
  92762. /**
  92763. * Creates a rectangle
  92764. * @param xmin bottom X coord
  92765. * @param ymin bottom Y coord
  92766. * @param xmax top X coord
  92767. * @param ymax top Y coord
  92768. * @returns points that make the resulting rectation
  92769. */
  92770. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  92771. return [
  92772. new BABYLON.Vector2(xmin, ymin),
  92773. new BABYLON.Vector2(xmax, ymin),
  92774. new BABYLON.Vector2(xmax, ymax),
  92775. new BABYLON.Vector2(xmin, ymax)
  92776. ];
  92777. };
  92778. /**
  92779. * Creates a circle
  92780. * @param radius radius of circle
  92781. * @param cx scale in x
  92782. * @param cy scale in y
  92783. * @param numberOfSides number of sides that make up the circle
  92784. * @returns points that make the resulting circle
  92785. */
  92786. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  92787. if (cx === void 0) { cx = 0; }
  92788. if (cy === void 0) { cy = 0; }
  92789. if (numberOfSides === void 0) { numberOfSides = 32; }
  92790. var result = new Array();
  92791. var angle = 0;
  92792. var increment = (Math.PI * 2) / numberOfSides;
  92793. for (var i = 0; i < numberOfSides; i++) {
  92794. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  92795. angle -= increment;
  92796. }
  92797. return result;
  92798. };
  92799. /**
  92800. * Creates a polygon from input string
  92801. * @param input Input polygon data
  92802. * @returns the parsed points
  92803. */
  92804. Polygon.Parse = function (input) {
  92805. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  92806. var i, result = [];
  92807. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  92808. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  92809. }
  92810. return result;
  92811. };
  92812. /**
  92813. * Starts building a polygon from x and y coordinates
  92814. * @param x x coordinate
  92815. * @param y y coordinate
  92816. * @returns the started path2
  92817. */
  92818. Polygon.StartingAt = function (x, y) {
  92819. return BABYLON.Path2.StartingAt(x, y);
  92820. };
  92821. return Polygon;
  92822. }());
  92823. BABYLON.Polygon = Polygon;
  92824. /**
  92825. * Builds a polygon
  92826. * @see https://doc.babylonjs.com/how_to/polygonmeshbuilder
  92827. */
  92828. var PolygonMeshBuilder = /** @class */ (function () {
  92829. /**
  92830. * Creates a PolygonMeshBuilder
  92831. * @param name name of the builder
  92832. * @param contours Path of the polygon
  92833. * @param scene scene to add to
  92834. */
  92835. function PolygonMeshBuilder(name, contours, scene) {
  92836. this._points = new PolygonPoints();
  92837. this._outlinepoints = new PolygonPoints();
  92838. this._holes = new Array();
  92839. this._epoints = new Array();
  92840. this._eholes = new Array();
  92841. this._name = name;
  92842. this._scene = scene;
  92843. var points;
  92844. if (contours instanceof BABYLON.Path2) {
  92845. points = contours.getPoints();
  92846. }
  92847. else {
  92848. points = contours;
  92849. }
  92850. this._addToepoint(points);
  92851. this._points.add(points);
  92852. this._outlinepoints.add(points);
  92853. if (typeof earcut === 'undefined') {
  92854. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  92855. }
  92856. }
  92857. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  92858. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  92859. var p = points_1[_i];
  92860. this._epoints.push(p.x, p.y);
  92861. }
  92862. };
  92863. /**
  92864. * Adds a whole within the polygon
  92865. * @param hole Array of points defining the hole
  92866. * @returns this
  92867. */
  92868. PolygonMeshBuilder.prototype.addHole = function (hole) {
  92869. this._points.add(hole);
  92870. var holepoints = new PolygonPoints();
  92871. holepoints.add(hole);
  92872. this._holes.push(holepoints);
  92873. this._eholes.push(this._epoints.length / 2);
  92874. this._addToepoint(hole);
  92875. return this;
  92876. };
  92877. /**
  92878. * Creates the polygon
  92879. * @param updatable If the mesh should be updatable
  92880. * @param depth The depth of the mesh created
  92881. * @returns the created mesh
  92882. */
  92883. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  92884. var _this = this;
  92885. if (updatable === void 0) { updatable = false; }
  92886. if (depth === void 0) { depth = 0; }
  92887. var result = new BABYLON.Mesh(this._name, this._scene);
  92888. var normals = new Array();
  92889. var positions = new Array();
  92890. var uvs = new Array();
  92891. var bounds = this._points.computeBounds();
  92892. this._points.elements.forEach(function (p) {
  92893. normals.push(0, 1.0, 0);
  92894. positions.push(p.x, 0, p.y);
  92895. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  92896. });
  92897. var indices = new Array();
  92898. var res = earcut(this._epoints, this._eholes, 2);
  92899. for (var i = 0; i < res.length; i++) {
  92900. indices.push(res[i]);
  92901. }
  92902. if (depth > 0) {
  92903. var positionscount = (positions.length / 3); //get the current pointcount
  92904. this._points.elements.forEach(function (p) {
  92905. normals.push(0, -1.0, 0);
  92906. positions.push(p.x, -depth, p.y);
  92907. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  92908. });
  92909. var totalCount = indices.length;
  92910. for (var i = 0; i < totalCount; i += 3) {
  92911. var i0 = indices[i + 0];
  92912. var i1 = indices[i + 1];
  92913. var i2 = indices[i + 2];
  92914. indices.push(i2 + positionscount);
  92915. indices.push(i1 + positionscount);
  92916. indices.push(i0 + positionscount);
  92917. }
  92918. //Add the sides
  92919. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  92920. this._holes.forEach(function (hole) {
  92921. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  92922. });
  92923. }
  92924. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  92925. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  92926. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  92927. result.setIndices(indices);
  92928. return result;
  92929. };
  92930. /**
  92931. * Adds a side to the polygon
  92932. * @param positions points that make the polygon
  92933. * @param normals normals of the polygon
  92934. * @param uvs uvs of the polygon
  92935. * @param indices indices of the polygon
  92936. * @param bounds bounds of the polygon
  92937. * @param points points of the polygon
  92938. * @param depth depth of the polygon
  92939. * @param flip flip of the polygon
  92940. */
  92941. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  92942. var StartIndex = positions.length / 3;
  92943. var ulength = 0;
  92944. for (var i = 0; i < points.elements.length; i++) {
  92945. var p = points.elements[i];
  92946. var p1;
  92947. if ((i + 1) > points.elements.length - 1) {
  92948. p1 = points.elements[0];
  92949. }
  92950. else {
  92951. p1 = points.elements[i + 1];
  92952. }
  92953. positions.push(p.x, 0, p.y);
  92954. positions.push(p.x, -depth, p.y);
  92955. positions.push(p1.x, 0, p1.y);
  92956. positions.push(p1.x, -depth, p1.y);
  92957. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  92958. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  92959. var v3 = v2.subtract(v1);
  92960. var v4 = new BABYLON.Vector3(0, 1, 0);
  92961. var vn = BABYLON.Vector3.Cross(v3, v4);
  92962. vn = vn.normalize();
  92963. uvs.push(ulength / bounds.width, 0);
  92964. uvs.push(ulength / bounds.width, 1);
  92965. ulength += v3.length();
  92966. uvs.push((ulength / bounds.width), 0);
  92967. uvs.push((ulength / bounds.width), 1);
  92968. if (!flip) {
  92969. normals.push(-vn.x, -vn.y, -vn.z);
  92970. normals.push(-vn.x, -vn.y, -vn.z);
  92971. normals.push(-vn.x, -vn.y, -vn.z);
  92972. normals.push(-vn.x, -vn.y, -vn.z);
  92973. indices.push(StartIndex);
  92974. indices.push(StartIndex + 1);
  92975. indices.push(StartIndex + 2);
  92976. indices.push(StartIndex + 1);
  92977. indices.push(StartIndex + 3);
  92978. indices.push(StartIndex + 2);
  92979. }
  92980. else {
  92981. normals.push(vn.x, vn.y, vn.z);
  92982. normals.push(vn.x, vn.y, vn.z);
  92983. normals.push(vn.x, vn.y, vn.z);
  92984. normals.push(vn.x, vn.y, vn.z);
  92985. indices.push(StartIndex);
  92986. indices.push(StartIndex + 2);
  92987. indices.push(StartIndex + 1);
  92988. indices.push(StartIndex + 1);
  92989. indices.push(StartIndex + 2);
  92990. indices.push(StartIndex + 3);
  92991. }
  92992. StartIndex += 4;
  92993. }
  92994. ;
  92995. };
  92996. return PolygonMeshBuilder;
  92997. }());
  92998. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  92999. })(BABYLON || (BABYLON = {}));
  93000. //# sourceMappingURL=babylon.polygonMesh.js.map
  93001. var BABYLON;
  93002. (function (BABYLON) {
  93003. /**
  93004. * Unique ID when we import meshes from Babylon to CSG
  93005. */
  93006. var currentCSGMeshId = 0;
  93007. /**
  93008. * Represents a vertex of a polygon. Use your own vertex class instead of this
  93009. * one to provide additional features like texture coordinates and vertex
  93010. * colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  93011. * `flip()`, and `interpolate()` methods that behave analogous to the ones
  93012. * defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  93013. * functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  93014. * is not used anywhere else.
  93015. * Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  93016. */
  93017. var Vertex = /** @class */ (function () {
  93018. /**
  93019. * Initializes the vertex
  93020. * @param pos The position of the vertex
  93021. * @param normal The normal of the vertex
  93022. * @param uv The texture coordinate of the vertex
  93023. */
  93024. function Vertex(
  93025. /**
  93026. * The position of the vertex
  93027. */
  93028. pos,
  93029. /**
  93030. * The normal of the vertex
  93031. */
  93032. normal,
  93033. /**
  93034. * The texture coordinate of the vertex
  93035. */
  93036. uv) {
  93037. this.pos = pos;
  93038. this.normal = normal;
  93039. this.uv = uv;
  93040. }
  93041. /**
  93042. * Make a clone, or deep copy, of the vertex
  93043. * @returns A new Vertex
  93044. */
  93045. Vertex.prototype.clone = function () {
  93046. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  93047. };
  93048. /**
  93049. * Invert all orientation-specific data (e.g. vertex normal). Called when the
  93050. * orientation of a polygon is flipped.
  93051. */
  93052. Vertex.prototype.flip = function () {
  93053. this.normal = this.normal.scale(-1);
  93054. };
  93055. /**
  93056. * Create a new vertex between this vertex and `other` by linearly
  93057. * interpolating all properties using a parameter of `t`. Subclasses should
  93058. * override this to interpolate additional properties.
  93059. * @param other the vertex to interpolate against
  93060. * @param t The factor used to linearly interpolate between the vertices
  93061. */
  93062. Vertex.prototype.interpolate = function (other, t) {
  93063. 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));
  93064. };
  93065. return Vertex;
  93066. }());
  93067. /**
  93068. * Represents a plane in 3D space.
  93069. */
  93070. var Plane = /** @class */ (function () {
  93071. /**
  93072. * Initializes the plane
  93073. * @param normal The normal for the plane
  93074. * @param w
  93075. */
  93076. function Plane(normal, w) {
  93077. this.normal = normal;
  93078. this.w = w;
  93079. }
  93080. /**
  93081. * Construct a plane from three points
  93082. * @param a Point a
  93083. * @param b Point b
  93084. * @param c Point c
  93085. */
  93086. Plane.FromPoints = function (a, b, c) {
  93087. var v0 = c.subtract(a);
  93088. var v1 = b.subtract(a);
  93089. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  93090. return null;
  93091. }
  93092. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  93093. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  93094. };
  93095. /**
  93096. * Clone, or make a deep copy of the plane
  93097. * @returns a new Plane
  93098. */
  93099. Plane.prototype.clone = function () {
  93100. return new Plane(this.normal.clone(), this.w);
  93101. };
  93102. /**
  93103. * Flip the face of the plane
  93104. */
  93105. Plane.prototype.flip = function () {
  93106. this.normal.scaleInPlace(-1);
  93107. this.w = -this.w;
  93108. };
  93109. /**
  93110. * Split `polygon` by this plane if needed, then put the polygon or polygon
  93111. * fragments in the appropriate lists. Coplanar polygons go into either
  93112. `* coplanarFront` or `coplanarBack` depending on their orientation with
  93113. * respect to this plane. Polygons in front or in back of this plane go into
  93114. * either `front` or `back`
  93115. * @param polygon The polygon to be split
  93116. * @param coplanarFront Will contain polygons coplanar with the plane that are oriented to the front of the plane
  93117. * @param coplanarBack Will contain polygons coplanar with the plane that are oriented to the back of the plane
  93118. * @param front Will contain the polygons in front of the plane
  93119. * @param back Will contain the polygons begind the plane
  93120. */
  93121. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  93122. var COPLANAR = 0;
  93123. var FRONT = 1;
  93124. var BACK = 2;
  93125. var SPANNING = 3;
  93126. // Classify each point as well as the entire polygon into one of the above
  93127. // four classes.
  93128. var polygonType = 0;
  93129. var types = [];
  93130. var i;
  93131. var t;
  93132. for (i = 0; i < polygon.vertices.length; i++) {
  93133. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  93134. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  93135. polygonType |= type;
  93136. types.push(type);
  93137. }
  93138. // Put the polygon in the correct list, splitting it when necessary
  93139. switch (polygonType) {
  93140. case COPLANAR:
  93141. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  93142. break;
  93143. case FRONT:
  93144. front.push(polygon);
  93145. break;
  93146. case BACK:
  93147. back.push(polygon);
  93148. break;
  93149. case SPANNING:
  93150. var f = [], b = [];
  93151. for (i = 0; i < polygon.vertices.length; i++) {
  93152. var j = (i + 1) % polygon.vertices.length;
  93153. var ti = types[i], tj = types[j];
  93154. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  93155. if (ti !== BACK)
  93156. f.push(vi);
  93157. if (ti !== FRONT)
  93158. b.push(ti !== BACK ? vi.clone() : vi);
  93159. if ((ti | tj) === SPANNING) {
  93160. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  93161. var v = vi.interpolate(vj, t);
  93162. f.push(v);
  93163. b.push(v.clone());
  93164. }
  93165. }
  93166. var poly;
  93167. if (f.length >= 3) {
  93168. poly = new Polygon(f, polygon.shared);
  93169. if (poly.plane)
  93170. front.push(poly);
  93171. }
  93172. if (b.length >= 3) {
  93173. poly = new Polygon(b, polygon.shared);
  93174. if (poly.plane)
  93175. back.push(poly);
  93176. }
  93177. break;
  93178. }
  93179. };
  93180. /**
  93181. * `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  93182. * point is on the plane
  93183. */
  93184. Plane.EPSILON = 1e-5;
  93185. return Plane;
  93186. }());
  93187. /**
  93188. * Represents a convex polygon. The vertices used to initialize a polygon must
  93189. * be coplanar and form a convex loop.
  93190. *
  93191. * Each convex polygon has a `shared` property, which is shared between all
  93192. * polygons that are clones of each other or were split from the same polygon.
  93193. * This can be used to define per-polygon properties (such as surface color)
  93194. */
  93195. var Polygon = /** @class */ (function () {
  93196. /**
  93197. * Initializes the polygon
  93198. * @param vertices The vertices of the polygon
  93199. * @param shared The properties shared across all polygons
  93200. */
  93201. function Polygon(vertices, shared) {
  93202. this.vertices = vertices;
  93203. this.shared = shared;
  93204. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  93205. }
  93206. /**
  93207. * Clones, or makes a deep copy, or the polygon
  93208. */
  93209. Polygon.prototype.clone = function () {
  93210. var vertices = this.vertices.map(function (v) { return v.clone(); });
  93211. return new Polygon(vertices, this.shared);
  93212. };
  93213. /**
  93214. * Flips the faces of the polygon
  93215. */
  93216. Polygon.prototype.flip = function () {
  93217. this.vertices.reverse().map(function (v) { v.flip(); });
  93218. this.plane.flip();
  93219. };
  93220. return Polygon;
  93221. }());
  93222. /**
  93223. * Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  93224. * by picking a polygon to split along. That polygon (and all other coplanar
  93225. * polygons) are added directly to that node and the other polygons are added to
  93226. * the front and/or back subtrees. This is not a leafy BSP tree since there is
  93227. * no distinction between internal and leaf nodes
  93228. */
  93229. var Node = /** @class */ (function () {
  93230. /**
  93231. * Initializes the node
  93232. * @param polygons A collection of polygons held in the node
  93233. */
  93234. function Node(polygons) {
  93235. this.plane = null;
  93236. this.front = null;
  93237. this.back = null;
  93238. this.polygons = new Array();
  93239. if (polygons) {
  93240. this.build(polygons);
  93241. }
  93242. }
  93243. /**
  93244. * Clones, or makes a deep copy, of the node
  93245. * @returns The cloned node
  93246. */
  93247. Node.prototype.clone = function () {
  93248. var node = new Node();
  93249. node.plane = this.plane && this.plane.clone();
  93250. node.front = this.front && this.front.clone();
  93251. node.back = this.back && this.back.clone();
  93252. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  93253. return node;
  93254. };
  93255. /**
  93256. * Convert solid space to empty space and empty space to solid space
  93257. */
  93258. Node.prototype.invert = function () {
  93259. for (var i = 0; i < this.polygons.length; i++) {
  93260. this.polygons[i].flip();
  93261. }
  93262. if (this.plane) {
  93263. this.plane.flip();
  93264. }
  93265. if (this.front) {
  93266. this.front.invert();
  93267. }
  93268. if (this.back) {
  93269. this.back.invert();
  93270. }
  93271. var temp = this.front;
  93272. this.front = this.back;
  93273. this.back = temp;
  93274. };
  93275. /**
  93276. * Recursively remove all polygons in `polygons` that are inside this BSP
  93277. * tree.
  93278. * @param polygons Polygons to remove from the BSP
  93279. * @returns Polygons clipped from the BSP
  93280. */
  93281. Node.prototype.clipPolygons = function (polygons) {
  93282. if (!this.plane)
  93283. return polygons.slice();
  93284. var front = new Array(), back = new Array();
  93285. for (var i = 0; i < polygons.length; i++) {
  93286. this.plane.splitPolygon(polygons[i], front, back, front, back);
  93287. }
  93288. if (this.front) {
  93289. front = this.front.clipPolygons(front);
  93290. }
  93291. if (this.back) {
  93292. back = this.back.clipPolygons(back);
  93293. }
  93294. else {
  93295. back = [];
  93296. }
  93297. return front.concat(back);
  93298. };
  93299. /**
  93300. * Remove all polygons in this BSP tree that are inside the other BSP tree
  93301. * `bsp`.
  93302. * @param bsp BSP containing polygons to remove from this BSP
  93303. */
  93304. Node.prototype.clipTo = function (bsp) {
  93305. this.polygons = bsp.clipPolygons(this.polygons);
  93306. if (this.front)
  93307. this.front.clipTo(bsp);
  93308. if (this.back)
  93309. this.back.clipTo(bsp);
  93310. };
  93311. /**
  93312. * Return a list of all polygons in this BSP tree
  93313. * @returns List of all polygons in this BSP tree
  93314. */
  93315. Node.prototype.allPolygons = function () {
  93316. var polygons = this.polygons.slice();
  93317. if (this.front)
  93318. polygons = polygons.concat(this.front.allPolygons());
  93319. if (this.back)
  93320. polygons = polygons.concat(this.back.allPolygons());
  93321. return polygons;
  93322. };
  93323. /**
  93324. * Build a BSP tree out of `polygons`. When called on an existing tree, the
  93325. * new polygons are filtered down to the bottom of the tree and become new
  93326. * nodes there. Each set of polygons is partitioned using the first polygon
  93327. * (no heuristic is used to pick a good split)
  93328. * @param polygons Polygons used to construct the BSP tree
  93329. */
  93330. Node.prototype.build = function (polygons) {
  93331. if (!polygons.length)
  93332. return;
  93333. if (!this.plane)
  93334. this.plane = polygons[0].plane.clone();
  93335. var front = new Array(), back = new Array();
  93336. for (var i = 0; i < polygons.length; i++) {
  93337. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  93338. }
  93339. if (front.length) {
  93340. if (!this.front)
  93341. this.front = new Node();
  93342. this.front.build(front);
  93343. }
  93344. if (back.length) {
  93345. if (!this.back)
  93346. this.back = new Node();
  93347. this.back.build(back);
  93348. }
  93349. };
  93350. return Node;
  93351. }());
  93352. /**
  93353. * Class for building Constructive Solid Geometry
  93354. */
  93355. var CSG = /** @class */ (function () {
  93356. function CSG() {
  93357. this.polygons = new Array();
  93358. }
  93359. /**
  93360. * Convert the BABYLON.Mesh to BABYLON.CSG
  93361. * @param mesh The BABYLON.Mesh to convert to BABYLON.CSG
  93362. * @returns A new BABYLON.CSG from the BABYLON.Mesh
  93363. */
  93364. CSG.FromMesh = function (mesh) {
  93365. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  93366. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  93367. if (mesh instanceof BABYLON.Mesh) {
  93368. mesh.computeWorldMatrix(true);
  93369. matrix = mesh.getWorldMatrix();
  93370. meshPosition = mesh.position.clone();
  93371. meshRotation = mesh.rotation.clone();
  93372. if (mesh.rotationQuaternion) {
  93373. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  93374. }
  93375. meshScaling = mesh.scaling.clone();
  93376. }
  93377. else {
  93378. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  93379. }
  93380. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  93381. var subMeshes = mesh.subMeshes;
  93382. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  93383. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  93384. vertices = [];
  93385. for (var j = 0; j < 3; j++) {
  93386. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  93387. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  93388. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  93389. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  93390. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  93391. vertex = new Vertex(position, normal, uv);
  93392. vertices.push(vertex);
  93393. }
  93394. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  93395. // To handle the case of degenerated triangle
  93396. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  93397. if (polygon.plane)
  93398. polygons.push(polygon);
  93399. }
  93400. }
  93401. var csg = CSG.FromPolygons(polygons);
  93402. csg.matrix = matrix;
  93403. csg.position = meshPosition;
  93404. csg.rotation = meshRotation;
  93405. csg.scaling = meshScaling;
  93406. csg.rotationQuaternion = meshRotationQuaternion;
  93407. currentCSGMeshId++;
  93408. return csg;
  93409. };
  93410. /**
  93411. * Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  93412. * @param polygons Polygons used to construct a BABYLON.CSG solid
  93413. */
  93414. CSG.FromPolygons = function (polygons) {
  93415. var csg = new CSG();
  93416. csg.polygons = polygons;
  93417. return csg;
  93418. };
  93419. /**
  93420. * Clones, or makes a deep copy, of the BABYLON.CSG
  93421. * @returns A new BABYLON.CSG
  93422. */
  93423. CSG.prototype.clone = function () {
  93424. var csg = new CSG();
  93425. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  93426. csg.copyTransformAttributes(this);
  93427. return csg;
  93428. };
  93429. /**
  93430. * Unions this CSG with another CSG
  93431. * @param csg The CSG to union against this CSG
  93432. * @returns The unioned CSG
  93433. */
  93434. CSG.prototype.union = function (csg) {
  93435. var a = new Node(this.clone().polygons);
  93436. var b = new Node(csg.clone().polygons);
  93437. a.clipTo(b);
  93438. b.clipTo(a);
  93439. b.invert();
  93440. b.clipTo(a);
  93441. b.invert();
  93442. a.build(b.allPolygons());
  93443. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93444. };
  93445. /**
  93446. * Unions this CSG with another CSG in place
  93447. * @param csg The CSG to union against this CSG
  93448. */
  93449. CSG.prototype.unionInPlace = function (csg) {
  93450. var a = new Node(this.polygons);
  93451. var b = new Node(csg.polygons);
  93452. a.clipTo(b);
  93453. b.clipTo(a);
  93454. b.invert();
  93455. b.clipTo(a);
  93456. b.invert();
  93457. a.build(b.allPolygons());
  93458. this.polygons = a.allPolygons();
  93459. };
  93460. /**
  93461. * Subtracts this CSG with another CSG
  93462. * @param csg The CSG to subtract against this CSG
  93463. * @returns A new BABYLON.CSG
  93464. */
  93465. CSG.prototype.subtract = function (csg) {
  93466. var a = new Node(this.clone().polygons);
  93467. var b = new Node(csg.clone().polygons);
  93468. a.invert();
  93469. a.clipTo(b);
  93470. b.clipTo(a);
  93471. b.invert();
  93472. b.clipTo(a);
  93473. b.invert();
  93474. a.build(b.allPolygons());
  93475. a.invert();
  93476. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93477. };
  93478. /**
  93479. * Subtracts this CSG with another CSG in place
  93480. * @param csg The CSG to subtact against this CSG
  93481. */
  93482. CSG.prototype.subtractInPlace = function (csg) {
  93483. var a = new Node(this.polygons);
  93484. var b = new Node(csg.polygons);
  93485. a.invert();
  93486. a.clipTo(b);
  93487. b.clipTo(a);
  93488. b.invert();
  93489. b.clipTo(a);
  93490. b.invert();
  93491. a.build(b.allPolygons());
  93492. a.invert();
  93493. this.polygons = a.allPolygons();
  93494. };
  93495. /**
  93496. * Intersect this CSG with another CSG
  93497. * @param csg The CSG to intersect against this CSG
  93498. * @returns A new BABYLON.CSG
  93499. */
  93500. CSG.prototype.intersect = function (csg) {
  93501. var a = new Node(this.clone().polygons);
  93502. var b = new Node(csg.clone().polygons);
  93503. a.invert();
  93504. b.clipTo(a);
  93505. b.invert();
  93506. a.clipTo(b);
  93507. b.clipTo(a);
  93508. a.build(b.allPolygons());
  93509. a.invert();
  93510. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  93511. };
  93512. /**
  93513. * Intersects this CSG with another CSG in place
  93514. * @param csg The CSG to intersect against this CSG
  93515. */
  93516. CSG.prototype.intersectInPlace = function (csg) {
  93517. var a = new Node(this.polygons);
  93518. var b = new Node(csg.polygons);
  93519. a.invert();
  93520. b.clipTo(a);
  93521. b.invert();
  93522. a.clipTo(b);
  93523. b.clipTo(a);
  93524. a.build(b.allPolygons());
  93525. a.invert();
  93526. this.polygons = a.allPolygons();
  93527. };
  93528. /**
  93529. * Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  93530. * not modified.
  93531. * @returns A new BABYLON.CSG solid with solid and empty space switched
  93532. */
  93533. CSG.prototype.inverse = function () {
  93534. var csg = this.clone();
  93535. csg.inverseInPlace();
  93536. return csg;
  93537. };
  93538. /**
  93539. * Inverses the BABYLON.CSG in place
  93540. */
  93541. CSG.prototype.inverseInPlace = function () {
  93542. this.polygons.map(function (p) { p.flip(); });
  93543. };
  93544. /**
  93545. * This is used to keep meshes transformations so they can be restored
  93546. * when we build back a Babylon Mesh
  93547. * NB : All CSG operations are performed in world coordinates
  93548. * @param csg The BABYLON.CSG to copy the transform attributes from
  93549. * @returns This BABYLON.CSG
  93550. */
  93551. CSG.prototype.copyTransformAttributes = function (csg) {
  93552. this.matrix = csg.matrix;
  93553. this.position = csg.position;
  93554. this.rotation = csg.rotation;
  93555. this.scaling = csg.scaling;
  93556. this.rotationQuaternion = csg.rotationQuaternion;
  93557. return this;
  93558. };
  93559. /**
  93560. * Build Raw mesh from CSG
  93561. * Coordinates here are in world space
  93562. * @param name The name of the mesh geometry
  93563. * @param scene The BABYLON.Scene
  93564. * @param keepSubMeshes Specifies if the submeshes should be kept
  93565. * @returns A new BABYLON.Mesh
  93566. */
  93567. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  93568. var matrix = this.matrix.clone();
  93569. matrix.invert();
  93570. 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;
  93571. if (keepSubMeshes) {
  93572. // Sort Polygons, since subMeshes are indices range
  93573. polygons.sort(function (a, b) {
  93574. if (a.shared.meshId === b.shared.meshId) {
  93575. return a.shared.subMeshId - b.shared.subMeshId;
  93576. }
  93577. else {
  93578. return a.shared.meshId - b.shared.meshId;
  93579. }
  93580. });
  93581. }
  93582. for (var i = 0, il = polygons.length; i < il; i++) {
  93583. polygon = polygons[i];
  93584. // Building SubMeshes
  93585. if (!subMesh_dict[polygon.shared.meshId]) {
  93586. subMesh_dict[polygon.shared.meshId] = {};
  93587. }
  93588. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  93589. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  93590. indexStart: +Infinity,
  93591. indexEnd: -Infinity,
  93592. materialIndex: polygon.shared.materialIndex
  93593. };
  93594. }
  93595. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  93596. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  93597. polygonIndices[0] = 0;
  93598. polygonIndices[1] = j - 1;
  93599. polygonIndices[2] = j;
  93600. for (var k = 0; k < 3; k++) {
  93601. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  93602. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  93603. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  93604. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  93605. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  93606. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  93607. // Check if 2 points can be merged
  93608. if (!(typeof vertex_idx !== 'undefined' &&
  93609. normals[vertex_idx * 3] === localNormal.x &&
  93610. normals[vertex_idx * 3 + 1] === localNormal.y &&
  93611. normals[vertex_idx * 3 + 2] === localNormal.z &&
  93612. uvs[vertex_idx * 2] === uv.x &&
  93613. uvs[vertex_idx * 2 + 1] === uv.y)) {
  93614. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  93615. uvs.push(uv.x, uv.y);
  93616. normals.push(normal.x, normal.y, normal.z);
  93617. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  93618. }
  93619. indices.push(vertex_idx);
  93620. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  93621. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  93622. currentIndex++;
  93623. }
  93624. }
  93625. }
  93626. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  93627. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  93628. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  93629. mesh.setIndices(indices, null);
  93630. if (keepSubMeshes) {
  93631. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  93632. var materialIndexOffset = 0, materialMaxIndex;
  93633. mesh.subMeshes = new Array();
  93634. for (var m in subMesh_dict) {
  93635. materialMaxIndex = -1;
  93636. for (var sm in subMesh_dict[m]) {
  93637. subMesh_obj = subMesh_dict[m][sm];
  93638. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  93639. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  93640. }
  93641. materialIndexOffset += ++materialMaxIndex;
  93642. }
  93643. }
  93644. return mesh;
  93645. };
  93646. /**
  93647. * Build Mesh from CSG taking material and transforms into account
  93648. * @param name The name of the BABYLON.Mesh
  93649. * @param material The material of the BABYLON.Mesh
  93650. * @param scene The BABYLON.Scene
  93651. * @param keepSubMeshes Specifies if submeshes should be kept
  93652. * @returns The new BABYLON.Mesh
  93653. */
  93654. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  93655. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  93656. mesh.material = material;
  93657. mesh.position.copyFrom(this.position);
  93658. mesh.rotation.copyFrom(this.rotation);
  93659. if (this.rotationQuaternion) {
  93660. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  93661. }
  93662. mesh.scaling.copyFrom(this.scaling);
  93663. mesh.computeWorldMatrix(true);
  93664. return mesh;
  93665. };
  93666. return CSG;
  93667. }());
  93668. BABYLON.CSG = CSG;
  93669. })(BABYLON || (BABYLON = {}));
  93670. //# sourceMappingURL=babylon.csg.js.map
  93671. var BABYLON;
  93672. (function (BABYLON) {
  93673. /**
  93674. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93675. * It controls one of the indiviual texture used in the effect.
  93676. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93677. */
  93678. var LensFlare = /** @class */ (function () {
  93679. /**
  93680. * Instantiates a new Lens Flare.
  93681. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93682. * It controls one of the indiviual texture used in the effect.
  93683. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93684. * @param size Define the size of the lens flare in the system (a floating value between 0 and 1)
  93685. * @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.
  93686. * @param color Define the lens color
  93687. * @param imgUrl Define the lens texture url
  93688. * @param system Define the `lensFlareSystem` this flare is part of
  93689. */
  93690. function LensFlare(
  93691. /**
  93692. * Define the size of the lens flare in the system (a floating value between 0 and 1)
  93693. */
  93694. size,
  93695. /**
  93696. * 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.
  93697. */
  93698. position, color, imgUrl, system) {
  93699. this.size = size;
  93700. this.position = position;
  93701. /**
  93702. * Define the alpha mode to render this particular lens.
  93703. */
  93704. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  93705. this.color = color || new BABYLON.Color3(1, 1, 1);
  93706. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  93707. this._system = system;
  93708. system.lensFlares.push(this);
  93709. }
  93710. /**
  93711. * Creates a new Lens Flare.
  93712. * This represents one of the lens effect in a `BABYLON.lensFlareSystem`.
  93713. * It controls one of the indiviual texture used in the effect.
  93714. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93715. * @param size Define the size of the lens flare (a floating value between 0 and 1)
  93716. * @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.
  93717. * @param color Define the lens color
  93718. * @param imgUrl Define the lens texture url
  93719. * @param system Define the `lensFlareSystem` this flare is part of
  93720. * @returns The newly created Lens Flare
  93721. */
  93722. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  93723. return new LensFlare(size, position, color, imgUrl, system);
  93724. };
  93725. /**
  93726. * Dispose and release the lens flare with its associated resources.
  93727. */
  93728. LensFlare.prototype.dispose = function () {
  93729. if (this.texture) {
  93730. this.texture.dispose();
  93731. }
  93732. // Remove from scene
  93733. var index = this._system.lensFlares.indexOf(this);
  93734. this._system.lensFlares.splice(index, 1);
  93735. };
  93736. ;
  93737. return LensFlare;
  93738. }());
  93739. BABYLON.LensFlare = LensFlare;
  93740. })(BABYLON || (BABYLON = {}));
  93741. //# sourceMappingURL=babylon.lensFlare.js.map
  93742. var BABYLON;
  93743. (function (BABYLON) {
  93744. // Adds the parser to the scene parsers.
  93745. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM, function (parsedData, scene, container, rootUrl) {
  93746. // Lens flares
  93747. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  93748. if (!container.lensFlareSystems) {
  93749. container.lensFlareSystems = new Array();
  93750. }
  93751. for (var index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  93752. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  93753. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  93754. container.lensFlareSystems.push(lf);
  93755. }
  93756. }
  93757. });
  93758. BABYLON.AbstractScene.prototype.getLensFlareSystemByName = function (name) {
  93759. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  93760. if (this.lensFlareSystems[index].name === name) {
  93761. return this.lensFlareSystems[index];
  93762. }
  93763. }
  93764. return null;
  93765. };
  93766. BABYLON.AbstractScene.prototype.getLensFlareSystemByID = function (id) {
  93767. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  93768. if (this.lensFlareSystems[index].id === id) {
  93769. return this.lensFlareSystems[index];
  93770. }
  93771. }
  93772. return null;
  93773. };
  93774. BABYLON.AbstractScene.prototype.removeLensFlareSystem = function (toRemove) {
  93775. var index = this.lensFlareSystems.indexOf(toRemove);
  93776. if (index !== -1) {
  93777. this.lensFlareSystems.splice(index, 1);
  93778. }
  93779. return index;
  93780. };
  93781. BABYLON.AbstractScene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  93782. this.lensFlareSystems.push(newLensFlareSystem);
  93783. };
  93784. /**
  93785. * Defines the lens flare scene component responsible to manage any lens flares
  93786. * in a given scene.
  93787. */
  93788. var LensFlareSystemSceneComponent = /** @class */ (function () {
  93789. /**
  93790. * Creates a new instance of the component for the given scene
  93791. * @param scene Defines the scene to register the component in
  93792. */
  93793. function LensFlareSystemSceneComponent(scene) {
  93794. /**
  93795. * The component name helpfull to identify the component in the list of scene components.
  93796. */
  93797. this.name = BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM;
  93798. this.scene = scene;
  93799. scene.lensFlareSystems = new Array();
  93800. }
  93801. /**
  93802. * Registers the component in a given scene
  93803. */
  93804. LensFlareSystemSceneComponent.prototype.register = function () {
  93805. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LENSFLARESYSTEM, this, this._draw);
  93806. };
  93807. /**
  93808. * Rebuilds the elements related to this component in case of
  93809. * context lost for instance.
  93810. */
  93811. LensFlareSystemSceneComponent.prototype.rebuild = function () {
  93812. // Nothing to do for lens flare
  93813. };
  93814. /**
  93815. * Adds all the element from the container to the scene
  93816. * @param container the container holding the elements
  93817. */
  93818. LensFlareSystemSceneComponent.prototype.addFromContainer = function (container) {
  93819. var _this = this;
  93820. if (!container.lensFlareSystems) {
  93821. return;
  93822. }
  93823. container.lensFlareSystems.forEach(function (o) {
  93824. _this.scene.addLensFlareSystem(o);
  93825. });
  93826. };
  93827. /**
  93828. * Removes all the elements in the container from the scene
  93829. * @param container contains the elements to remove
  93830. */
  93831. LensFlareSystemSceneComponent.prototype.removeFromContainer = function (container) {
  93832. var _this = this;
  93833. if (!container.lensFlareSystems) {
  93834. return;
  93835. }
  93836. container.lensFlareSystems.forEach(function (o) {
  93837. _this.scene.removeLensFlareSystem(o);
  93838. });
  93839. };
  93840. /**
  93841. * Serializes the component data to the specified json object
  93842. * @param serializationObject The object to serialize to
  93843. */
  93844. LensFlareSystemSceneComponent.prototype.serialize = function (serializationObject) {
  93845. // Lens flares
  93846. serializationObject.lensFlareSystems = [];
  93847. var lensFlareSystems = this.scene.lensFlareSystems;
  93848. for (var _i = 0, lensFlareSystems_1 = lensFlareSystems; _i < lensFlareSystems_1.length; _i++) {
  93849. var lensFlareSystem = lensFlareSystems_1[_i];
  93850. serializationObject.lensFlareSystems.push(lensFlareSystem.serialize());
  93851. }
  93852. };
  93853. /**
  93854. * Disposes the component and the associated ressources.
  93855. */
  93856. LensFlareSystemSceneComponent.prototype.dispose = function () {
  93857. var lensFlareSystems = this.scene.lensFlareSystems;
  93858. while (lensFlareSystems.length) {
  93859. lensFlareSystems[0].dispose();
  93860. }
  93861. };
  93862. LensFlareSystemSceneComponent.prototype._draw = function (camera) {
  93863. // Lens flares
  93864. if (this.scene.lensFlaresEnabled) {
  93865. var lensFlareSystems = this.scene.lensFlareSystems;
  93866. BABYLON.Tools.StartPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  93867. for (var _i = 0, lensFlareSystems_2 = lensFlareSystems; _i < lensFlareSystems_2.length; _i++) {
  93868. var lensFlareSystem = lensFlareSystems_2[_i];
  93869. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  93870. lensFlareSystem.render();
  93871. }
  93872. }
  93873. BABYLON.Tools.EndPerformanceCounter("Lens flares", lensFlareSystems.length > 0);
  93874. }
  93875. };
  93876. return LensFlareSystemSceneComponent;
  93877. }());
  93878. BABYLON.LensFlareSystemSceneComponent = LensFlareSystemSceneComponent;
  93879. })(BABYLON || (BABYLON = {}));
  93880. //# sourceMappingURL=babylon.lensFlareSystemSceneComponent.js.map
  93881. var BABYLON;
  93882. (function (BABYLON) {
  93883. /**
  93884. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  93885. * It is usually composed of several `BABYLON.lensFlare`.
  93886. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93887. */
  93888. var LensFlareSystem = /** @class */ (function () {
  93889. /**
  93890. * Instantiates a lens flare system.
  93891. * This represents a Lens Flare System or the shiny effect created by the light reflection on the camera lenses.
  93892. * It is usually composed of several `BABYLON.lensFlare`.
  93893. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  93894. * @param name Define the name of the lens flare system in the scene
  93895. * @param emitter Define the source (the emitter) of the lens flares (it can be a camera, a light or a mesh).
  93896. * @param scene Define the scene the lens flare system belongs to
  93897. */
  93898. function LensFlareSystem(
  93899. /**
  93900. * Define the name of the lens flare system
  93901. */
  93902. name, emitter, scene) {
  93903. this.name = name;
  93904. /**
  93905. * List of lens flares used in this system.
  93906. */
  93907. this.lensFlares = new Array();
  93908. /**
  93909. * Define a limit from the border the lens flare can be visible.
  93910. */
  93911. this.borderLimit = 300;
  93912. /**
  93913. * Define a viewport border we do not want to see the lens flare in.
  93914. */
  93915. this.viewportBorder = 0;
  93916. /**
  93917. * Restricts the rendering of the effect to only the camera rendering this layer mask.
  93918. */
  93919. this.layerMask = 0x0FFFFFFF;
  93920. this._vertexBuffers = {};
  93921. this._isEnabled = true;
  93922. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  93923. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LENSFLARESYSTEM);
  93924. if (!component) {
  93925. component = new BABYLON.LensFlareSystemSceneComponent(this._scene);
  93926. scene._addComponent(component);
  93927. }
  93928. this._emitter = emitter;
  93929. this.id = name;
  93930. scene.lensFlareSystems.push(this);
  93931. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  93932. var engine = scene.getEngine();
  93933. // VBO
  93934. var vertices = [];
  93935. vertices.push(1, 1);
  93936. vertices.push(-1, 1);
  93937. vertices.push(-1, -1);
  93938. vertices.push(1, -1);
  93939. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  93940. // Indices
  93941. var indices = [];
  93942. indices.push(0);
  93943. indices.push(1);
  93944. indices.push(2);
  93945. indices.push(0);
  93946. indices.push(2);
  93947. indices.push(3);
  93948. this._indexBuffer = engine.createIndexBuffer(indices);
  93949. // Effects
  93950. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  93951. }
  93952. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  93953. /**
  93954. * Define if the lens flare system is enabled.
  93955. */
  93956. get: function () {
  93957. return this._isEnabled;
  93958. },
  93959. set: function (value) {
  93960. this._isEnabled = value;
  93961. },
  93962. enumerable: true,
  93963. configurable: true
  93964. });
  93965. /**
  93966. * Get the scene the effects belongs to.
  93967. * @returns the scene holding the lens flare system
  93968. */
  93969. LensFlareSystem.prototype.getScene = function () {
  93970. return this._scene;
  93971. };
  93972. /**
  93973. * Get the emitter of the lens flare system.
  93974. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  93975. * @returns the emitter of the lens flare system
  93976. */
  93977. LensFlareSystem.prototype.getEmitter = function () {
  93978. return this._emitter;
  93979. };
  93980. /**
  93981. * Set the emitter of the lens flare system.
  93982. * It defines the source of the lens flares (it can be a camera, a light or a mesh).
  93983. * @param newEmitter Define the new emitter of the system
  93984. */
  93985. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  93986. this._emitter = newEmitter;
  93987. };
  93988. /**
  93989. * Get the lens flare system emitter position.
  93990. * The emitter defines the source of the lens flares (it can be a camera, a light or a mesh).
  93991. * @returns the position
  93992. */
  93993. LensFlareSystem.prototype.getEmitterPosition = function () {
  93994. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  93995. };
  93996. /**
  93997. * @hidden
  93998. */
  93999. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  94000. var position = this.getEmitterPosition();
  94001. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  94002. this._positionX = position.x;
  94003. this._positionY = position.y;
  94004. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  94005. if (this.viewportBorder > 0) {
  94006. globalViewport.x -= this.viewportBorder;
  94007. globalViewport.y -= this.viewportBorder;
  94008. globalViewport.width += this.viewportBorder * 2;
  94009. globalViewport.height += this.viewportBorder * 2;
  94010. position.x += this.viewportBorder;
  94011. position.y += this.viewportBorder;
  94012. this._positionX += this.viewportBorder;
  94013. this._positionY += this.viewportBorder;
  94014. }
  94015. if (position.z > 0) {
  94016. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  94017. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  94018. return true;
  94019. }
  94020. return true;
  94021. }
  94022. return false;
  94023. };
  94024. /** @hidden */
  94025. LensFlareSystem.prototype._isVisible = function () {
  94026. if (!this._isEnabled || !this._scene.activeCamera) {
  94027. return false;
  94028. }
  94029. var emitterPosition = this.getEmitterPosition();
  94030. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  94031. var distance = direction.length();
  94032. direction.normalize();
  94033. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  94034. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  94035. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  94036. };
  94037. /**
  94038. * @hidden
  94039. */
  94040. LensFlareSystem.prototype.render = function () {
  94041. if (!this._effect.isReady() || !this._scene.activeCamera)
  94042. return false;
  94043. var engine = this._scene.getEngine();
  94044. var viewport = this._scene.activeCamera.viewport;
  94045. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  94046. // Position
  94047. if (!this.computeEffectivePosition(globalViewport)) {
  94048. return false;
  94049. }
  94050. // Visibility
  94051. if (!this._isVisible()) {
  94052. return false;
  94053. }
  94054. // Intensity
  94055. var awayX;
  94056. var awayY;
  94057. if (this._positionX < this.borderLimit + globalViewport.x) {
  94058. awayX = this.borderLimit + globalViewport.x - this._positionX;
  94059. }
  94060. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  94061. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  94062. }
  94063. else {
  94064. awayX = 0;
  94065. }
  94066. if (this._positionY < this.borderLimit + globalViewport.y) {
  94067. awayY = this.borderLimit + globalViewport.y - this._positionY;
  94068. }
  94069. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  94070. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  94071. }
  94072. else {
  94073. awayY = 0;
  94074. }
  94075. var away = (awayX > awayY) ? awayX : awayY;
  94076. away -= this.viewportBorder;
  94077. if (away > this.borderLimit) {
  94078. away = this.borderLimit;
  94079. }
  94080. var intensity = 1.0 - (away / this.borderLimit);
  94081. if (intensity < 0) {
  94082. return false;
  94083. }
  94084. if (intensity > 1.0) {
  94085. intensity = 1.0;
  94086. }
  94087. if (this.viewportBorder > 0) {
  94088. globalViewport.x += this.viewportBorder;
  94089. globalViewport.y += this.viewportBorder;
  94090. globalViewport.width -= this.viewportBorder * 2;
  94091. globalViewport.height -= this.viewportBorder * 2;
  94092. this._positionX -= this.viewportBorder;
  94093. this._positionY -= this.viewportBorder;
  94094. }
  94095. // Position
  94096. var centerX = globalViewport.x + globalViewport.width / 2;
  94097. var centerY = globalViewport.y + globalViewport.height / 2;
  94098. var distX = centerX - this._positionX;
  94099. var distY = centerY - this._positionY;
  94100. // Effects
  94101. engine.enableEffect(this._effect);
  94102. engine.setState(false);
  94103. engine.setDepthBuffer(false);
  94104. // VBOs
  94105. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  94106. // Flares
  94107. for (var index = 0; index < this.lensFlares.length; index++) {
  94108. var flare = this.lensFlares[index];
  94109. engine.setAlphaMode(flare.alphaMode);
  94110. var x = centerX - (distX * flare.position);
  94111. var y = centerY - (distY * flare.position);
  94112. var cw = flare.size;
  94113. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  94114. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  94115. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  94116. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  94117. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  94118. // Texture
  94119. this._effect.setTexture("textureSampler", flare.texture);
  94120. // Color
  94121. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  94122. // Draw order
  94123. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94124. }
  94125. engine.setDepthBuffer(true);
  94126. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94127. return true;
  94128. };
  94129. /**
  94130. * Dispose and release the lens flare with its associated resources.
  94131. */
  94132. LensFlareSystem.prototype.dispose = function () {
  94133. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94134. if (vertexBuffer) {
  94135. vertexBuffer.dispose();
  94136. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94137. }
  94138. if (this._indexBuffer) {
  94139. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94140. this._indexBuffer = null;
  94141. }
  94142. while (this.lensFlares.length) {
  94143. this.lensFlares[0].dispose();
  94144. }
  94145. // Remove from scene
  94146. var index = this._scene.lensFlareSystems.indexOf(this);
  94147. this._scene.lensFlareSystems.splice(index, 1);
  94148. };
  94149. /**
  94150. * Parse a lens flare system from a JSON repressentation
  94151. * @param parsedLensFlareSystem Define the JSON to parse
  94152. * @param scene Define the scene the parsed system should be instantiated in
  94153. * @param rootUrl Define the rootUrl of the load sequence to easily find a load relative dependencies such as textures
  94154. * @returns the parsed system
  94155. */
  94156. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  94157. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  94158. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  94159. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  94160. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  94161. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  94162. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  94163. var parsedFlare = parsedLensFlareSystem.flares[index];
  94164. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  94165. }
  94166. return lensFlareSystem;
  94167. };
  94168. /**
  94169. * Serialize the current Lens Flare System into a JSON representation.
  94170. * @returns the serialized JSON
  94171. */
  94172. LensFlareSystem.prototype.serialize = function () {
  94173. var serializationObject = {};
  94174. serializationObject.id = this.id;
  94175. serializationObject.name = this.name;
  94176. serializationObject.emitterId = this.getEmitter().id;
  94177. serializationObject.borderLimit = this.borderLimit;
  94178. serializationObject.flares = [];
  94179. for (var index = 0; index < this.lensFlares.length; index++) {
  94180. var flare = this.lensFlares[index];
  94181. serializationObject.flares.push({
  94182. size: flare.size,
  94183. position: flare.position,
  94184. color: flare.color.asArray(),
  94185. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  94186. });
  94187. }
  94188. return serializationObject;
  94189. };
  94190. return LensFlareSystem;
  94191. }());
  94192. BABYLON.LensFlareSystem = LensFlareSystem;
  94193. })(BABYLON || (BABYLON = {}));
  94194. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  94195. var BABYLON;
  94196. (function (BABYLON) {
  94197. /**
  94198. * This is a holder class for the physics joint created by the physics plugin
  94199. * It holds a set of functions to control the underlying joint
  94200. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94201. */
  94202. var PhysicsJoint = /** @class */ (function () {
  94203. /**
  94204. * Initializes the physics joint
  94205. * @param type The type of the physics joint
  94206. * @param jointData The data for the physics joint
  94207. */
  94208. function PhysicsJoint(
  94209. /**
  94210. * The type of the physics joint
  94211. */
  94212. type,
  94213. /**
  94214. * The data for the physics joint
  94215. */
  94216. jointData) {
  94217. this.type = type;
  94218. this.jointData = jointData;
  94219. jointData.nativeParams = jointData.nativeParams || {};
  94220. }
  94221. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  94222. /**
  94223. * Gets the physics joint
  94224. */
  94225. get: function () {
  94226. return this._physicsJoint;
  94227. },
  94228. /**
  94229. * Sets the physics joint
  94230. */
  94231. set: function (newJoint) {
  94232. if (this._physicsJoint) {
  94233. //remove from the wolrd
  94234. }
  94235. this._physicsJoint = newJoint;
  94236. },
  94237. enumerable: true,
  94238. configurable: true
  94239. });
  94240. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  94241. /**
  94242. * Sets the physics plugin
  94243. */
  94244. set: function (physicsPlugin) {
  94245. this._physicsPlugin = physicsPlugin;
  94246. },
  94247. enumerable: true,
  94248. configurable: true
  94249. });
  94250. /**
  94251. * Execute a function that is physics-plugin specific.
  94252. * @param {Function} func the function that will be executed.
  94253. * It accepts two parameters: the physics world and the physics joint
  94254. */
  94255. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  94256. func(this._physicsPlugin.world, this._physicsJoint);
  94257. };
  94258. //TODO check if the native joints are the same
  94259. //Joint Types
  94260. /**
  94261. * Distance-Joint type
  94262. */
  94263. PhysicsJoint.DistanceJoint = 0;
  94264. /**
  94265. * Hinge-Joint type
  94266. */
  94267. PhysicsJoint.HingeJoint = 1;
  94268. /**
  94269. * Ball-and-Socket joint type
  94270. */
  94271. PhysicsJoint.BallAndSocketJoint = 2;
  94272. /**
  94273. * Wheel-Joint type
  94274. */
  94275. PhysicsJoint.WheelJoint = 3;
  94276. /**
  94277. * Slider-Joint type
  94278. */
  94279. PhysicsJoint.SliderJoint = 4;
  94280. //OIMO
  94281. /**
  94282. * Prismatic-Joint type
  94283. */
  94284. PhysicsJoint.PrismaticJoint = 5;
  94285. //
  94286. /**
  94287. * Universal-Joint type
  94288. * ENERGY FTW! (compare with this - @see http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  94289. */
  94290. PhysicsJoint.UniversalJoint = 6;
  94291. /**
  94292. * Hinge-Joint 2 type
  94293. */
  94294. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  94295. //Cannon
  94296. /**
  94297. * Point to Point Joint type. Similar to a Ball-Joint. Different in parameters
  94298. */
  94299. PhysicsJoint.PointToPointJoint = 8;
  94300. //Cannon only at the moment
  94301. /**
  94302. * Spring-Joint type
  94303. */
  94304. PhysicsJoint.SpringJoint = 9;
  94305. /**
  94306. * Lock-Joint type
  94307. */
  94308. PhysicsJoint.LockJoint = 10;
  94309. return PhysicsJoint;
  94310. }());
  94311. BABYLON.PhysicsJoint = PhysicsJoint;
  94312. /**
  94313. * A class representing a physics distance joint
  94314. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94315. */
  94316. var DistanceJoint = /** @class */ (function (_super) {
  94317. __extends(DistanceJoint, _super);
  94318. /**
  94319. *
  94320. * @param jointData The data for the Distance-Joint
  94321. */
  94322. function DistanceJoint(jointData) {
  94323. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  94324. }
  94325. /**
  94326. * Update the predefined distance.
  94327. * @param maxDistance The maximum preferred distance
  94328. * @param minDistance The minimum preferred distance
  94329. */
  94330. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  94331. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  94332. };
  94333. return DistanceJoint;
  94334. }(PhysicsJoint));
  94335. BABYLON.DistanceJoint = DistanceJoint;
  94336. /**
  94337. * Represents a Motor-Enabled Joint
  94338. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94339. */
  94340. var MotorEnabledJoint = /** @class */ (function (_super) {
  94341. __extends(MotorEnabledJoint, _super);
  94342. /**
  94343. * Initializes the Motor-Enabled Joint
  94344. * @param type The type of the joint
  94345. * @param jointData The physica joint data for the joint
  94346. */
  94347. function MotorEnabledJoint(type, jointData) {
  94348. return _super.call(this, type, jointData) || this;
  94349. }
  94350. /**
  94351. * Set the motor values.
  94352. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94353. * @param force the force to apply
  94354. * @param maxForce max force for this motor.
  94355. */
  94356. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  94357. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94358. };
  94359. /**
  94360. * Set the motor's limits.
  94361. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94362. * @param upperLimit The upper limit of the motor
  94363. * @param lowerLimit The lower limit of the motor
  94364. */
  94365. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94366. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94367. };
  94368. return MotorEnabledJoint;
  94369. }(PhysicsJoint));
  94370. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  94371. /**
  94372. * This class represents a single physics Hinge-Joint
  94373. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94374. */
  94375. var HingeJoint = /** @class */ (function (_super) {
  94376. __extends(HingeJoint, _super);
  94377. /**
  94378. * Initializes the Hinge-Joint
  94379. * @param jointData The joint data for the Hinge-Joint
  94380. */
  94381. function HingeJoint(jointData) {
  94382. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  94383. }
  94384. /**
  94385. * Set the motor values.
  94386. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94387. * @param {number} force the force to apply
  94388. * @param {number} maxForce max force for this motor.
  94389. */
  94390. HingeJoint.prototype.setMotor = function (force, maxForce) {
  94391. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  94392. };
  94393. /**
  94394. * Set the motor's limits.
  94395. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94396. * @param upperLimit The upper limit of the motor
  94397. * @param lowerLimit The lower limit of the motor
  94398. */
  94399. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  94400. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  94401. };
  94402. return HingeJoint;
  94403. }(MotorEnabledJoint));
  94404. BABYLON.HingeJoint = HingeJoint;
  94405. /**
  94406. * This class represents a dual hinge physics joint (same as wheel joint)
  94407. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94408. */
  94409. var Hinge2Joint = /** @class */ (function (_super) {
  94410. __extends(Hinge2Joint, _super);
  94411. /**
  94412. * Initializes the Hinge2-Joint
  94413. * @param jointData The joint data for the Hinge2-Joint
  94414. */
  94415. function Hinge2Joint(jointData) {
  94416. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  94417. }
  94418. /**
  94419. * Set the motor values.
  94420. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94421. * @param {number} force the force to apply
  94422. * @param {number} maxForce max force for this motor.
  94423. * @param {motorIndex} the motor's index, 0 or 1.
  94424. */
  94425. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  94426. if (motorIndex === void 0) { motorIndex = 0; }
  94427. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  94428. };
  94429. /**
  94430. * Set the motor limits.
  94431. * Attention, this function is plugin specific. Engines won't react 100% the same.
  94432. * @param {number} upperLimit the upper limit
  94433. * @param {number} lowerLimit lower limit
  94434. * @param {motorIndex} the motor's index, 0 or 1.
  94435. */
  94436. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  94437. if (motorIndex === void 0) { motorIndex = 0; }
  94438. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  94439. };
  94440. return Hinge2Joint;
  94441. }(MotorEnabledJoint));
  94442. BABYLON.Hinge2Joint = Hinge2Joint;
  94443. })(BABYLON || (BABYLON = {}));
  94444. //# sourceMappingURL=babylon.physicsJoint.js.map
  94445. var BABYLON;
  94446. (function (BABYLON) {
  94447. /**
  94448. * Represents a physics imposter
  94449. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  94450. */
  94451. var PhysicsImpostor = /** @class */ (function () {
  94452. /**
  94453. * Initializes the physics imposter
  94454. * @param object The physics-enabled object used as the physics imposter
  94455. * @param type The type of the physics imposter
  94456. * @param _options The options for the physics imposter
  94457. * @param _scene The Babylon scene
  94458. */
  94459. function PhysicsImpostor(
  94460. /**
  94461. * The physics-enabled object used as the physics imposter
  94462. */
  94463. object,
  94464. /**
  94465. * The type of the physics imposter
  94466. */
  94467. type, _options, _scene) {
  94468. if (_options === void 0) { _options = { mass: 0 }; }
  94469. var _this = this;
  94470. this.object = object;
  94471. this.type = type;
  94472. this._options = _options;
  94473. this._scene = _scene;
  94474. this._bodyUpdateRequired = false;
  94475. this._onBeforePhysicsStepCallbacks = new Array();
  94476. this._onAfterPhysicsStepCallbacks = new Array();
  94477. this._onPhysicsCollideCallbacks = [];
  94478. this._deltaPosition = BABYLON.Vector3.Zero();
  94479. this._isDisposed = false;
  94480. //temp variables for parent rotation calculations
  94481. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  94482. this._tmpQuat = new BABYLON.Quaternion();
  94483. this._tmpQuat2 = new BABYLON.Quaternion();
  94484. /**
  94485. * this function is executed by the physics engine.
  94486. */
  94487. this.beforeStep = function () {
  94488. if (!_this._physicsEngine) {
  94489. return;
  94490. }
  94491. _this.object.translate(_this._deltaPosition, -1);
  94492. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  94493. _this.object.computeWorldMatrix(false);
  94494. if (_this.object.parent && _this.object.rotationQuaternion) {
  94495. _this.getParentsRotation();
  94496. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  94497. }
  94498. else {
  94499. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  94500. }
  94501. if (!_this._options.disableBidirectionalTransformation) {
  94502. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  94503. }
  94504. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  94505. func(_this);
  94506. });
  94507. };
  94508. /**
  94509. * this function is executed by the physics engine
  94510. */
  94511. this.afterStep = function () {
  94512. if (!_this._physicsEngine) {
  94513. return;
  94514. }
  94515. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  94516. func(_this);
  94517. });
  94518. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  94519. // object has now its world rotation. needs to be converted to local.
  94520. if (_this.object.parent && _this.object.rotationQuaternion) {
  94521. _this.getParentsRotation();
  94522. _this._tmpQuat.conjugateInPlace();
  94523. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  94524. }
  94525. // take the position set and make it the absolute position of this object.
  94526. _this.object.setAbsolutePosition(_this.object.position);
  94527. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  94528. _this.object.translate(_this._deltaPosition, 1);
  94529. };
  94530. /**
  94531. * Legacy collision detection event support
  94532. */
  94533. this.onCollideEvent = null;
  94534. /**
  94535. * event and body object due to cannon's event-based architecture.
  94536. */
  94537. this.onCollide = function (e) {
  94538. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  94539. return;
  94540. }
  94541. if (!_this._physicsEngine) {
  94542. return;
  94543. }
  94544. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  94545. if (otherImpostor) {
  94546. // Legacy collision detection event support
  94547. if (_this.onCollideEvent) {
  94548. _this.onCollideEvent(_this, otherImpostor);
  94549. }
  94550. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  94551. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  94552. }).forEach(function (obj) {
  94553. obj.callback(_this, otherImpostor);
  94554. });
  94555. }
  94556. };
  94557. //sanity check!
  94558. if (!this.object) {
  94559. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  94560. return;
  94561. }
  94562. //legacy support for old syntax.
  94563. if (!this._scene && object.getScene) {
  94564. this._scene = object.getScene();
  94565. }
  94566. if (!this._scene) {
  94567. return;
  94568. }
  94569. this._physicsEngine = this._scene.getPhysicsEngine();
  94570. if (!this._physicsEngine) {
  94571. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  94572. }
  94573. else {
  94574. //set the object's quaternion, if not set
  94575. if (!this.object.rotationQuaternion) {
  94576. if (this.object.rotation) {
  94577. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  94578. }
  94579. else {
  94580. this.object.rotationQuaternion = new BABYLON.Quaternion();
  94581. }
  94582. }
  94583. //default options params
  94584. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  94585. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  94586. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  94587. this._joints = [];
  94588. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  94589. if (!this.object.parent || this._options.ignoreParent) {
  94590. this._init();
  94591. }
  94592. else if (this.object.parent.physicsImpostor) {
  94593. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  94594. }
  94595. }
  94596. }
  94597. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  94598. /**
  94599. * Specifies if the physics imposter is disposed
  94600. */
  94601. get: function () {
  94602. return this._isDisposed;
  94603. },
  94604. enumerable: true,
  94605. configurable: true
  94606. });
  94607. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  94608. /**
  94609. * Gets the mass of the physics imposter
  94610. */
  94611. get: function () {
  94612. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  94613. },
  94614. set: function (value) {
  94615. this.setMass(value);
  94616. },
  94617. enumerable: true,
  94618. configurable: true
  94619. });
  94620. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  94621. /**
  94622. * Gets the coefficient of friction
  94623. */
  94624. get: function () {
  94625. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  94626. },
  94627. /**
  94628. * Sets the coefficient of friction
  94629. */
  94630. set: function (value) {
  94631. if (!this._physicsEngine) {
  94632. return;
  94633. }
  94634. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  94635. },
  94636. enumerable: true,
  94637. configurable: true
  94638. });
  94639. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  94640. /**
  94641. * Gets the coefficient of restitution
  94642. */
  94643. get: function () {
  94644. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  94645. },
  94646. /**
  94647. * Sets the coefficient of restitution
  94648. */
  94649. set: function (value) {
  94650. if (!this._physicsEngine) {
  94651. return;
  94652. }
  94653. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  94654. },
  94655. enumerable: true,
  94656. configurable: true
  94657. });
  94658. /**
  94659. * This function will completly initialize this impostor.
  94660. * It will create a new body - but only if this mesh has no parent.
  94661. * If it has, this impostor will not be used other than to define the impostor
  94662. * of the child mesh.
  94663. * @hidden
  94664. */
  94665. PhysicsImpostor.prototype._init = function () {
  94666. if (!this._physicsEngine) {
  94667. return;
  94668. }
  94669. this._physicsEngine.removeImpostor(this);
  94670. this.physicsBody = null;
  94671. this._parent = this._parent || this._getPhysicsParent();
  94672. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  94673. this._physicsEngine.addImpostor(this);
  94674. }
  94675. };
  94676. PhysicsImpostor.prototype._getPhysicsParent = function () {
  94677. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  94678. var parentMesh = this.object.parent;
  94679. return parentMesh.physicsImpostor;
  94680. }
  94681. return null;
  94682. };
  94683. /**
  94684. * Should a new body be generated.
  94685. * @returns boolean specifying if body initialization is required
  94686. */
  94687. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  94688. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  94689. };
  94690. /**
  94691. * Sets the updated scaling
  94692. * @param updated Specifies if the scaling is updated
  94693. */
  94694. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  94695. this.forceUpdate();
  94696. };
  94697. /**
  94698. * Force a regeneration of this or the parent's impostor's body.
  94699. * Use under cautious - This will remove all joints already implemented.
  94700. */
  94701. PhysicsImpostor.prototype.forceUpdate = function () {
  94702. this._init();
  94703. if (this.parent && !this._options.ignoreParent) {
  94704. this.parent.forceUpdate();
  94705. }
  94706. };
  94707. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  94708. /*public get mesh(): AbstractMesh {
  94709. return this._mesh;
  94710. }*/
  94711. /**
  94712. * Gets the body that holds this impostor. Either its own, or its parent.
  94713. */
  94714. get: function () {
  94715. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  94716. },
  94717. /**
  94718. * Set the physics body. Used mainly by the physics engine/plugin
  94719. */
  94720. set: function (physicsBody) {
  94721. if (this._physicsBody && this._physicsEngine) {
  94722. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  94723. }
  94724. this._physicsBody = physicsBody;
  94725. this.resetUpdateFlags();
  94726. },
  94727. enumerable: true,
  94728. configurable: true
  94729. });
  94730. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  94731. /**
  94732. * Get the parent of the physics imposter
  94733. * @returns Physics imposter or null
  94734. */
  94735. get: function () {
  94736. return !this._options.ignoreParent && this._parent ? this._parent : null;
  94737. },
  94738. /**
  94739. * Sets the parent of the physics imposter
  94740. */
  94741. set: function (value) {
  94742. this._parent = value;
  94743. },
  94744. enumerable: true,
  94745. configurable: true
  94746. });
  94747. /**
  94748. * Resets the update flags
  94749. */
  94750. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  94751. this._bodyUpdateRequired = false;
  94752. };
  94753. /**
  94754. * Gets the object extend size
  94755. * @returns the object extend size
  94756. */
  94757. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  94758. if (this.object.getBoundingInfo) {
  94759. var q = this.object.rotationQuaternion;
  94760. //reset rotation
  94761. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  94762. //calculate the world matrix with no rotation
  94763. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  94764. var boundingInfo = this.object.getBoundingInfo();
  94765. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  94766. //bring back the rotation
  94767. this.object.rotationQuaternion = q;
  94768. //calculate the world matrix with the new rotation
  94769. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  94770. return size;
  94771. }
  94772. else {
  94773. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  94774. }
  94775. };
  94776. /**
  94777. * Gets the object center
  94778. * @returns The object center
  94779. */
  94780. PhysicsImpostor.prototype.getObjectCenter = function () {
  94781. if (this.object.getBoundingInfo) {
  94782. var boundingInfo = this.object.getBoundingInfo();
  94783. return boundingInfo.boundingBox.centerWorld;
  94784. }
  94785. else {
  94786. return this.object.position;
  94787. }
  94788. };
  94789. /**
  94790. * Get a specific parametes from the options parameter
  94791. * @param paramName The object parameter name
  94792. * @returns The object parameter
  94793. */
  94794. PhysicsImpostor.prototype.getParam = function (paramName) {
  94795. return this._options[paramName];
  94796. };
  94797. /**
  94798. * Sets a specific parameter in the options given to the physics plugin
  94799. * @param paramName The parameter name
  94800. * @param value The value of the parameter
  94801. */
  94802. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  94803. this._options[paramName] = value;
  94804. this._bodyUpdateRequired = true;
  94805. };
  94806. /**
  94807. * Specifically change the body's mass option. Won't recreate the physics body object
  94808. * @param mass The mass of the physics imposter
  94809. */
  94810. PhysicsImpostor.prototype.setMass = function (mass) {
  94811. if (this.getParam("mass") !== mass) {
  94812. this.setParam("mass", mass);
  94813. }
  94814. if (this._physicsEngine) {
  94815. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  94816. }
  94817. };
  94818. /**
  94819. * Gets the linear velocity
  94820. * @returns linear velocity or null
  94821. */
  94822. PhysicsImpostor.prototype.getLinearVelocity = function () {
  94823. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  94824. };
  94825. /**
  94826. * Sets the linear velocity
  94827. * @param velocity linear velocity or null
  94828. */
  94829. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  94830. if (this._physicsEngine) {
  94831. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  94832. }
  94833. };
  94834. /**
  94835. * Gets the angular velocity
  94836. * @returns angular velocity or null
  94837. */
  94838. PhysicsImpostor.prototype.getAngularVelocity = function () {
  94839. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  94840. };
  94841. /**
  94842. * Sets the angular velocity
  94843. * @param velocity The velocity or null
  94844. */
  94845. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  94846. if (this._physicsEngine) {
  94847. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  94848. }
  94849. };
  94850. /**
  94851. * Execute a function with the physics plugin native code
  94852. * Provide a function the will have two variables - the world object and the physics body object
  94853. * @param func The function to execute with the physics plugin native code
  94854. */
  94855. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  94856. if (this._physicsEngine) {
  94857. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  94858. }
  94859. };
  94860. /**
  94861. * Register a function that will be executed before the physics world is stepping forward
  94862. * @param func The function to execute before the physics world is stepped forward
  94863. */
  94864. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  94865. this._onBeforePhysicsStepCallbacks.push(func);
  94866. };
  94867. /**
  94868. * Unregister a function that will be executed before the physics world is stepping forward
  94869. * @param func The function to execute before the physics world is stepped forward
  94870. */
  94871. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  94872. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  94873. if (index > -1) {
  94874. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  94875. }
  94876. else {
  94877. BABYLON.Tools.Warn("Function to remove was not found");
  94878. }
  94879. };
  94880. /**
  94881. * Register a function that will be executed after the physics step
  94882. * @param func The function to execute after physics step
  94883. */
  94884. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  94885. this._onAfterPhysicsStepCallbacks.push(func);
  94886. };
  94887. /**
  94888. * Unregisters a function that will be executed after the physics step
  94889. * @param func The function to execute after physics step
  94890. */
  94891. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  94892. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  94893. if (index > -1) {
  94894. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  94895. }
  94896. else {
  94897. BABYLON.Tools.Warn("Function to remove was not found");
  94898. }
  94899. };
  94900. /**
  94901. * register a function that will be executed when this impostor collides against a different body
  94902. * @param collideAgainst Physics imposter, or array of physics imposters to collide against
  94903. * @param func Callback that is executed on collision
  94904. */
  94905. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  94906. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  94907. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  94908. };
  94909. /**
  94910. * Unregisters the physics imposter on contact
  94911. * @param collideAgainst The physics object to collide against
  94912. * @param func Callback to execute on collision
  94913. */
  94914. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  94915. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  94916. var index = -1;
  94917. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  94918. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  94919. // chcek the arrays match
  94920. var sameList = cbDef.otherImpostors.every(function (impostor) {
  94921. return collidedAgainstList.indexOf(impostor) > -1;
  94922. });
  94923. if (sameList) {
  94924. index = idx;
  94925. }
  94926. return sameList;
  94927. }
  94928. return false;
  94929. });
  94930. if (found) {
  94931. this._onPhysicsCollideCallbacks.splice(index, 1);
  94932. }
  94933. else {
  94934. BABYLON.Tools.Warn("Function to remove was not found");
  94935. }
  94936. };
  94937. /**
  94938. * Get the parent rotation
  94939. * @returns The parent rotation
  94940. */
  94941. PhysicsImpostor.prototype.getParentsRotation = function () {
  94942. var parent = this.object.parent;
  94943. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  94944. while (parent) {
  94945. if (parent.rotationQuaternion) {
  94946. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  94947. }
  94948. else {
  94949. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  94950. }
  94951. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  94952. parent = parent.parent;
  94953. }
  94954. return this._tmpQuat;
  94955. };
  94956. /**
  94957. * Apply a force
  94958. * @param force The force to apply
  94959. * @param contactPoint The contact point for the force
  94960. * @returns The physics imposter
  94961. */
  94962. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  94963. if (this._physicsEngine) {
  94964. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  94965. }
  94966. return this;
  94967. };
  94968. /**
  94969. * Apply an impulse
  94970. * @param force The impulse force
  94971. * @param contactPoint The contact point for the impulse force
  94972. * @returns The physics imposter
  94973. */
  94974. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  94975. if (this._physicsEngine) {
  94976. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  94977. }
  94978. return this;
  94979. };
  94980. /**
  94981. * A help function to create a joint
  94982. * @param otherImpostor A physics imposter used to create a joint
  94983. * @param jointType The type of joint
  94984. * @param jointData The data for the joint
  94985. * @returns The physics imposter
  94986. */
  94987. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  94988. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  94989. this.addJoint(otherImpostor, joint);
  94990. return this;
  94991. };
  94992. /**
  94993. * Add a joint to this impostor with a different impostor
  94994. * @param otherImpostor A physics imposter used to add a joint
  94995. * @param joint The joint to add
  94996. * @returns The physics imposter
  94997. */
  94998. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  94999. this._joints.push({
  95000. otherImpostor: otherImpostor,
  95001. joint: joint
  95002. });
  95003. if (this._physicsEngine) {
  95004. this._physicsEngine.addJoint(this, otherImpostor, joint);
  95005. }
  95006. return this;
  95007. };
  95008. /**
  95009. * Will keep this body still, in a sleep mode.
  95010. * @returns the physics imposter
  95011. */
  95012. PhysicsImpostor.prototype.sleep = function () {
  95013. if (this._physicsEngine) {
  95014. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  95015. }
  95016. return this;
  95017. };
  95018. /**
  95019. * Wake the body up.
  95020. * @returns The physics imposter
  95021. */
  95022. PhysicsImpostor.prototype.wakeUp = function () {
  95023. if (this._physicsEngine) {
  95024. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  95025. }
  95026. return this;
  95027. };
  95028. /**
  95029. * Clones the physics imposter
  95030. * @param newObject The physics imposter clones to this physics-enabled object
  95031. * @returns A nullable physics imposter
  95032. */
  95033. PhysicsImpostor.prototype.clone = function (newObject) {
  95034. if (!newObject)
  95035. return null;
  95036. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  95037. };
  95038. /**
  95039. * Disposes the physics imposter
  95040. */
  95041. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  95042. var _this = this;
  95043. //no dispose if no physics engine is available.
  95044. if (!this._physicsEngine) {
  95045. return;
  95046. }
  95047. this._joints.forEach(function (j) {
  95048. if (_this._physicsEngine) {
  95049. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  95050. }
  95051. });
  95052. //dispose the physics body
  95053. this._physicsEngine.removeImpostor(this);
  95054. if (this.parent) {
  95055. this.parent.forceUpdate();
  95056. }
  95057. else {
  95058. /*this._object.getChildMeshes().forEach(function(mesh) {
  95059. if (mesh.physicsImpostor) {
  95060. if (disposeChildren) {
  95061. mesh.physicsImpostor.dispose();
  95062. mesh.physicsImpostor = null;
  95063. }
  95064. }
  95065. })*/
  95066. }
  95067. this._isDisposed = true;
  95068. };
  95069. /**
  95070. * Sets the delta position
  95071. * @param position The delta position amount
  95072. */
  95073. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  95074. this._deltaPosition.copyFrom(position);
  95075. };
  95076. /**
  95077. * Sets the delta rotation
  95078. * @param rotation The delta rotation amount
  95079. */
  95080. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  95081. if (!this._deltaRotation) {
  95082. this._deltaRotation = new BABYLON.Quaternion();
  95083. }
  95084. this._deltaRotation.copyFrom(rotation);
  95085. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  95086. };
  95087. /**
  95088. * Gets the box size of the physics imposter and stores the result in the input parameter
  95089. * @param result Stores the box size
  95090. * @returns The physics imposter
  95091. */
  95092. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  95093. if (this._physicsEngine) {
  95094. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  95095. }
  95096. return this;
  95097. };
  95098. /**
  95099. * Gets the radius of the physics imposter
  95100. * @returns Radius of the physics imposter
  95101. */
  95102. PhysicsImpostor.prototype.getRadius = function () {
  95103. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  95104. };
  95105. /**
  95106. * Sync a bone with this impostor
  95107. * @param bone The bone to sync to the impostor.
  95108. * @param boneMesh The mesh that the bone is influencing.
  95109. * @param jointPivot The pivot of the joint / bone in local space.
  95110. * @param distToJoint Optional distance from the impostor to the joint.
  95111. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95112. */
  95113. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  95114. var tempVec = PhysicsImpostor._tmpVecs[0];
  95115. var mesh = this.object;
  95116. if (mesh.rotationQuaternion) {
  95117. if (adjustRotation) {
  95118. var tempQuat = PhysicsImpostor._tmpQuat;
  95119. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  95120. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  95121. }
  95122. else {
  95123. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  95124. }
  95125. }
  95126. tempVec.x = 0;
  95127. tempVec.y = 0;
  95128. tempVec.z = 0;
  95129. if (jointPivot) {
  95130. tempVec.x = jointPivot.x;
  95131. tempVec.y = jointPivot.y;
  95132. tempVec.z = jointPivot.z;
  95133. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  95134. if (distToJoint === undefined || distToJoint === null) {
  95135. distToJoint = jointPivot.length();
  95136. }
  95137. tempVec.x *= distToJoint;
  95138. tempVec.y *= distToJoint;
  95139. tempVec.z *= distToJoint;
  95140. }
  95141. if (bone.getParent()) {
  95142. tempVec.addInPlace(mesh.getAbsolutePosition());
  95143. bone.setAbsolutePosition(tempVec, boneMesh);
  95144. }
  95145. else {
  95146. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  95147. boneMesh.position.x -= tempVec.x;
  95148. boneMesh.position.y -= tempVec.y;
  95149. boneMesh.position.z -= tempVec.z;
  95150. }
  95151. };
  95152. /**
  95153. * Sync impostor to a bone
  95154. * @param bone The bone that the impostor will be synced to.
  95155. * @param boneMesh The mesh that the bone is influencing.
  95156. * @param jointPivot The pivot of the joint / bone in local space.
  95157. * @param distToJoint Optional distance from the impostor to the joint.
  95158. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  95159. * @param boneAxis Optional vector3 axis the bone is aligned with
  95160. */
  95161. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  95162. var mesh = this.object;
  95163. if (mesh.rotationQuaternion) {
  95164. if (adjustRotation) {
  95165. var tempQuat = PhysicsImpostor._tmpQuat;
  95166. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  95167. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  95168. }
  95169. else {
  95170. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  95171. }
  95172. }
  95173. var pos = PhysicsImpostor._tmpVecs[0];
  95174. var boneDir = PhysicsImpostor._tmpVecs[1];
  95175. if (!boneAxis) {
  95176. boneAxis = PhysicsImpostor._tmpVecs[2];
  95177. boneAxis.x = 0;
  95178. boneAxis.y = 1;
  95179. boneAxis.z = 0;
  95180. }
  95181. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  95182. bone.getAbsolutePositionToRef(boneMesh, pos);
  95183. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  95184. distToJoint = jointPivot.length();
  95185. }
  95186. if (distToJoint !== undefined && distToJoint !== null) {
  95187. pos.x += boneDir.x * distToJoint;
  95188. pos.y += boneDir.y * distToJoint;
  95189. pos.z += boneDir.z * distToJoint;
  95190. }
  95191. mesh.setAbsolutePosition(pos);
  95192. };
  95193. /**
  95194. * The default object size of the imposter
  95195. */
  95196. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  95197. /**
  95198. * The identity quaternion of the imposter
  95199. */
  95200. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  95201. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  95202. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  95203. //Impostor types
  95204. /**
  95205. * No-Imposter type
  95206. */
  95207. PhysicsImpostor.NoImpostor = 0;
  95208. /**
  95209. * Sphere-Imposter type
  95210. */
  95211. PhysicsImpostor.SphereImpostor = 1;
  95212. /**
  95213. * Box-Imposter type
  95214. */
  95215. PhysicsImpostor.BoxImpostor = 2;
  95216. /**
  95217. * Plane-Imposter type
  95218. */
  95219. PhysicsImpostor.PlaneImpostor = 3;
  95220. /**
  95221. * Mesh-imposter type
  95222. */
  95223. PhysicsImpostor.MeshImpostor = 4;
  95224. /**
  95225. * Cylinder-Imposter type
  95226. */
  95227. PhysicsImpostor.CylinderImpostor = 7;
  95228. /**
  95229. * Particle-Imposter type
  95230. */
  95231. PhysicsImpostor.ParticleImpostor = 8;
  95232. /**
  95233. * Heightmap-Imposter type
  95234. */
  95235. PhysicsImpostor.HeightmapImpostor = 9;
  95236. return PhysicsImpostor;
  95237. }());
  95238. BABYLON.PhysicsImpostor = PhysicsImpostor;
  95239. })(BABYLON || (BABYLON = {}));
  95240. //# sourceMappingURL=babylon.physicsImpostor.js.map
  95241. var BABYLON;
  95242. (function (BABYLON) {
  95243. /**
  95244. * Class used to control physics engine
  95245. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  95246. */
  95247. var PhysicsEngine = /** @class */ (function () {
  95248. /**
  95249. * Creates a new Physics Engine
  95250. * @param gravity defines the gravity vector used by the simulation
  95251. * @param _physicsPlugin defines the plugin to use (CannonJS by default)
  95252. */
  95253. function PhysicsEngine(gravity, _physicsPlugin) {
  95254. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  95255. this._physicsPlugin = _physicsPlugin;
  95256. this._impostors = [];
  95257. this._joints = [];
  95258. if (!this._physicsPlugin.isSupported()) {
  95259. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  95260. + "Please make sure it is included.");
  95261. }
  95262. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  95263. this.setGravity(gravity);
  95264. this.setTimeStep();
  95265. }
  95266. /**
  95267. * Sets the gravity vector used by the simulation
  95268. * @param gravity defines the gravity vector to use
  95269. */
  95270. PhysicsEngine.prototype.setGravity = function (gravity) {
  95271. this.gravity = gravity;
  95272. this._physicsPlugin.setGravity(this.gravity);
  95273. };
  95274. /**
  95275. * Set the time step of the physics engine.
  95276. * Default is 1/60.
  95277. * To slow it down, enter 1/600 for example.
  95278. * To speed it up, 1/30
  95279. * @param newTimeStep defines the new timestep to apply to this world.
  95280. */
  95281. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  95282. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  95283. this._physicsPlugin.setTimeStep(newTimeStep);
  95284. };
  95285. /**
  95286. * Get the time step of the physics engine.
  95287. * @returns the current time step
  95288. */
  95289. PhysicsEngine.prototype.getTimeStep = function () {
  95290. return this._physicsPlugin.getTimeStep();
  95291. };
  95292. /**
  95293. * Release all resources
  95294. */
  95295. PhysicsEngine.prototype.dispose = function () {
  95296. this._impostors.forEach(function (impostor) {
  95297. impostor.dispose();
  95298. });
  95299. this._physicsPlugin.dispose();
  95300. };
  95301. /**
  95302. * Gets the name of the current physics plugin
  95303. * @returns the name of the plugin
  95304. */
  95305. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  95306. return this._physicsPlugin.name;
  95307. };
  95308. /**
  95309. * Adding a new impostor for the impostor tracking.
  95310. * This will be done by the impostor itself.
  95311. * @param impostor the impostor to add
  95312. */
  95313. PhysicsEngine.prototype.addImpostor = function (impostor) {
  95314. impostor.uniqueId = this._impostors.push(impostor);
  95315. //if no parent, generate the body
  95316. if (!impostor.parent) {
  95317. this._physicsPlugin.generatePhysicsBody(impostor);
  95318. }
  95319. };
  95320. /**
  95321. * Remove an impostor from the engine.
  95322. * This impostor and its mesh will not longer be updated by the physics engine.
  95323. * @param impostor the impostor to remove
  95324. */
  95325. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  95326. var index = this._impostors.indexOf(impostor);
  95327. if (index > -1) {
  95328. var removed = this._impostors.splice(index, 1);
  95329. //Is it needed?
  95330. if (removed.length) {
  95331. //this will also remove it from the world.
  95332. removed[0].physicsBody = null;
  95333. }
  95334. }
  95335. };
  95336. /**
  95337. * Add a joint to the physics engine
  95338. * @param mainImpostor defines the main impostor to which the joint is added.
  95339. * @param connectedImpostor defines the impostor that is connected to the main impostor using this joint
  95340. * @param joint defines the joint that will connect both impostors.
  95341. */
  95342. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  95343. var impostorJoint = {
  95344. mainImpostor: mainImpostor,
  95345. connectedImpostor: connectedImpostor,
  95346. joint: joint
  95347. };
  95348. joint.physicsPlugin = this._physicsPlugin;
  95349. this._joints.push(impostorJoint);
  95350. this._physicsPlugin.generateJoint(impostorJoint);
  95351. };
  95352. /**
  95353. * Removes a joint from the simulation
  95354. * @param mainImpostor defines the impostor used with the joint
  95355. * @param connectedImpostor defines the other impostor connected to the main one by the joint
  95356. * @param joint defines the joint to remove
  95357. */
  95358. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  95359. var matchingJoints = this._joints.filter(function (impostorJoint) {
  95360. return (impostorJoint.connectedImpostor === connectedImpostor
  95361. && impostorJoint.joint === joint
  95362. && impostorJoint.mainImpostor === mainImpostor);
  95363. });
  95364. if (matchingJoints.length) {
  95365. this._physicsPlugin.removeJoint(matchingJoints[0]);
  95366. //TODO remove it from the list as well
  95367. }
  95368. };
  95369. /**
  95370. * Called by the scene. No need to call it.
  95371. * @param delta defines the timespam between frames
  95372. */
  95373. PhysicsEngine.prototype._step = function (delta) {
  95374. var _this = this;
  95375. //check if any mesh has no body / requires an update
  95376. this._impostors.forEach(function (impostor) {
  95377. if (impostor.isBodyInitRequired()) {
  95378. _this._physicsPlugin.generatePhysicsBody(impostor);
  95379. }
  95380. });
  95381. if (delta > 0.1) {
  95382. delta = 0.1;
  95383. }
  95384. else if (delta <= 0) {
  95385. delta = 1.0 / 60.0;
  95386. }
  95387. this._physicsPlugin.executeStep(delta, this._impostors);
  95388. };
  95389. /**
  95390. * Gets the current plugin used to run the simulation
  95391. * @returns current plugin
  95392. */
  95393. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  95394. return this._physicsPlugin;
  95395. };
  95396. /**
  95397. * Gets the list of physic impostors
  95398. * @returns an array of PhysicsImpostor
  95399. */
  95400. PhysicsEngine.prototype.getImpostors = function () {
  95401. return this._impostors;
  95402. };
  95403. /**
  95404. * Gets the impostor for a physics enabled object
  95405. * @param object defines the object impersonated by the impostor
  95406. * @returns the PhysicsImpostor or null if not found
  95407. */
  95408. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  95409. for (var i = 0; i < this._impostors.length; ++i) {
  95410. if (this._impostors[i].object === object) {
  95411. return this._impostors[i];
  95412. }
  95413. }
  95414. return null;
  95415. };
  95416. /**
  95417. * Gets the impostor for a physics body object
  95418. * @param body defines physics body used by the impostor
  95419. * @returns the PhysicsImpostor or null if not found
  95420. */
  95421. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  95422. for (var i = 0; i < this._impostors.length; ++i) {
  95423. if (this._impostors[i].physicsBody === body) {
  95424. return this._impostors[i];
  95425. }
  95426. }
  95427. return null;
  95428. };
  95429. /**
  95430. * Global value used to control the smallest number supported by the simulation
  95431. */
  95432. PhysicsEngine.Epsilon = 0.001;
  95433. return PhysicsEngine;
  95434. }());
  95435. BABYLON.PhysicsEngine = PhysicsEngine;
  95436. })(BABYLON || (BABYLON = {}));
  95437. //# sourceMappingURL=babylon.physicsEngine.js.map
  95438. var BABYLON;
  95439. (function (BABYLON) {
  95440. /**
  95441. * A helper for physics simulations
  95442. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95443. */
  95444. var PhysicsHelper = /** @class */ (function () {
  95445. /**
  95446. * Initializes the Physics helper
  95447. * @param scene Babylon.js scene
  95448. */
  95449. function PhysicsHelper(scene) {
  95450. this._scene = scene;
  95451. this._physicsEngine = this._scene.getPhysicsEngine();
  95452. if (!this._physicsEngine) {
  95453. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  95454. }
  95455. }
  95456. /**
  95457. * Applies a radial explosion impulse
  95458. * @param origin the origin of the explosion
  95459. * @param radius the explosion radius
  95460. * @param strength the explosion strength
  95461. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95462. * @returns A physics radial explosion event, or null
  95463. */
  95464. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  95465. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95466. if (!this._physicsEngine) {
  95467. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  95468. return null;
  95469. }
  95470. var impostors = this._physicsEngine.getImpostors();
  95471. if (impostors.length === 0) {
  95472. return null;
  95473. }
  95474. var event = new PhysicsRadialExplosionEvent(this._scene);
  95475. impostors.forEach(function (impostor) {
  95476. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95477. if (!impostorForceAndContactPoint) {
  95478. return;
  95479. }
  95480. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95481. });
  95482. event.dispose(false);
  95483. return event;
  95484. };
  95485. /**
  95486. * Applies a radial explosion force
  95487. * @param origin the origin of the explosion
  95488. * @param radius the explosion radius
  95489. * @param strength the explosion strength
  95490. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95491. * @returns A physics radial explosion event, or null
  95492. */
  95493. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  95494. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95495. if (!this._physicsEngine) {
  95496. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95497. return null;
  95498. }
  95499. var impostors = this._physicsEngine.getImpostors();
  95500. if (impostors.length === 0) {
  95501. return null;
  95502. }
  95503. var event = new PhysicsRadialExplosionEvent(this._scene);
  95504. impostors.forEach(function (impostor) {
  95505. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  95506. if (!impostorForceAndContactPoint) {
  95507. return;
  95508. }
  95509. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95510. });
  95511. event.dispose(false);
  95512. return event;
  95513. };
  95514. /**
  95515. * Creates a gravitational field
  95516. * @param origin the origin of the explosion
  95517. * @param radius the explosion radius
  95518. * @param strength the explosion strength
  95519. * @param falloff possible options: Constant & Linear. Defaults to Constant
  95520. * @returns A physics gravitational field event, or null
  95521. */
  95522. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  95523. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95524. if (!this._physicsEngine) {
  95525. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95526. return null;
  95527. }
  95528. var impostors = this._physicsEngine.getImpostors();
  95529. if (impostors.length === 0) {
  95530. return null;
  95531. }
  95532. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  95533. event.dispose(false);
  95534. return event;
  95535. };
  95536. /**
  95537. * Creates a physics updraft event
  95538. * @param origin the origin of the updraft
  95539. * @param radius the radius of the updraft
  95540. * @param strength the strength of the updraft
  95541. * @param height the height of the updraft
  95542. * @param updraftMode possible options: Center & Perpendicular. Defaults to Center
  95543. * @returns A physics updraft event, or null
  95544. */
  95545. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  95546. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  95547. if (!this._physicsEngine) {
  95548. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95549. return null;
  95550. }
  95551. if (this._physicsEngine.getImpostors().length === 0) {
  95552. return null;
  95553. }
  95554. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  95555. event.dispose(false);
  95556. return event;
  95557. };
  95558. /**
  95559. * Creates a physics vortex event
  95560. * @param origin the of the vortex
  95561. * @param radius the radius of the vortex
  95562. * @param strength the strength of the vortex
  95563. * @param height the height of the vortex
  95564. * @returns a Physics vortex event, or null
  95565. * A physics vortex event or null
  95566. */
  95567. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  95568. if (!this._physicsEngine) {
  95569. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  95570. return null;
  95571. }
  95572. if (this._physicsEngine.getImpostors().length === 0) {
  95573. return null;
  95574. }
  95575. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  95576. event.dispose(false);
  95577. return event;
  95578. };
  95579. return PhysicsHelper;
  95580. }());
  95581. BABYLON.PhysicsHelper = PhysicsHelper;
  95582. /**
  95583. * Represents a physics radial explosion event
  95584. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95585. */
  95586. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  95587. /**
  95588. * Initializes a radial explosioin event
  95589. * @param scene BabylonJS scene
  95590. */
  95591. function PhysicsRadialExplosionEvent(scene) {
  95592. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  95593. this._rays = [];
  95594. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  95595. this._scene = scene;
  95596. }
  95597. /**
  95598. * Returns the data related to the radial explosion event (sphere & rays).
  95599. * @returns The radial explosion event data
  95600. */
  95601. PhysicsRadialExplosionEvent.prototype.getData = function () {
  95602. this._dataFetched = true;
  95603. return {
  95604. sphere: this._sphere,
  95605. rays: this._rays,
  95606. };
  95607. };
  95608. /**
  95609. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  95610. * @param impostor A physics imposter
  95611. * @param origin the origin of the explosion
  95612. * @param radius the explosion radius
  95613. * @param strength the explosion strength
  95614. * @param falloff possible options: Constant & Linear
  95615. * @returns {Nullable<PhysicsForceAndContactPoint>} A physics force and contact point, or null
  95616. */
  95617. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  95618. if (impostor.mass === 0) {
  95619. return null;
  95620. }
  95621. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  95622. return null;
  95623. }
  95624. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95625. return null;
  95626. }
  95627. var impostorObjectCenter = impostor.getObjectCenter();
  95628. var direction = impostorObjectCenter.subtract(origin);
  95629. var ray = new BABYLON.Ray(origin, direction, radius);
  95630. this._rays.push(ray);
  95631. var hit = ray.intersectsMesh(impostor.object);
  95632. var contactPoint = hit.pickedPoint;
  95633. if (!contactPoint) {
  95634. return null;
  95635. }
  95636. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  95637. if (distanceFromOrigin > radius) {
  95638. return null;
  95639. }
  95640. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  95641. ? strength
  95642. : strength * (1 - (distanceFromOrigin / radius));
  95643. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95644. return { force: force, contactPoint: contactPoint };
  95645. };
  95646. /**
  95647. * Disposes the sphere.
  95648. * @param force Specifies if the sphere should be disposed by force
  95649. */
  95650. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  95651. var _this = this;
  95652. if (force === void 0) { force = true; }
  95653. if (force) {
  95654. this._sphere.dispose();
  95655. }
  95656. else {
  95657. setTimeout(function () {
  95658. if (!_this._dataFetched) {
  95659. _this._sphere.dispose();
  95660. }
  95661. }, 0);
  95662. }
  95663. };
  95664. /*** Helpers ***/
  95665. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  95666. if (!this._sphere) {
  95667. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  95668. this._sphere.isVisible = false;
  95669. }
  95670. };
  95671. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  95672. var impostorObject = impostor.object;
  95673. this._prepareSphere();
  95674. this._sphere.position = origin;
  95675. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  95676. this._sphere._updateBoundingInfo();
  95677. this._sphere.computeWorldMatrix(true);
  95678. return this._sphere.intersectsMesh(impostorObject, true);
  95679. };
  95680. return PhysicsRadialExplosionEvent;
  95681. }());
  95682. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  95683. /**
  95684. * Represents a gravitational field event
  95685. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95686. */
  95687. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  95688. /**
  95689. * Initializes the physics gravitational field event
  95690. * @param physicsHelper A physics helper
  95691. * @param scene BabylonJS scene
  95692. * @param origin The origin position of the gravitational field event
  95693. * @param radius The radius of the gravitational field event
  95694. * @param strength The strength of the gravitational field event
  95695. * @param falloff The falloff for the gravitational field event
  95696. */
  95697. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  95698. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  95699. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95700. this._physicsHelper = physicsHelper;
  95701. this._scene = scene;
  95702. this._origin = origin;
  95703. this._radius = radius;
  95704. this._strength = strength;
  95705. this._falloff = falloff;
  95706. this._tickCallback = this._tick.bind(this);
  95707. }
  95708. /**
  95709. * Returns the data related to the gravitational field event (sphere).
  95710. * @returns A gravitational field event
  95711. */
  95712. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  95713. this._dataFetched = true;
  95714. return {
  95715. sphere: this._sphere,
  95716. };
  95717. };
  95718. /**
  95719. * Enables the gravitational field.
  95720. */
  95721. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  95722. this._tickCallback.call(this);
  95723. this._scene.registerBeforeRender(this._tickCallback);
  95724. };
  95725. /**
  95726. * Disables the gravitational field.
  95727. */
  95728. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  95729. this._scene.unregisterBeforeRender(this._tickCallback);
  95730. };
  95731. /**
  95732. * Disposes the sphere.
  95733. * @param force The force to dispose from the gravitational field event
  95734. */
  95735. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  95736. var _this = this;
  95737. if (force === void 0) { force = true; }
  95738. if (force) {
  95739. this._sphere.dispose();
  95740. }
  95741. else {
  95742. setTimeout(function () {
  95743. if (!_this._dataFetched) {
  95744. _this._sphere.dispose();
  95745. }
  95746. }, 0);
  95747. }
  95748. };
  95749. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  95750. // Since the params won't change, we fetch the event only once
  95751. if (this._sphere) {
  95752. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  95753. }
  95754. else {
  95755. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  95756. if (radialExplosionEvent) {
  95757. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  95758. }
  95759. }
  95760. };
  95761. return PhysicsGravitationalFieldEvent;
  95762. }());
  95763. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  95764. /**
  95765. * Represents a physics updraft event
  95766. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95767. */
  95768. var PhysicsUpdraftEvent = /** @class */ (function () {
  95769. /**
  95770. * Initializes the physics updraft event
  95771. * @param _scene BabylonJS scene
  95772. * @param _origin The origin position of the updraft
  95773. * @param _radius The radius of the updraft
  95774. * @param _strength The strength of the updraft
  95775. * @param _height The height of the updraft
  95776. * @param _updraftMode The mode of the updraft
  95777. */
  95778. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  95779. this._scene = _scene;
  95780. this._origin = _origin;
  95781. this._radius = _radius;
  95782. this._strength = _strength;
  95783. this._height = _height;
  95784. this._updraftMode = _updraftMode;
  95785. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  95786. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  95787. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  95788. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95789. this._physicsEngine = this._scene.getPhysicsEngine();
  95790. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  95791. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  95792. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  95793. this._originDirection = this._origin.subtract(this._originTop).normalize();
  95794. }
  95795. this._tickCallback = this._tick.bind(this);
  95796. }
  95797. /**
  95798. * Returns the data related to the updraft event (cylinder).
  95799. * @returns A physics updraft event
  95800. */
  95801. PhysicsUpdraftEvent.prototype.getData = function () {
  95802. this._dataFetched = true;
  95803. return {
  95804. cylinder: this._cylinder,
  95805. };
  95806. };
  95807. /**
  95808. * Enables the updraft.
  95809. */
  95810. PhysicsUpdraftEvent.prototype.enable = function () {
  95811. this._tickCallback.call(this);
  95812. this._scene.registerBeforeRender(this._tickCallback);
  95813. };
  95814. /**
  95815. * Disables the cortex.
  95816. */
  95817. PhysicsUpdraftEvent.prototype.disable = function () {
  95818. this._scene.unregisterBeforeRender(this._tickCallback);
  95819. };
  95820. /**
  95821. * Disposes the sphere.
  95822. * @param force Specifies if the updraft should be disposed by force
  95823. */
  95824. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  95825. var _this = this;
  95826. if (force === void 0) { force = true; }
  95827. if (force) {
  95828. this._cylinder.dispose();
  95829. }
  95830. else {
  95831. setTimeout(function () {
  95832. if (!_this._dataFetched) {
  95833. _this._cylinder.dispose();
  95834. }
  95835. }, 0);
  95836. }
  95837. };
  95838. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  95839. if (impostor.mass === 0) {
  95840. return null;
  95841. }
  95842. if (!this._intersectsWithCylinder(impostor)) {
  95843. return null;
  95844. }
  95845. var impostorObjectCenter = impostor.getObjectCenter();
  95846. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  95847. var direction = this._originDirection;
  95848. }
  95849. else {
  95850. var direction = impostorObjectCenter.subtract(this._originTop);
  95851. }
  95852. var multiplier = this._strength * -1;
  95853. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  95854. return { force: force, contactPoint: impostorObjectCenter };
  95855. };
  95856. PhysicsUpdraftEvent.prototype._tick = function () {
  95857. var _this = this;
  95858. this._physicsEngine.getImpostors().forEach(function (impostor) {
  95859. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  95860. if (!impostorForceAndContactPoint) {
  95861. return;
  95862. }
  95863. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  95864. });
  95865. };
  95866. /*** Helpers ***/
  95867. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  95868. if (!this._cylinder) {
  95869. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  95870. height: this._height,
  95871. diameter: this._radius * 2,
  95872. }, this._scene);
  95873. this._cylinder.isVisible = false;
  95874. }
  95875. };
  95876. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  95877. var impostorObject = impostor.object;
  95878. this._prepareCylinder();
  95879. this._cylinder.position = this._cylinderPosition;
  95880. return this._cylinder.intersectsMesh(impostorObject, true);
  95881. };
  95882. return PhysicsUpdraftEvent;
  95883. }());
  95884. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  95885. /**
  95886. * Represents a physics vortex event
  95887. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  95888. */
  95889. var PhysicsVortexEvent = /** @class */ (function () {
  95890. /**
  95891. * Initializes the physics vortex event
  95892. * @param _scene The BabylonJS scene
  95893. * @param _origin The origin position of the vortex
  95894. * @param _radius The radius of the vortex
  95895. * @param _strength The strength of the vortex
  95896. * @param _height The height of the vortex
  95897. */
  95898. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  95899. this._scene = _scene;
  95900. this._origin = _origin;
  95901. this._radius = _radius;
  95902. this._strength = _strength;
  95903. this._height = _height;
  95904. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  95905. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  95906. this._updraftMultiplier = 0.02;
  95907. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  95908. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  95909. this._physicsEngine = this._scene.getPhysicsEngine();
  95910. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  95911. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  95912. this._tickCallback = this._tick.bind(this);
  95913. }
  95914. /**
  95915. * Returns the data related to the vortex event (cylinder).
  95916. * @returns The physics vortex event data
  95917. */
  95918. PhysicsVortexEvent.prototype.getData = function () {
  95919. this._dataFetched = true;
  95920. return {
  95921. cylinder: this._cylinder,
  95922. };
  95923. };
  95924. /**
  95925. * Enables the vortex.
  95926. */
  95927. PhysicsVortexEvent.prototype.enable = function () {
  95928. this._tickCallback.call(this);
  95929. this._scene.registerBeforeRender(this._tickCallback);
  95930. };
  95931. /**
  95932. * Disables the cortex.
  95933. */
  95934. PhysicsVortexEvent.prototype.disable = function () {
  95935. this._scene.unregisterBeforeRender(this._tickCallback);
  95936. };
  95937. /**
  95938. * Disposes the sphere.
  95939. * @param force
  95940. */
  95941. PhysicsVortexEvent.prototype.dispose = function (force) {
  95942. var _this = this;
  95943. if (force === void 0) { force = true; }
  95944. if (force) {
  95945. this._cylinder.dispose();
  95946. }
  95947. else {
  95948. setTimeout(function () {
  95949. if (!_this._dataFetched) {
  95950. _this._cylinder.dispose();
  95951. }
  95952. }, 0);
  95953. }
  95954. };
  95955. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  95956. if (impostor.mass === 0) {
  95957. return null;
  95958. }
  95959. if (!this._intersectsWithCylinder(impostor)) {
  95960. return null;
  95961. }
  95962. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  95963. return null;
  95964. }
  95965. var impostorObjectCenter = impostor.getObjectCenter();
  95966. 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)
  95967. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  95968. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  95969. var hit = ray.intersectsMesh(impostor.object);
  95970. var contactPoint = hit.pickedPoint;
  95971. if (!contactPoint) {
  95972. return null;
  95973. }
  95974. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  95975. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  95976. var directionToOrigin = contactPoint.normalize();
  95977. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  95978. directionToOrigin = directionToOrigin.negate();
  95979. }
  95980. // TODO: find a more physically based solution
  95981. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  95982. var forceX = directionToOrigin.x * this._strength / 8;
  95983. var forceY = directionToOrigin.y * this._updraftMultiplier;
  95984. var forceZ = directionToOrigin.z * this._strength / 8;
  95985. }
  95986. else {
  95987. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  95988. var forceY = this._originTop.y * this._updraftMultiplier;
  95989. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  95990. }
  95991. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  95992. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  95993. return { force: force, contactPoint: impostorObjectCenter };
  95994. };
  95995. PhysicsVortexEvent.prototype._tick = function () {
  95996. var _this = this;
  95997. this._physicsEngine.getImpostors().forEach(function (impostor) {
  95998. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  95999. if (!impostorForceAndContactPoint) {
  96000. return;
  96001. }
  96002. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  96003. });
  96004. };
  96005. /*** Helpers ***/
  96006. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  96007. if (!this._cylinder) {
  96008. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  96009. height: this._height,
  96010. diameter: this._radius * 2,
  96011. }, this._scene);
  96012. this._cylinder.isVisible = false;
  96013. }
  96014. };
  96015. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  96016. var impostorObject = impostor.object;
  96017. this._prepareCylinder();
  96018. this._cylinder.position = this._cylinderPosition;
  96019. return this._cylinder.intersectsMesh(impostorObject, true);
  96020. };
  96021. return PhysicsVortexEvent;
  96022. }());
  96023. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  96024. /**
  96025. * The strenght of the force in correspondence to the distance of the affected object
  96026. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96027. */
  96028. var PhysicsRadialImpulseFalloff;
  96029. (function (PhysicsRadialImpulseFalloff) {
  96030. /** Defines that impulse is constant in strength across it's whole radius */
  96031. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  96032. /** DEfines that impulse gets weaker if it's further from the origin */
  96033. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  96034. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  96035. /**
  96036. * The strength of the force in correspondence to the distance of the affected object
  96037. * @see https://doc.babylonjs.com/how_to/using_the_physics_engine
  96038. */
  96039. var PhysicsUpdraftMode;
  96040. (function (PhysicsUpdraftMode) {
  96041. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  96042. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  96043. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  96044. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  96045. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  96046. })(BABYLON || (BABYLON = {}));
  96047. //# sourceMappingURL=babylon.physicsHelper.js.map
  96048. var BABYLON;
  96049. (function (BABYLON) {
  96050. /** @hidden */
  96051. var CannonJSPlugin = /** @class */ (function () {
  96052. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  96053. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  96054. if (iterations === void 0) { iterations = 10; }
  96055. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  96056. this.name = "CannonJSPlugin";
  96057. this._physicsMaterials = new Array();
  96058. this._fixedTimeStep = 1 / 60;
  96059. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  96060. this.BJSCANNON = CANNON;
  96061. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  96062. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  96063. this._tmpPosition = BABYLON.Vector3.Zero();
  96064. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  96065. this._tmpUnityRotation = new BABYLON.Quaternion();
  96066. if (!this.isSupported()) {
  96067. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  96068. return;
  96069. }
  96070. this._extendNamespace();
  96071. this.world = new this.BJSCANNON.World();
  96072. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  96073. this.world.solver.iterations = iterations;
  96074. }
  96075. CannonJSPlugin.prototype.setGravity = function (gravity) {
  96076. this.world.gravity.copy(gravity);
  96077. };
  96078. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  96079. this._fixedTimeStep = timeStep;
  96080. };
  96081. CannonJSPlugin.prototype.getTimeStep = function () {
  96082. return this._fixedTimeStep;
  96083. };
  96084. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  96085. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  96086. };
  96087. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96088. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96089. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96090. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  96091. };
  96092. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96093. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  96094. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  96095. impostor.physicsBody.applyForce(impulse, worldPoint);
  96096. };
  96097. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96098. //parent-child relationship. Does this impostor has a parent impostor?
  96099. if (impostor.parent) {
  96100. if (impostor.physicsBody) {
  96101. this.removePhysicsBody(impostor);
  96102. //TODO is that needed?
  96103. impostor.forceUpdate();
  96104. }
  96105. return;
  96106. }
  96107. //should a new body be created for this impostor?
  96108. if (impostor.isBodyInitRequired()) {
  96109. var shape = this._createShape(impostor);
  96110. //unregister events, if body is being changed
  96111. var oldBody = impostor.physicsBody;
  96112. if (oldBody) {
  96113. this.removePhysicsBody(impostor);
  96114. }
  96115. //create the body and material
  96116. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  96117. var bodyCreationObject = {
  96118. mass: impostor.getParam("mass"),
  96119. material: material
  96120. };
  96121. // A simple extend, in case native options were used.
  96122. var nativeOptions = impostor.getParam("nativeOptions");
  96123. for (var key in nativeOptions) {
  96124. if (nativeOptions.hasOwnProperty(key)) {
  96125. bodyCreationObject[key] = nativeOptions[key];
  96126. }
  96127. }
  96128. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  96129. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  96130. this.world.addEventListener("preStep", impostor.beforeStep);
  96131. this.world.addEventListener("postStep", impostor.afterStep);
  96132. impostor.physicsBody.addShape(shape);
  96133. this.world.add(impostor.physicsBody);
  96134. //try to keep the body moving in the right direction by taking old properties.
  96135. //Should be tested!
  96136. if (oldBody) {
  96137. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  96138. impostor.physicsBody[param].copy(oldBody[param]);
  96139. });
  96140. }
  96141. this._processChildMeshes(impostor);
  96142. }
  96143. //now update the body's transformation
  96144. this._updatePhysicsBodyTransformation(impostor);
  96145. };
  96146. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  96147. var _this = this;
  96148. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  96149. var currentRotation = mainImpostor.object.rotationQuaternion;
  96150. if (meshChildren.length) {
  96151. var processMesh = function (localPosition, mesh) {
  96152. if (!currentRotation || !mesh.rotationQuaternion) {
  96153. return;
  96154. }
  96155. var childImpostor = mesh.getPhysicsImpostor();
  96156. if (childImpostor) {
  96157. var parent = childImpostor.parent;
  96158. if (parent !== mainImpostor) {
  96159. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  96160. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  96161. if (childImpostor.physicsBody) {
  96162. _this.removePhysicsBody(childImpostor);
  96163. childImpostor.physicsBody = null;
  96164. }
  96165. childImpostor.parent = mainImpostor;
  96166. childImpostor.resetUpdateFlags();
  96167. 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));
  96168. //Add the mass of the children.
  96169. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  96170. }
  96171. }
  96172. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  96173. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  96174. };
  96175. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  96176. }
  96177. };
  96178. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96179. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  96180. this.world.removeEventListener("preStep", impostor.beforeStep);
  96181. this.world.removeEventListener("postStep", impostor.afterStep);
  96182. this.world.remove(impostor.physicsBody);
  96183. };
  96184. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96185. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96186. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96187. if (!mainBody || !connectedBody) {
  96188. return;
  96189. }
  96190. var constraint;
  96191. var jointData = impostorJoint.joint.jointData;
  96192. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  96193. var constraintData = {
  96194. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  96195. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  96196. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  96197. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  96198. maxForce: jointData.nativeParams.maxForce,
  96199. collideConnected: !!jointData.collision
  96200. };
  96201. switch (impostorJoint.joint.type) {
  96202. case BABYLON.PhysicsJoint.HingeJoint:
  96203. case BABYLON.PhysicsJoint.Hinge2Joint:
  96204. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  96205. break;
  96206. case BABYLON.PhysicsJoint.DistanceJoint:
  96207. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  96208. break;
  96209. case BABYLON.PhysicsJoint.SpringJoint:
  96210. var springData = jointData;
  96211. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  96212. restLength: springData.length,
  96213. stiffness: springData.stiffness,
  96214. damping: springData.damping,
  96215. localAnchorA: constraintData.pivotA,
  96216. localAnchorB: constraintData.pivotB
  96217. });
  96218. break;
  96219. case BABYLON.PhysicsJoint.LockJoint:
  96220. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  96221. break;
  96222. case BABYLON.PhysicsJoint.PointToPointJoint:
  96223. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96224. default:
  96225. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  96226. break;
  96227. }
  96228. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  96229. constraint.collideConnected = !!jointData.collision;
  96230. impostorJoint.joint.physicsJoint = constraint;
  96231. //don't add spring as constraint, as it is not one.
  96232. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96233. this.world.addConstraint(constraint);
  96234. }
  96235. else {
  96236. impostorJoint.joint.jointData.forceApplicationCallback = impostorJoint.joint.jointData.forceApplicationCallback || function () {
  96237. constraint.applyForce();
  96238. };
  96239. impostorJoint.mainImpostor.registerAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96240. }
  96241. };
  96242. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96243. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  96244. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  96245. }
  96246. else {
  96247. impostorJoint.mainImpostor.unregisterAfterPhysicsStep(impostorJoint.joint.jointData.forceApplicationCallback);
  96248. }
  96249. };
  96250. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  96251. var index;
  96252. var mat;
  96253. for (index = 0; index < this._physicsMaterials.length; index++) {
  96254. mat = this._physicsMaterials[index];
  96255. if (mat.friction === friction && mat.restitution === restitution) {
  96256. return mat;
  96257. }
  96258. }
  96259. var currentMat = new this.BJSCANNON.Material(name);
  96260. currentMat.friction = friction;
  96261. currentMat.restitution = restitution;
  96262. this._physicsMaterials.push(currentMat);
  96263. return currentMat;
  96264. };
  96265. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  96266. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  96267. };
  96268. CannonJSPlugin.prototype._createShape = function (impostor) {
  96269. var object = impostor.object;
  96270. var returnValue;
  96271. var extendSize = impostor.getObjectExtendSize();
  96272. switch (impostor.type) {
  96273. case BABYLON.PhysicsImpostor.SphereImpostor:
  96274. var radiusX = extendSize.x;
  96275. var radiusY = extendSize.y;
  96276. var radiusZ = extendSize.z;
  96277. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  96278. break;
  96279. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  96280. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96281. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  96282. break;
  96283. case BABYLON.PhysicsImpostor.BoxImpostor:
  96284. var box = extendSize.scale(0.5);
  96285. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  96286. break;
  96287. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96288. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  96289. returnValue = new this.BJSCANNON.Plane();
  96290. break;
  96291. case BABYLON.PhysicsImpostor.MeshImpostor:
  96292. // should transform the vertex data to world coordinates!!
  96293. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  96294. var rawFaces = object.getIndices ? object.getIndices() : [];
  96295. if (!rawVerts)
  96296. return;
  96297. // get only scale! so the object could transform correctly.
  96298. var oldPosition = object.position.clone();
  96299. var oldRotation = object.rotation && object.rotation.clone();
  96300. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  96301. object.position.copyFromFloats(0, 0, 0);
  96302. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96303. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96304. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96305. var transform = object.computeWorldMatrix(true);
  96306. // convert rawVerts to object space
  96307. var temp = new Array();
  96308. var index;
  96309. for (index = 0; index < rawVerts.length; index += 3) {
  96310. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  96311. }
  96312. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  96313. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  96314. //now set back the transformation!
  96315. object.position.copyFrom(oldPosition);
  96316. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  96317. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  96318. break;
  96319. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  96320. var oldPosition2 = object.position.clone();
  96321. var oldRotation2 = object.rotation && object.rotation.clone();
  96322. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  96323. object.position.copyFromFloats(0, 0, 0);
  96324. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  96325. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  96326. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  96327. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  96328. returnValue = this._createHeightmap(object);
  96329. object.position.copyFrom(oldPosition2);
  96330. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  96331. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  96332. object.computeWorldMatrix(true);
  96333. break;
  96334. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96335. returnValue = new this.BJSCANNON.Particle();
  96336. break;
  96337. }
  96338. return returnValue;
  96339. };
  96340. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  96341. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  96342. var transform = object.computeWorldMatrix(true);
  96343. // convert rawVerts to object space
  96344. var temp = new Array();
  96345. var index;
  96346. for (index = 0; index < pos.length; index += 3) {
  96347. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  96348. }
  96349. pos = temp;
  96350. var matrix = new Array();
  96351. //For now pointDepth will not be used and will be automatically calculated.
  96352. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  96353. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  96354. var boundingInfo = object.getBoundingInfo();
  96355. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  96356. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  96357. var elementSize = dim * 2 / arraySize;
  96358. for (var i = 0; i < pos.length; i = i + 3) {
  96359. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  96360. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  96361. var y = -pos[i + 2] + minY;
  96362. if (!matrix[x]) {
  96363. matrix[x] = [];
  96364. }
  96365. if (!matrix[x][z]) {
  96366. matrix[x][z] = y;
  96367. }
  96368. matrix[x][z] = Math.max(y, matrix[x][z]);
  96369. }
  96370. for (var x = 0; x <= arraySize; ++x) {
  96371. if (!matrix[x]) {
  96372. var loc = 1;
  96373. while (!matrix[(x + loc) % arraySize]) {
  96374. loc++;
  96375. }
  96376. matrix[x] = matrix[(x + loc) % arraySize].slice();
  96377. //console.log("missing x", x);
  96378. }
  96379. for (var z = 0; z <= arraySize; ++z) {
  96380. if (!matrix[x][z]) {
  96381. var loc = 1;
  96382. var newValue;
  96383. while (newValue === undefined) {
  96384. newValue = matrix[x][(z + loc++) % arraySize];
  96385. }
  96386. matrix[x][z] = newValue;
  96387. }
  96388. }
  96389. }
  96390. var shape = new this.BJSCANNON.Heightfield(matrix, {
  96391. elementSize: elementSize
  96392. });
  96393. //For future reference, needed for body transformation
  96394. shape.minY = minY;
  96395. return shape;
  96396. };
  96397. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  96398. var object = impostor.object;
  96399. //make sure it is updated...
  96400. object.computeWorldMatrix && object.computeWorldMatrix(true);
  96401. // The delta between the mesh position and the mesh bounding box center
  96402. var bInfo = object.getBoundingInfo();
  96403. if (!bInfo)
  96404. return;
  96405. var center = impostor.getObjectCenter();
  96406. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  96407. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  96408. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  96409. this._tmpPosition.copyFrom(center);
  96410. var quaternion = object.rotationQuaternion;
  96411. if (!quaternion) {
  96412. return;
  96413. }
  96414. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  96415. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  96416. //-90 DEG in X, precalculated
  96417. quaternion = quaternion.multiply(this._minus90X);
  96418. //Invert! (Precalculated, 90 deg in X)
  96419. //No need to clone. this will never change.
  96420. impostor.setDeltaRotation(this._plus90X);
  96421. }
  96422. //If it is a heightfield, if should be centered.
  96423. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  96424. var mesh = object;
  96425. var boundingInfo = mesh.getBoundingInfo();
  96426. //calculate the correct body position:
  96427. var rotationQuaternion = mesh.rotationQuaternion;
  96428. mesh.rotationQuaternion = this._tmpUnityRotation;
  96429. mesh.computeWorldMatrix(true);
  96430. //get original center with no rotation
  96431. var c = center.clone();
  96432. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  96433. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  96434. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  96435. mesh.setPreTransformMatrix(p);
  96436. mesh.computeWorldMatrix(true);
  96437. //calculate the translation
  96438. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  96439. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  96440. //add it inverted to the delta
  96441. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  96442. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  96443. //rotation is back
  96444. mesh.rotationQuaternion = rotationQuaternion;
  96445. mesh.setPreTransformMatrix(oldPivot);
  96446. mesh.computeWorldMatrix(true);
  96447. }
  96448. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  96449. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  96450. //this._tmpPosition.copyFrom(object.position);
  96451. }
  96452. impostor.setDeltaPosition(this._tmpDeltaPosition);
  96453. //Now update the impostor object
  96454. impostor.physicsBody.position.copy(this._tmpPosition);
  96455. impostor.physicsBody.quaternion.copy(quaternion);
  96456. };
  96457. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96458. impostor.object.position.copyFrom(impostor.physicsBody.position);
  96459. if (impostor.object.rotationQuaternion) {
  96460. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  96461. }
  96462. };
  96463. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96464. impostor.physicsBody.position.copy(newPosition);
  96465. impostor.physicsBody.quaternion.copy(newRotation);
  96466. };
  96467. CannonJSPlugin.prototype.isSupported = function () {
  96468. return this.BJSCANNON !== undefined;
  96469. };
  96470. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96471. impostor.physicsBody.velocity.copy(velocity);
  96472. };
  96473. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96474. impostor.physicsBody.angularVelocity.copy(velocity);
  96475. };
  96476. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96477. var v = impostor.physicsBody.velocity;
  96478. if (!v) {
  96479. return null;
  96480. }
  96481. return new BABYLON.Vector3(v.x, v.y, v.z);
  96482. };
  96483. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96484. var v = impostor.physicsBody.angularVelocity;
  96485. if (!v) {
  96486. return null;
  96487. }
  96488. return new BABYLON.Vector3(v.x, v.y, v.z);
  96489. };
  96490. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96491. impostor.physicsBody.mass = mass;
  96492. impostor.physicsBody.updateMassProperties();
  96493. };
  96494. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  96495. return impostor.physicsBody.mass;
  96496. };
  96497. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  96498. return impostor.physicsBody.material.friction;
  96499. };
  96500. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96501. impostor.physicsBody.material.friction = friction;
  96502. };
  96503. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96504. return impostor.physicsBody.material.restitution;
  96505. };
  96506. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96507. impostor.physicsBody.material.restitution = restitution;
  96508. };
  96509. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  96510. impostor.physicsBody.sleep();
  96511. };
  96512. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  96513. impostor.physicsBody.wakeUp();
  96514. };
  96515. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96516. joint.physicsJoint.distance = maxDistance;
  96517. };
  96518. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96519. // if (!motorIndex) {
  96520. // joint.physicsJoint.enableMotor();
  96521. // }
  96522. // }
  96523. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  96524. // if (!motorIndex) {
  96525. // joint.physicsJoint.disableMotor();
  96526. // }
  96527. // }
  96528. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96529. if (!motorIndex) {
  96530. joint.physicsJoint.enableMotor();
  96531. joint.physicsJoint.setMotorSpeed(speed);
  96532. if (maxForce) {
  96533. this.setLimit(joint, maxForce);
  96534. }
  96535. }
  96536. };
  96537. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  96538. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  96539. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  96540. };
  96541. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96542. var body = impostor.physicsBody;
  96543. mesh.position.x = body.position.x;
  96544. mesh.position.y = body.position.y;
  96545. mesh.position.z = body.position.z;
  96546. if (mesh.rotationQuaternion) {
  96547. mesh.rotationQuaternion.x = body.quaternion.x;
  96548. mesh.rotationQuaternion.y = body.quaternion.y;
  96549. mesh.rotationQuaternion.z = body.quaternion.z;
  96550. mesh.rotationQuaternion.w = body.quaternion.w;
  96551. }
  96552. };
  96553. CannonJSPlugin.prototype.getRadius = function (impostor) {
  96554. var shape = impostor.physicsBody.shapes[0];
  96555. return shape.boundingSphereRadius;
  96556. };
  96557. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96558. var shape = impostor.physicsBody.shapes[0];
  96559. result.x = shape.halfExtents.x * 2;
  96560. result.y = shape.halfExtents.y * 2;
  96561. result.z = shape.halfExtents.z * 2;
  96562. };
  96563. CannonJSPlugin.prototype.dispose = function () {
  96564. };
  96565. CannonJSPlugin.prototype._extendNamespace = function () {
  96566. //this will force cannon to execute at least one step when using interpolation
  96567. var step_tmp1 = new this.BJSCANNON.Vec3();
  96568. var Engine = this.BJSCANNON;
  96569. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  96570. maxSubSteps = maxSubSteps || 10;
  96571. timeSinceLastCalled = timeSinceLastCalled || 0;
  96572. if (timeSinceLastCalled === 0) {
  96573. this.internalStep(dt);
  96574. this.time += dt;
  96575. }
  96576. else {
  96577. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  96578. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  96579. var t0 = performance.now();
  96580. for (var i = 0; i !== internalSteps; i++) {
  96581. this.internalStep(dt);
  96582. if (performance.now() - t0 > dt * 1000) {
  96583. break;
  96584. }
  96585. }
  96586. this.time += timeSinceLastCalled;
  96587. var h = this.time % dt;
  96588. var h_div_dt = h / dt;
  96589. var interpvelo = step_tmp1;
  96590. var bodies = this.bodies;
  96591. for (var j = 0; j !== bodies.length; j++) {
  96592. var b = bodies[j];
  96593. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  96594. b.position.vsub(b.previousPosition, interpvelo);
  96595. interpvelo.scale(h_div_dt, interpvelo);
  96596. b.position.vadd(interpvelo, b.interpolatedPosition);
  96597. }
  96598. else {
  96599. b.interpolatedPosition.copy(b.position);
  96600. b.interpolatedQuaternion.copy(b.quaternion);
  96601. }
  96602. }
  96603. }
  96604. };
  96605. };
  96606. return CannonJSPlugin;
  96607. }());
  96608. BABYLON.CannonJSPlugin = CannonJSPlugin;
  96609. })(BABYLON || (BABYLON = {}));
  96610. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  96611. var BABYLON;
  96612. (function (BABYLON) {
  96613. /** @hidden */
  96614. var OimoJSPlugin = /** @class */ (function () {
  96615. function OimoJSPlugin(iterations) {
  96616. this.name = "OimoJSPlugin";
  96617. this._tmpImpostorsArray = [];
  96618. this._tmpPositionVector = BABYLON.Vector3.Zero();
  96619. this.BJSOIMO = OIMO;
  96620. this.world = new this.BJSOIMO.World({
  96621. iterations: iterations
  96622. });
  96623. this.world.clear();
  96624. }
  96625. OimoJSPlugin.prototype.setGravity = function (gravity) {
  96626. this.world.gravity.copy(gravity);
  96627. };
  96628. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  96629. this.world.timeStep = timeStep;
  96630. };
  96631. OimoJSPlugin.prototype.getTimeStep = function () {
  96632. return this.world.timeStep;
  96633. };
  96634. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  96635. var _this = this;
  96636. impostors.forEach(function (impostor) {
  96637. impostor.beforeStep();
  96638. });
  96639. this.world.step();
  96640. impostors.forEach(function (impostor) {
  96641. impostor.afterStep();
  96642. //update the ordered impostors array
  96643. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  96644. });
  96645. //check for collisions
  96646. var contact = this.world.contacts;
  96647. while (contact !== null) {
  96648. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  96649. contact = contact.next;
  96650. continue;
  96651. }
  96652. //is this body colliding with any other? get the impostor
  96653. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  96654. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  96655. if (!mainImpostor || !collidingImpostor) {
  96656. contact = contact.next;
  96657. continue;
  96658. }
  96659. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  96660. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  96661. contact = contact.next;
  96662. }
  96663. };
  96664. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  96665. var mass = impostor.physicsBody.mass;
  96666. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  96667. };
  96668. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  96669. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  96670. this.applyImpulse(impostor, force, contactPoint);
  96671. };
  96672. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  96673. var _this = this;
  96674. //parent-child relationship. Does this impostor has a parent impostor?
  96675. if (impostor.parent) {
  96676. if (impostor.physicsBody) {
  96677. this.removePhysicsBody(impostor);
  96678. //TODO is that needed?
  96679. impostor.forceUpdate();
  96680. }
  96681. return;
  96682. }
  96683. if (impostor.isBodyInitRequired()) {
  96684. var bodyConfig = {
  96685. name: impostor.uniqueId,
  96686. //Oimo must have mass, also for static objects.
  96687. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  96688. size: [],
  96689. type: [],
  96690. pos: [],
  96691. posShape: [],
  96692. rot: [],
  96693. rotShape: [],
  96694. move: impostor.getParam("mass") !== 0,
  96695. density: impostor.getParam("mass"),
  96696. friction: impostor.getParam("friction"),
  96697. restitution: impostor.getParam("restitution"),
  96698. //Supporting older versions of Oimo
  96699. world: this.world
  96700. };
  96701. var impostors = [impostor];
  96702. var addToArray = function (parent) {
  96703. if (!parent.getChildMeshes)
  96704. return;
  96705. parent.getChildMeshes().forEach(function (m) {
  96706. if (m.physicsImpostor) {
  96707. impostors.push(m.physicsImpostor);
  96708. //m.physicsImpostor._init();
  96709. }
  96710. });
  96711. };
  96712. addToArray(impostor.object);
  96713. var checkWithEpsilon_1 = function (value) {
  96714. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  96715. };
  96716. var globalQuaternion_1 = new BABYLON.Quaternion();
  96717. impostors.forEach(function (i) {
  96718. if (!i.object.rotationQuaternion) {
  96719. return;
  96720. }
  96721. //get the correct bounding box
  96722. var oldQuaternion = i.object.rotationQuaternion;
  96723. globalQuaternion_1 = oldQuaternion.clone();
  96724. var rot = oldQuaternion.toEulerAngles();
  96725. var extendSize = i.getObjectExtendSize();
  96726. var radToDeg = 57.295779513082320876;
  96727. if (i === impostor) {
  96728. var center = impostor.getObjectCenter();
  96729. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  96730. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  96731. //Can also use Array.prototype.push.apply
  96732. bodyConfig.pos.push(center.x);
  96733. bodyConfig.pos.push(center.y);
  96734. bodyConfig.pos.push(center.z);
  96735. bodyConfig.posShape.push(0, 0, 0);
  96736. //tmp solution
  96737. bodyConfig.rot.push(0);
  96738. bodyConfig.rot.push(0);
  96739. bodyConfig.rot.push(0);
  96740. bodyConfig.rotShape.push(0, 0, 0);
  96741. }
  96742. else {
  96743. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  96744. bodyConfig.posShape.push(localPosition.x);
  96745. bodyConfig.posShape.push(localPosition.y);
  96746. bodyConfig.posShape.push(localPosition.z);
  96747. bodyConfig.pos.push(0, 0, 0);
  96748. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  96749. bodyConfig.rot.push(0);
  96750. bodyConfig.rot.push(0);
  96751. bodyConfig.rot.push(0);
  96752. bodyConfig.rotShape.push(rot.x * radToDeg);
  96753. bodyConfig.rotShape.push(rot.y * radToDeg);
  96754. bodyConfig.rotShape.push(rot.z * radToDeg);
  96755. }
  96756. // register mesh
  96757. switch (i.type) {
  96758. case BABYLON.PhysicsImpostor.ParticleImpostor:
  96759. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  96760. case BABYLON.PhysicsImpostor.SphereImpostor:
  96761. var radiusX = extendSize.x;
  96762. var radiusY = extendSize.y;
  96763. var radiusZ = extendSize.z;
  96764. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  96765. bodyConfig.type.push('sphere');
  96766. //due to the way oimo works with compounds, add 3 times
  96767. bodyConfig.size.push(size);
  96768. bodyConfig.size.push(size);
  96769. bodyConfig.size.push(size);
  96770. break;
  96771. case BABYLON.PhysicsImpostor.CylinderImpostor:
  96772. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  96773. var sizeY = checkWithEpsilon_1(extendSize.y);
  96774. bodyConfig.type.push('cylinder');
  96775. bodyConfig.size.push(sizeX);
  96776. bodyConfig.size.push(sizeY);
  96777. //due to the way oimo works with compounds, add one more value.
  96778. bodyConfig.size.push(sizeY);
  96779. break;
  96780. case BABYLON.PhysicsImpostor.PlaneImpostor:
  96781. case BABYLON.PhysicsImpostor.BoxImpostor:
  96782. default:
  96783. var sizeX = checkWithEpsilon_1(extendSize.x);
  96784. var sizeY = checkWithEpsilon_1(extendSize.y);
  96785. var sizeZ = checkWithEpsilon_1(extendSize.z);
  96786. bodyConfig.type.push('box');
  96787. //if (i === impostor) {
  96788. bodyConfig.size.push(sizeX);
  96789. bodyConfig.size.push(sizeY);
  96790. bodyConfig.size.push(sizeZ);
  96791. //} else {
  96792. // bodyConfig.size.push(0,0,0);
  96793. //}
  96794. break;
  96795. }
  96796. //actually not needed, but hey...
  96797. i.object.rotationQuaternion = oldQuaternion;
  96798. });
  96799. impostor.physicsBody = this.world.add(bodyConfig);
  96800. // set the quaternion, ignoring the previously defined (euler) rotation
  96801. impostor.physicsBody.resetQuaternion(globalQuaternion_1);
  96802. // update with delta 0, so the body will reveive the new rotation.
  96803. impostor.physicsBody.updatePosition(0);
  96804. }
  96805. else {
  96806. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  96807. }
  96808. impostor.setDeltaPosition(this._tmpPositionVector);
  96809. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  96810. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  96811. };
  96812. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  96813. //impostor.physicsBody.dispose();
  96814. //Same as : (older oimo versions)
  96815. this.world.removeRigidBody(impostor.physicsBody);
  96816. };
  96817. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  96818. var mainBody = impostorJoint.mainImpostor.physicsBody;
  96819. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  96820. if (!mainBody || !connectedBody) {
  96821. return;
  96822. }
  96823. var jointData = impostorJoint.joint.jointData;
  96824. var options = jointData.nativeParams || {};
  96825. var type;
  96826. var nativeJointData = {
  96827. body1: mainBody,
  96828. body2: connectedBody,
  96829. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  96830. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  96831. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  96832. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  96833. min: options.min,
  96834. max: options.max,
  96835. collision: options.collision || jointData.collision,
  96836. spring: options.spring,
  96837. //supporting older version of Oimo
  96838. world: this.world
  96839. };
  96840. switch (impostorJoint.joint.type) {
  96841. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  96842. type = "jointBall";
  96843. break;
  96844. case BABYLON.PhysicsJoint.SpringJoint:
  96845. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  96846. var springData = jointData;
  96847. nativeJointData.min = springData.length || nativeJointData.min;
  96848. //Max should also be set, just make sure it is at least min
  96849. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  96850. case BABYLON.PhysicsJoint.DistanceJoint:
  96851. type = "jointDistance";
  96852. nativeJointData.max = jointData.maxDistance;
  96853. break;
  96854. case BABYLON.PhysicsJoint.PrismaticJoint:
  96855. type = "jointPrisme";
  96856. break;
  96857. case BABYLON.PhysicsJoint.SliderJoint:
  96858. type = "jointSlide";
  96859. break;
  96860. case BABYLON.PhysicsJoint.WheelJoint:
  96861. type = "jointWheel";
  96862. break;
  96863. case BABYLON.PhysicsJoint.HingeJoint:
  96864. default:
  96865. type = "jointHinge";
  96866. break;
  96867. }
  96868. nativeJointData.type = type;
  96869. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  96870. };
  96871. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  96872. //Bug in Oimo prevents us from disposing a joint in the playground
  96873. //joint.joint.physicsJoint.dispose();
  96874. //So we will bruteforce it!
  96875. try {
  96876. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  96877. }
  96878. catch (e) {
  96879. BABYLON.Tools.Warn(e);
  96880. }
  96881. };
  96882. OimoJSPlugin.prototype.isSupported = function () {
  96883. return this.BJSOIMO !== undefined;
  96884. };
  96885. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  96886. if (!impostor.physicsBody.sleeping) {
  96887. //TODO check that
  96888. /*if (impostor.physicsBody.shapes.next) {
  96889. var parentShape = this._getLastShape(impostor.physicsBody);
  96890. impostor.object.position.copyFrom(parentShape.position);
  96891. console.log(parentShape.position);
  96892. } else {*/
  96893. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  96894. //}
  96895. if (impostor.object.rotationQuaternion) {
  96896. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  96897. }
  96898. }
  96899. };
  96900. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  96901. var body = impostor.physicsBody;
  96902. body.position.copy(newPosition);
  96903. body.orientation.copy(newRotation);
  96904. body.syncShapes();
  96905. body.awake();
  96906. };
  96907. /*private _getLastShape(body: any): any {
  96908. var lastShape = body.shapes;
  96909. while (lastShape.next) {
  96910. lastShape = lastShape.next;
  96911. }
  96912. return lastShape;
  96913. }*/
  96914. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  96915. impostor.physicsBody.linearVelocity.copy(velocity);
  96916. };
  96917. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  96918. impostor.physicsBody.angularVelocity.copy(velocity);
  96919. };
  96920. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  96921. var v = impostor.physicsBody.linearVelocity;
  96922. if (!v) {
  96923. return null;
  96924. }
  96925. return new BABYLON.Vector3(v.x, v.y, v.z);
  96926. };
  96927. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  96928. var v = impostor.physicsBody.angularVelocity;
  96929. if (!v) {
  96930. return null;
  96931. }
  96932. return new BABYLON.Vector3(v.x, v.y, v.z);
  96933. };
  96934. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  96935. var staticBody = mass === 0;
  96936. //this will actually set the body's density and not its mass.
  96937. //But this is how oimo treats the mass variable.
  96938. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  96939. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  96940. };
  96941. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  96942. return impostor.physicsBody.shapes.density;
  96943. };
  96944. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  96945. return impostor.physicsBody.shapes.friction;
  96946. };
  96947. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  96948. impostor.physicsBody.shapes.friction = friction;
  96949. };
  96950. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  96951. return impostor.physicsBody.shapes.restitution;
  96952. };
  96953. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  96954. impostor.physicsBody.shapes.restitution = restitution;
  96955. };
  96956. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  96957. impostor.physicsBody.sleep();
  96958. };
  96959. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  96960. impostor.physicsBody.awake();
  96961. };
  96962. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  96963. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  96964. if (minDistance !== void 0) {
  96965. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  96966. }
  96967. };
  96968. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  96969. //TODO separate rotational and transational motors.
  96970. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  96971. if (motor) {
  96972. motor.setMotor(speed, maxForce);
  96973. }
  96974. };
  96975. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  96976. //TODO separate rotational and transational motors.
  96977. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  96978. if (motor) {
  96979. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  96980. }
  96981. };
  96982. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  96983. var body = impostor.physicsBody;
  96984. mesh.position.x = body.position.x;
  96985. mesh.position.y = body.position.y;
  96986. mesh.position.z = body.position.z;
  96987. if (mesh.rotationQuaternion) {
  96988. mesh.rotationQuaternion.x = body.orientation.x;
  96989. mesh.rotationQuaternion.y = body.orientation.y;
  96990. mesh.rotationQuaternion.z = body.orientation.z;
  96991. mesh.rotationQuaternion.w = body.orientation.s;
  96992. }
  96993. };
  96994. OimoJSPlugin.prototype.getRadius = function (impostor) {
  96995. return impostor.physicsBody.shapes.radius;
  96996. };
  96997. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  96998. var shape = impostor.physicsBody.shapes;
  96999. result.x = shape.halfWidth * 2;
  97000. result.y = shape.halfHeight * 2;
  97001. result.z = shape.halfDepth * 2;
  97002. };
  97003. OimoJSPlugin.prototype.dispose = function () {
  97004. this.world.clear();
  97005. };
  97006. return OimoJSPlugin;
  97007. }());
  97008. BABYLON.OimoJSPlugin = OimoJSPlugin;
  97009. })(BABYLON || (BABYLON = {}));
  97010. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  97011. var BABYLON;
  97012. (function (BABYLON) {
  97013. /**
  97014. * Gets the current physics engine
  97015. * @returns a IPhysicsEngine or null if none attached
  97016. */
  97017. BABYLON.Scene.prototype.getPhysicsEngine = function () {
  97018. return this._physicsEngine;
  97019. };
  97020. /**
  97021. * Enables physics to the current scene
  97022. * @param gravity defines the scene's gravity for the physics engine
  97023. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  97024. * @return a boolean indicating if the physics engine was initialized
  97025. */
  97026. BABYLON.Scene.prototype.enablePhysics = function (gravity, plugin) {
  97027. if (gravity === void 0) { gravity = null; }
  97028. if (this._physicsEngine) {
  97029. return true;
  97030. }
  97031. // Register the component to the scene
  97032. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE);
  97033. if (!component) {
  97034. component = new PhysicsEngineSceneComponent(this);
  97035. this._addComponent(component);
  97036. }
  97037. try {
  97038. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  97039. return true;
  97040. }
  97041. catch (e) {
  97042. BABYLON.Tools.Error(e.message);
  97043. return false;
  97044. }
  97045. };
  97046. /**
  97047. * Disables and disposes the physics engine associated with the scene
  97048. */
  97049. BABYLON.Scene.prototype.disablePhysicsEngine = function () {
  97050. if (!this._physicsEngine) {
  97051. return;
  97052. }
  97053. this._physicsEngine.dispose();
  97054. this._physicsEngine = null;
  97055. };
  97056. /**
  97057. * Gets a boolean indicating if there is an active physics engine
  97058. * @returns a boolean indicating if there is an active physics engine
  97059. */
  97060. BABYLON.Scene.prototype.isPhysicsEnabled = function () {
  97061. return this._physicsEngine !== undefined;
  97062. };
  97063. /**
  97064. * Deletes a physics compound impostor
  97065. * @param compound defines the compound to delete
  97066. */
  97067. BABYLON.Scene.prototype.deleteCompoundImpostor = function (compound) {
  97068. var mesh = compound.parts[0].mesh;
  97069. if (mesh.physicsImpostor) {
  97070. mesh.physicsImpostor.dispose( /*true*/);
  97071. mesh.physicsImpostor = null;
  97072. }
  97073. };
  97074. /** @hidden */
  97075. BABYLON.Scene.prototype._advancePhysicsEngineStep = function (step) {
  97076. if (this._physicsEngine) {
  97077. this.onBeforePhysicsObservable.notifyObservers(this);
  97078. this._physicsEngine._step(step / 1000);
  97079. this.onAfterPhysicsObservable.notifyObservers(this);
  97080. }
  97081. };
  97082. Object.defineProperty(BABYLON.AbstractMesh.prototype, "physicsImpostor", {
  97083. get: function () {
  97084. return this._physicsImpostor;
  97085. },
  97086. set: function (value) {
  97087. var _this = this;
  97088. if (this._physicsImpostor === value) {
  97089. return;
  97090. }
  97091. if (this._disposePhysicsObserver) {
  97092. this.onDisposeObservable.remove(this._disposePhysicsObserver);
  97093. }
  97094. this._physicsImpostor = value;
  97095. if (value) {
  97096. this._disposePhysicsObserver = this.onDisposeObservable.add(function () {
  97097. // Physics
  97098. if (_this.physicsImpostor) {
  97099. _this.physicsImpostor.dispose( /*!doNotRecurse*/);
  97100. _this.physicsImpostor = null;
  97101. }
  97102. });
  97103. }
  97104. },
  97105. enumerable: true,
  97106. configurable: true
  97107. });
  97108. /**
  97109. * Gets the current physics impostor
  97110. * @see http://doc.babylonjs.com/features/physics_engine
  97111. * @returns a physics impostor or null
  97112. */
  97113. BABYLON.AbstractMesh.prototype.getPhysicsImpostor = function () {
  97114. return this.physicsImpostor;
  97115. };
  97116. /**
  97117. * Apply a physic impulse to the mesh
  97118. * @param force defines the force to apply
  97119. * @param contactPoint defines where to apply the force
  97120. * @returns the current mesh
  97121. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  97122. */
  97123. BABYLON.AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  97124. if (!this.physicsImpostor) {
  97125. return this;
  97126. }
  97127. this.physicsImpostor.applyImpulse(force, contactPoint);
  97128. return this;
  97129. };
  97130. /**
  97131. * Creates a physic joint between two meshes
  97132. * @param otherMesh defines the other mesh to use
  97133. * @param pivot1 defines the pivot to use on this mesh
  97134. * @param pivot2 defines the pivot to use on the other mesh
  97135. * @param options defines additional options (can be plugin dependent)
  97136. * @returns the current mesh
  97137. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  97138. */
  97139. BABYLON.AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  97140. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  97141. return this;
  97142. }
  97143. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  97144. mainPivot: pivot1,
  97145. connectedPivot: pivot2,
  97146. nativeParams: options
  97147. });
  97148. return this;
  97149. };
  97150. /**
  97151. * Defines the physics engine scene component responsible to manage a physics engine
  97152. */
  97153. var PhysicsEngineSceneComponent = /** @class */ (function () {
  97154. /**
  97155. * Creates a new instance of the component for the given scene
  97156. * @param scene Defines the scene to register the component in
  97157. */
  97158. function PhysicsEngineSceneComponent(scene) {
  97159. var _this = this;
  97160. /**
  97161. * The component name helpful to identify the component in the list of scene components.
  97162. */
  97163. this.name = BABYLON.SceneComponentConstants.NAME_PHYSICSENGINE;
  97164. this.scene = scene;
  97165. this.scene.onBeforePhysicsObservable = new BABYLON.Observable();
  97166. this.scene.onAfterPhysicsObservable = new BABYLON.Observable();
  97167. // Replace the function used to get the deterministic frame time
  97168. this.scene.getDeterministicFrameTime = function () {
  97169. if (_this.scene._physicsEngine) {
  97170. return _this.scene._physicsEngine.getTimeStep() * 1000;
  97171. }
  97172. return 1000.0 / 60.0;
  97173. };
  97174. }
  97175. /**
  97176. * Registers the component in a given scene
  97177. */
  97178. PhysicsEngineSceneComponent.prototype.register = function () {
  97179. };
  97180. /**
  97181. * Rebuilds the elements related to this component in case of
  97182. * context lost for instance.
  97183. */
  97184. PhysicsEngineSceneComponent.prototype.rebuild = function () {
  97185. // Nothing to do for this component
  97186. };
  97187. /**
  97188. * Disposes the component and the associated ressources
  97189. */
  97190. PhysicsEngineSceneComponent.prototype.dispose = function () {
  97191. this.scene.onBeforePhysicsObservable.clear();
  97192. this.scene.onAfterPhysicsObservable.clear();
  97193. if (this.scene._physicsEngine) {
  97194. this.scene.disablePhysicsEngine();
  97195. }
  97196. };
  97197. return PhysicsEngineSceneComponent;
  97198. }());
  97199. BABYLON.PhysicsEngineSceneComponent = PhysicsEngineSceneComponent;
  97200. })(BABYLON || (BABYLON = {}));
  97201. //# sourceMappingURL=babylon.physicsEngineComponent.js.map
  97202. var BABYLON;
  97203. (function (BABYLON) {
  97204. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  97205. // All values and structures referenced from:
  97206. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  97207. var DDS_MAGIC = 0x20534444;
  97208. var
  97209. //DDSD_CAPS = 0x1,
  97210. //DDSD_HEIGHT = 0x2,
  97211. //DDSD_WIDTH = 0x4,
  97212. //DDSD_PITCH = 0x8,
  97213. //DDSD_PIXELFORMAT = 0x1000,
  97214. DDSD_MIPMAPCOUNT = 0x20000;
  97215. //DDSD_LINEARSIZE = 0x80000,
  97216. //DDSD_DEPTH = 0x800000;
  97217. // var DDSCAPS_COMPLEX = 0x8,
  97218. // DDSCAPS_MIPMAP = 0x400000,
  97219. // DDSCAPS_TEXTURE = 0x1000;
  97220. var DDSCAPS2_CUBEMAP = 0x200;
  97221. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  97222. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  97223. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  97224. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  97225. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  97226. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  97227. // DDSCAPS2_VOLUME = 0x200000;
  97228. var
  97229. //DDPF_ALPHAPIXELS = 0x1,
  97230. //DDPF_ALPHA = 0x2,
  97231. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  97232. //DDPF_YUV = 0x200,
  97233. DDPF_LUMINANCE = 0x20000;
  97234. function FourCCToInt32(value) {
  97235. return value.charCodeAt(0) +
  97236. (value.charCodeAt(1) << 8) +
  97237. (value.charCodeAt(2) << 16) +
  97238. (value.charCodeAt(3) << 24);
  97239. }
  97240. function Int32ToFourCC(value) {
  97241. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  97242. }
  97243. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  97244. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  97245. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  97246. var FOURCC_DX10 = FourCCToInt32("DX10");
  97247. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  97248. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  97249. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  97250. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  97251. var headerLengthInt = 31; // The header length in 32 bit ints
  97252. // Offsets into the header array
  97253. var off_magic = 0;
  97254. var off_size = 1;
  97255. var off_flags = 2;
  97256. var off_height = 3;
  97257. var off_width = 4;
  97258. var off_mipmapCount = 7;
  97259. var off_pfFlags = 20;
  97260. var off_pfFourCC = 21;
  97261. var off_RGBbpp = 22;
  97262. var off_RMask = 23;
  97263. var off_GMask = 24;
  97264. var off_BMask = 25;
  97265. var off_AMask = 26;
  97266. // var off_caps1 = 27;
  97267. var off_caps2 = 28;
  97268. // var off_caps3 = 29;
  97269. // var off_caps4 = 30;
  97270. var off_dxgiFormat = 32;
  97271. ;
  97272. /**
  97273. * Class used to provide DDS decompression tools
  97274. */
  97275. var DDSTools = /** @class */ (function () {
  97276. function DDSTools() {
  97277. }
  97278. /**
  97279. * Gets DDS information from an array buffer
  97280. * @param arrayBuffer defines the array buffer to read data from
  97281. * @returns the DDS information
  97282. */
  97283. DDSTools.GetDDSInfo = function (arrayBuffer) {
  97284. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97285. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  97286. var mipmapCount = 1;
  97287. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  97288. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97289. }
  97290. var fourCC = header[off_pfFourCC];
  97291. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  97292. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97293. switch (fourCC) {
  97294. case FOURCC_D3DFMT_R16G16B16A16F:
  97295. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97296. break;
  97297. case FOURCC_D3DFMT_R32G32B32A32F:
  97298. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97299. break;
  97300. case FOURCC_DX10:
  97301. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  97302. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97303. break;
  97304. }
  97305. }
  97306. return {
  97307. width: header[off_width],
  97308. height: header[off_height],
  97309. mipmapCount: mipmapCount,
  97310. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  97311. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  97312. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  97313. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  97314. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  97315. dxgiFormat: dxgiFormat,
  97316. textureType: textureType
  97317. };
  97318. };
  97319. DDSTools._ToHalfFloat = function (value) {
  97320. if (!DDSTools._FloatView) {
  97321. DDSTools._FloatView = new Float32Array(1);
  97322. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  97323. }
  97324. DDSTools._FloatView[0] = value;
  97325. var x = DDSTools._Int32View[0];
  97326. var bits = (x >> 16) & 0x8000; /* Get the sign */
  97327. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  97328. var e = (x >> 23) & 0xff; /* Using int is faster here */
  97329. /* If zero, or denormal, or exponent underflows too much for a denormal
  97330. * half, return signed zero. */
  97331. if (e < 103) {
  97332. return bits;
  97333. }
  97334. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  97335. if (e > 142) {
  97336. bits |= 0x7c00;
  97337. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  97338. * not Inf, so make sure we set one mantissa bit too. */
  97339. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  97340. return bits;
  97341. }
  97342. /* If exponent underflows but not too much, return a denormal */
  97343. if (e < 113) {
  97344. m |= 0x0800;
  97345. /* Extra rounding may overflow and set mantissa to 0 and exponent
  97346. * to 1, which is OK. */
  97347. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  97348. return bits;
  97349. }
  97350. bits |= ((e - 112) << 10) | (m >> 1);
  97351. bits += m & 1;
  97352. return bits;
  97353. };
  97354. DDSTools._FromHalfFloat = function (value) {
  97355. var s = (value & 0x8000) >> 15;
  97356. var e = (value & 0x7C00) >> 10;
  97357. var f = value & 0x03FF;
  97358. if (e === 0) {
  97359. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  97360. }
  97361. else if (e == 0x1F) {
  97362. return f ? NaN : ((s ? -1 : 1) * Infinity);
  97363. }
  97364. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  97365. };
  97366. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97367. var destArray = new Float32Array(dataLength);
  97368. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97369. var index = 0;
  97370. for (var y = 0; y < height; y++) {
  97371. for (var x = 0; x < width; x++) {
  97372. var srcPos = (x + y * width) * 4;
  97373. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  97374. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  97375. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  97376. if (DDSTools.StoreLODInAlphaChannel) {
  97377. destArray[index + 3] = lod;
  97378. }
  97379. else {
  97380. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  97381. }
  97382. index += 4;
  97383. }
  97384. }
  97385. return destArray;
  97386. };
  97387. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97388. if (DDSTools.StoreLODInAlphaChannel) {
  97389. var destArray = new Uint16Array(dataLength);
  97390. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97391. var index = 0;
  97392. for (var y = 0; y < height; y++) {
  97393. for (var x = 0; x < width; x++) {
  97394. var srcPos = (x + y * width) * 4;
  97395. destArray[index] = srcData[srcPos];
  97396. destArray[index + 1] = srcData[srcPos + 1];
  97397. destArray[index + 2] = srcData[srcPos + 2];
  97398. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  97399. index += 4;
  97400. }
  97401. }
  97402. return destArray;
  97403. }
  97404. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  97405. };
  97406. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97407. if (DDSTools.StoreLODInAlphaChannel) {
  97408. var destArray = new Float32Array(dataLength);
  97409. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97410. var index = 0;
  97411. for (var y = 0; y < height; y++) {
  97412. for (var x = 0; x < width; x++) {
  97413. var srcPos = (x + y * width) * 4;
  97414. destArray[index] = srcData[srcPos];
  97415. destArray[index + 1] = srcData[srcPos + 1];
  97416. destArray[index + 2] = srcData[srcPos + 2];
  97417. destArray[index + 3] = lod;
  97418. index += 4;
  97419. }
  97420. }
  97421. return destArray;
  97422. }
  97423. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  97424. };
  97425. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97426. var destArray = new Uint8Array(dataLength);
  97427. var srcData = new Float32Array(arrayBuffer, dataOffset);
  97428. var index = 0;
  97429. for (var y = 0; y < height; y++) {
  97430. for (var x = 0; x < width; x++) {
  97431. var srcPos = (x + y * width) * 4;
  97432. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  97433. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  97434. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  97435. if (DDSTools.StoreLODInAlphaChannel) {
  97436. destArray[index + 3] = lod;
  97437. }
  97438. else {
  97439. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  97440. }
  97441. index += 4;
  97442. }
  97443. }
  97444. return destArray;
  97445. };
  97446. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  97447. var destArray = new Uint8Array(dataLength);
  97448. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  97449. var index = 0;
  97450. for (var y = 0; y < height; y++) {
  97451. for (var x = 0; x < width; x++) {
  97452. var srcPos = (x + y * width) * 4;
  97453. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  97454. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  97455. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  97456. if (DDSTools.StoreLODInAlphaChannel) {
  97457. destArray[index + 3] = lod;
  97458. }
  97459. else {
  97460. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  97461. }
  97462. index += 4;
  97463. }
  97464. }
  97465. return destArray;
  97466. };
  97467. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  97468. var byteArray = new Uint8Array(dataLength);
  97469. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97470. var index = 0;
  97471. for (var y = 0; y < height; y++) {
  97472. for (var x = 0; x < width; x++) {
  97473. var srcPos = (x + y * width) * 4;
  97474. byteArray[index] = srcData[srcPos + rOffset];
  97475. byteArray[index + 1] = srcData[srcPos + gOffset];
  97476. byteArray[index + 2] = srcData[srcPos + bOffset];
  97477. byteArray[index + 3] = srcData[srcPos + aOffset];
  97478. index += 4;
  97479. }
  97480. }
  97481. return byteArray;
  97482. };
  97483. DDSTools._ExtractLongWordOrder = function (value) {
  97484. if (value === 0 || value === 255 || value === -16777216) {
  97485. return 0;
  97486. }
  97487. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  97488. };
  97489. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  97490. var byteArray = new Uint8Array(dataLength);
  97491. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97492. var index = 0;
  97493. for (var y = 0; y < height; y++) {
  97494. for (var x = 0; x < width; x++) {
  97495. var srcPos = (x + y * width) * 3;
  97496. byteArray[index] = srcData[srcPos + rOffset];
  97497. byteArray[index + 1] = srcData[srcPos + gOffset];
  97498. byteArray[index + 2] = srcData[srcPos + bOffset];
  97499. index += 3;
  97500. }
  97501. }
  97502. return byteArray;
  97503. };
  97504. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  97505. var byteArray = new Uint8Array(dataLength);
  97506. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  97507. var index = 0;
  97508. for (var y = 0; y < height; y++) {
  97509. for (var x = 0; x < width; x++) {
  97510. var srcPos = (x + y * width);
  97511. byteArray[index] = srcData[srcPos];
  97512. index++;
  97513. }
  97514. }
  97515. return byteArray;
  97516. };
  97517. /**
  97518. * Uploads DDS Levels to a Babylon Texture
  97519. * @hidden
  97520. */
  97521. DDSTools.UploadDDSLevels = function (engine, texture, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  97522. if (lodIndex === void 0) { lodIndex = -1; }
  97523. var sphericalPolynomialFaces = null;
  97524. if (info.sphericalPolynomial) {
  97525. sphericalPolynomialFaces = new Array();
  97526. }
  97527. var ext = engine.getCaps().s3tc;
  97528. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  97529. var fourCC, width, height, dataLength = 0, dataOffset;
  97530. var byteArray, mipmapCount, mip;
  97531. var internalCompressedFormat = 0;
  97532. var blockBytes = 1;
  97533. if (header[off_magic] !== DDS_MAGIC) {
  97534. BABYLON.Tools.Error("Invalid magic number in DDS header");
  97535. return;
  97536. }
  97537. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  97538. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  97539. return;
  97540. }
  97541. if (info.isCompressed && !ext) {
  97542. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  97543. return;
  97544. }
  97545. var bpp = header[off_RGBbpp];
  97546. dataOffset = header[off_size] + 4;
  97547. var computeFormats = false;
  97548. if (info.isFourCC) {
  97549. fourCC = header[off_pfFourCC];
  97550. switch (fourCC) {
  97551. case FOURCC_DXT1:
  97552. blockBytes = 8;
  97553. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  97554. break;
  97555. case FOURCC_DXT3:
  97556. blockBytes = 16;
  97557. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  97558. break;
  97559. case FOURCC_DXT5:
  97560. blockBytes = 16;
  97561. internalCompressedFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  97562. break;
  97563. case FOURCC_D3DFMT_R16G16B16A16F:
  97564. computeFormats = true;
  97565. break;
  97566. case FOURCC_D3DFMT_R32G32B32A32F:
  97567. computeFormats = true;
  97568. break;
  97569. case FOURCC_DX10:
  97570. // There is an additionnal header so dataOffset need to be changed
  97571. dataOffset += 5 * 4; // 5 uints
  97572. var supported = false;
  97573. switch (info.dxgiFormat) {
  97574. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  97575. computeFormats = true;
  97576. supported = true;
  97577. break;
  97578. case DXGI_FORMAT_B8G8R8X8_UNORM:
  97579. info.isRGB = true;
  97580. info.isFourCC = false;
  97581. bpp = 32;
  97582. supported = true;
  97583. break;
  97584. }
  97585. if (supported) {
  97586. break;
  97587. }
  97588. default:
  97589. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  97590. return;
  97591. }
  97592. }
  97593. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  97594. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  97595. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  97596. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  97597. if (computeFormats) {
  97598. internalCompressedFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  97599. }
  97600. mipmapCount = 1;
  97601. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  97602. mipmapCount = Math.max(1, header[off_mipmapCount]);
  97603. }
  97604. for (var face = 0; face < faces; face++) {
  97605. width = header[off_width];
  97606. height = header[off_height];
  97607. for (mip = 0; mip < mipmapCount; ++mip) {
  97608. if (lodIndex === -1 || lodIndex === mip) {
  97609. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  97610. var i = (lodIndex === -1) ? mip : 0;
  97611. if (!info.isCompressed && info.isFourCC) {
  97612. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97613. dataLength = width * height * 4;
  97614. var floatArray = null;
  97615. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  97616. if (bpp === 128) {
  97617. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97618. if (sphericalPolynomialFaces && i == 0) {
  97619. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97620. }
  97621. }
  97622. else if (bpp === 64) {
  97623. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97624. if (sphericalPolynomialFaces && i == 0) {
  97625. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97626. }
  97627. }
  97628. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97629. }
  97630. else {
  97631. if (bpp === 128) {
  97632. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97633. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97634. if (sphericalPolynomialFaces && i == 0) {
  97635. sphericalPolynomialFaces.push(floatArray);
  97636. }
  97637. }
  97638. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  97639. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  97640. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97641. if (sphericalPolynomialFaces && i == 0) {
  97642. sphericalPolynomialFaces.push(floatArray);
  97643. }
  97644. }
  97645. else { // 64
  97646. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  97647. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  97648. if (sphericalPolynomialFaces && i == 0) {
  97649. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  97650. }
  97651. }
  97652. }
  97653. if (floatArray) {
  97654. engine._uploadDataToTextureDirectly(texture, floatArray, face, i);
  97655. }
  97656. }
  97657. else if (info.isRGB) {
  97658. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97659. if (bpp === 24) {
  97660. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGB;
  97661. dataLength = width * height * 3;
  97662. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  97663. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97664. }
  97665. else { // 32
  97666. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  97667. dataLength = width * height * 4;
  97668. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  97669. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97670. }
  97671. }
  97672. else if (info.isLuminance) {
  97673. var unpackAlignment = engine._getUnpackAlignement();
  97674. var unpaddedRowSize = width;
  97675. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  97676. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  97677. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  97678. texture.format = BABYLON.Engine.TEXTUREFORMAT_LUMINANCE;
  97679. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97680. engine._uploadDataToTextureDirectly(texture, byteArray, face, i);
  97681. }
  97682. else {
  97683. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  97684. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  97685. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  97686. engine._uploadCompressedDataToTextureDirectly(texture, internalCompressedFormat, width, height, byteArray, face, i);
  97687. }
  97688. }
  97689. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  97690. width *= 0.5;
  97691. height *= 0.5;
  97692. width = Math.max(1.0, width);
  97693. height = Math.max(1.0, height);
  97694. }
  97695. if (currentFace !== undefined) {
  97696. // Loading a single face
  97697. break;
  97698. }
  97699. }
  97700. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  97701. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  97702. size: header[off_width],
  97703. right: sphericalPolynomialFaces[0],
  97704. left: sphericalPolynomialFaces[1],
  97705. up: sphericalPolynomialFaces[2],
  97706. down: sphericalPolynomialFaces[3],
  97707. front: sphericalPolynomialFaces[4],
  97708. back: sphericalPolynomialFaces[5],
  97709. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  97710. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  97711. gammaSpace: false,
  97712. });
  97713. }
  97714. else {
  97715. info.sphericalPolynomial = undefined;
  97716. }
  97717. };
  97718. /**
  97719. * Gets or sets a boolean indicating that LOD info is stored in alpha channel (false by default)
  97720. */
  97721. DDSTools.StoreLODInAlphaChannel = false;
  97722. return DDSTools;
  97723. }());
  97724. BABYLON.DDSTools = DDSTools;
  97725. })(BABYLON || (BABYLON = {}));
  97726. //# sourceMappingURL=babylon.dds.js.map
  97727. var BABYLON;
  97728. (function (BABYLON) {
  97729. /**
  97730. * Implementation of the DDS Texture Loader.
  97731. */
  97732. var DDSTextureLoader = /** @class */ (function () {
  97733. function DDSTextureLoader() {
  97734. /**
  97735. * Defines wether the loader supports cascade loading the different faces.
  97736. */
  97737. this.supportCascades = true;
  97738. }
  97739. /**
  97740. * This returns if the loader support the current file information.
  97741. * @param extension defines the file extension of the file being loaded
  97742. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97743. * @param fallback defines the fallback internal texture if any
  97744. * @param isBase64 defines whether the texture is encoded as a base64
  97745. * @param isBuffer defines whether the texture data are stored as a buffer
  97746. * @returns true if the loader can load the specified file
  97747. */
  97748. DDSTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  97749. return extension.indexOf(".dds") === 0;
  97750. };
  97751. /**
  97752. * Transform the url before loading if required.
  97753. * @param rootUrl the url of the texture
  97754. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97755. * @returns the transformed texture
  97756. */
  97757. DDSTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  97758. return rootUrl;
  97759. };
  97760. /**
  97761. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  97762. * @param rootUrl the url of the texture
  97763. * @param textureFormatInUse defines the current compressed format in use iun the engine
  97764. * @returns the fallback texture
  97765. */
  97766. DDSTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  97767. return null;
  97768. };
  97769. /**
  97770. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  97771. * @param data contains the texture data
  97772. * @param texture defines the BabylonJS internal texture
  97773. * @param createPolynomials will be true if polynomials have been requested
  97774. * @param onLoad defines the callback to trigger once the texture is ready
  97775. * @param onError defines the callback to trigger in case of error
  97776. */
  97777. DDSTextureLoader.prototype.loadCubeData = function (imgs, texture, createPolynomials, onLoad, onError) {
  97778. var engine = texture.getEngine();
  97779. var info;
  97780. var loadMipmap = false;
  97781. if (Array.isArray(imgs)) {
  97782. for (var index = 0; index < imgs.length; index++) {
  97783. var data_1 = imgs[index];
  97784. info = BABYLON.DDSTools.GetDDSInfo(data_1);
  97785. texture.width = info.width;
  97786. texture.height = info.height;
  97787. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  97788. engine._unpackFlipY(info.isCompressed);
  97789. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data_1, info, loadMipmap, 6, -1, index);
  97790. if (!info.isFourCC && info.mipmapCount === 1) {
  97791. engine.generateMipMapsForCubemap(texture);
  97792. }
  97793. }
  97794. }
  97795. else {
  97796. var data = imgs;
  97797. info = BABYLON.DDSTools.GetDDSInfo(data);
  97798. texture.width = info.width;
  97799. texture.height = info.height;
  97800. if (createPolynomials) {
  97801. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  97802. }
  97803. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps;
  97804. engine._unpackFlipY(info.isCompressed);
  97805. BABYLON.DDSTools.UploadDDSLevels(engine, texture, data, info, loadMipmap, 6);
  97806. if (!info.isFourCC && info.mipmapCount === 1) {
  97807. engine.generateMipMapsForCubemap(texture);
  97808. }
  97809. }
  97810. engine._setCubeMapTextureParams(loadMipmap);
  97811. texture.isReady = true;
  97812. if (onLoad) {
  97813. onLoad({ isDDS: true, width: texture.width, info: info, data: imgs, texture: texture });
  97814. }
  97815. };
  97816. /**
  97817. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  97818. * @param data contains the texture data
  97819. * @param texture defines the BabylonJS internal texture
  97820. * @param callback defines the method to call once ready to upload
  97821. */
  97822. DDSTextureLoader.prototype.loadData = function (data, texture, callback) {
  97823. var info = BABYLON.DDSTools.GetDDSInfo(data);
  97824. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && texture.generateMipMaps && ((info.width >> (info.mipmapCount - 1)) === 1);
  97825. callback(info.width, info.height, loadMipmap, info.isFourCC, function () {
  97826. BABYLON.DDSTools.UploadDDSLevels(texture.getEngine(), texture, data, info, loadMipmap, 1);
  97827. });
  97828. };
  97829. return DDSTextureLoader;
  97830. }());
  97831. // Register the loader.
  97832. BABYLON.Engine._TextureLoaders.push(new DDSTextureLoader());
  97833. })(BABYLON || (BABYLON = {}));
  97834. //# sourceMappingURL=babylon.ddsTextureLoader.js.map
  97835. var BABYLON;
  97836. (function (BABYLON) {
  97837. /**
  97838. * Based on jsTGALoader - Javascript loader for TGA file
  97839. * By Vincent Thibault
  97840. * @see http://blog.robrowser.com/javascript-tga-loader.html
  97841. */
  97842. var TGATools = /** @class */ (function () {
  97843. function TGATools() {
  97844. }
  97845. /**
  97846. * Gets the header of a TGA file
  97847. * @param data defines the TGA data
  97848. * @returns the header
  97849. */
  97850. TGATools.GetTGAHeader = function (data) {
  97851. var offset = 0;
  97852. var header = {
  97853. id_length: data[offset++],
  97854. colormap_type: data[offset++],
  97855. image_type: data[offset++],
  97856. colormap_index: data[offset++] | data[offset++] << 8,
  97857. colormap_length: data[offset++] | data[offset++] << 8,
  97858. colormap_size: data[offset++],
  97859. origin: [
  97860. data[offset++] | data[offset++] << 8,
  97861. data[offset++] | data[offset++] << 8
  97862. ],
  97863. width: data[offset++] | data[offset++] << 8,
  97864. height: data[offset++] | data[offset++] << 8,
  97865. pixel_size: data[offset++],
  97866. flags: data[offset++]
  97867. };
  97868. return header;
  97869. };
  97870. /**
  97871. * Uploads TGA content to a Babylon Texture
  97872. * @hidden
  97873. */
  97874. TGATools.UploadContent = function (texture, data) {
  97875. // Not enough data to contain header ?
  97876. if (data.length < 19) {
  97877. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  97878. return;
  97879. }
  97880. // Read Header
  97881. var offset = 18;
  97882. var header = TGATools.GetTGAHeader(data);
  97883. // Assume it's a valid Targa file.
  97884. if (header.id_length + offset > data.length) {
  97885. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  97886. return;
  97887. }
  97888. // Skip not needed data
  97889. offset += header.id_length;
  97890. var use_rle = false;
  97891. var use_pal = false;
  97892. var use_grey = false;
  97893. // Get some informations.
  97894. switch (header.image_type) {
  97895. case TGATools._TYPE_RLE_INDEXED:
  97896. use_rle = true;
  97897. case TGATools._TYPE_INDEXED:
  97898. use_pal = true;
  97899. break;
  97900. case TGATools._TYPE_RLE_RGB:
  97901. use_rle = true;
  97902. case TGATools._TYPE_RGB:
  97903. // use_rgb = true;
  97904. break;
  97905. case TGATools._TYPE_RLE_GREY:
  97906. use_rle = true;
  97907. case TGATools._TYPE_GREY:
  97908. use_grey = true;
  97909. break;
  97910. }
  97911. var pixel_data;
  97912. // var numAlphaBits = header.flags & 0xf;
  97913. var pixel_size = header.pixel_size >> 3;
  97914. var pixel_total = header.width * header.height * pixel_size;
  97915. // Read palettes
  97916. var palettes;
  97917. if (use_pal) {
  97918. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  97919. }
  97920. // Read LRE
  97921. if (use_rle) {
  97922. pixel_data = new Uint8Array(pixel_total);
  97923. var c, count, i;
  97924. var localOffset = 0;
  97925. var pixels = new Uint8Array(pixel_size);
  97926. while (offset < pixel_total && localOffset < pixel_total) {
  97927. c = data[offset++];
  97928. count = (c & 0x7f) + 1;
  97929. // RLE pixels
  97930. if (c & 0x80) {
  97931. // Bind pixel tmp array
  97932. for (i = 0; i < pixel_size; ++i) {
  97933. pixels[i] = data[offset++];
  97934. }
  97935. // Copy pixel array
  97936. for (i = 0; i < count; ++i) {
  97937. pixel_data.set(pixels, localOffset + i * pixel_size);
  97938. }
  97939. localOffset += pixel_size * count;
  97940. }
  97941. // Raw pixels
  97942. else {
  97943. count *= pixel_size;
  97944. for (i = 0; i < count; ++i) {
  97945. pixel_data[localOffset + i] = data[offset++];
  97946. }
  97947. localOffset += count;
  97948. }
  97949. }
  97950. }
  97951. // RAW Pixels
  97952. else {
  97953. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  97954. }
  97955. // Load to texture
  97956. var x_start, y_start, x_step, y_step, y_end, x_end;
  97957. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  97958. default:
  97959. case TGATools._ORIGIN_UL:
  97960. x_start = 0;
  97961. x_step = 1;
  97962. x_end = header.width;
  97963. y_start = 0;
  97964. y_step = 1;
  97965. y_end = header.height;
  97966. break;
  97967. case TGATools._ORIGIN_BL:
  97968. x_start = 0;
  97969. x_step = 1;
  97970. x_end = header.width;
  97971. y_start = header.height - 1;
  97972. y_step = -1;
  97973. y_end = -1;
  97974. break;
  97975. case TGATools._ORIGIN_UR:
  97976. x_start = header.width - 1;
  97977. x_step = -1;
  97978. x_end = -1;
  97979. y_start = 0;
  97980. y_step = 1;
  97981. y_end = header.height;
  97982. break;
  97983. case TGATools._ORIGIN_BR:
  97984. x_start = header.width - 1;
  97985. x_step = -1;
  97986. x_end = -1;
  97987. y_start = header.height - 1;
  97988. y_step = -1;
  97989. y_end = -1;
  97990. break;
  97991. }
  97992. // Load the specify method
  97993. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  97994. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  97995. var engine = texture.getEngine();
  97996. engine._uploadDataToTextureDirectly(texture, imageData);
  97997. };
  97998. /** @hidden */
  97999. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98000. var image = pixel_data, colormap = palettes;
  98001. var width = header.width, height = header.height;
  98002. var color, i = 0, x, y;
  98003. var imageData = new Uint8Array(width * height * 4);
  98004. for (y = y_start; y !== y_end; y += y_step) {
  98005. for (x = x_start; x !== x_end; x += x_step, i++) {
  98006. color = image[i];
  98007. imageData[(x + width * y) * 4 + 3] = 255;
  98008. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  98009. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  98010. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  98011. }
  98012. }
  98013. return imageData;
  98014. };
  98015. /** @hidden */
  98016. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98017. var image = pixel_data;
  98018. var width = header.width, height = header.height;
  98019. var color, i = 0, x, y;
  98020. var imageData = new Uint8Array(width * height * 4);
  98021. for (y = y_start; y !== y_end; y += y_step) {
  98022. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98023. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  98024. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  98025. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  98026. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  98027. imageData[(x + width * y) * 4 + 0] = r;
  98028. imageData[(x + width * y) * 4 + 1] = g;
  98029. imageData[(x + width * y) * 4 + 2] = b;
  98030. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  98031. }
  98032. }
  98033. return imageData;
  98034. };
  98035. /** @hidden */
  98036. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98037. var image = pixel_data;
  98038. var width = header.width, height = header.height;
  98039. var i = 0, x, y;
  98040. var imageData = new Uint8Array(width * height * 4);
  98041. for (y = y_start; y !== y_end; y += y_step) {
  98042. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  98043. imageData[(x + width * y) * 4 + 3] = 255;
  98044. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98045. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98046. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98047. }
  98048. }
  98049. return imageData;
  98050. };
  98051. /** @hidden */
  98052. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98053. var image = pixel_data;
  98054. var width = header.width, height = header.height;
  98055. var i = 0, x, y;
  98056. var imageData = new Uint8Array(width * height * 4);
  98057. for (y = y_start; y !== y_end; y += y_step) {
  98058. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  98059. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98060. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  98061. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  98062. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  98063. }
  98064. }
  98065. return imageData;
  98066. };
  98067. /** @hidden */
  98068. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98069. var image = pixel_data;
  98070. var width = header.width, height = header.height;
  98071. var color, i = 0, x, y;
  98072. var imageData = new Uint8Array(width * height * 4);
  98073. for (y = y_start; y !== y_end; y += y_step) {
  98074. for (x = x_start; x !== x_end; x += x_step, i++) {
  98075. color = image[i];
  98076. imageData[(x + width * y) * 4 + 0] = color;
  98077. imageData[(x + width * y) * 4 + 1] = color;
  98078. imageData[(x + width * y) * 4 + 2] = color;
  98079. imageData[(x + width * y) * 4 + 3] = 255;
  98080. }
  98081. }
  98082. return imageData;
  98083. };
  98084. /** @hidden */
  98085. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  98086. var image = pixel_data;
  98087. var width = header.width, height = header.height;
  98088. var i = 0, x, y;
  98089. var imageData = new Uint8Array(width * height * 4);
  98090. for (y = y_start; y !== y_end; y += y_step) {
  98091. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  98092. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  98093. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  98094. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  98095. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  98096. }
  98097. }
  98098. return imageData;
  98099. };
  98100. //private static _TYPE_NO_DATA = 0;
  98101. TGATools._TYPE_INDEXED = 1;
  98102. TGATools._TYPE_RGB = 2;
  98103. TGATools._TYPE_GREY = 3;
  98104. TGATools._TYPE_RLE_INDEXED = 9;
  98105. TGATools._TYPE_RLE_RGB = 10;
  98106. TGATools._TYPE_RLE_GREY = 11;
  98107. TGATools._ORIGIN_MASK = 0x30;
  98108. TGATools._ORIGIN_SHIFT = 0x04;
  98109. TGATools._ORIGIN_BL = 0x00;
  98110. TGATools._ORIGIN_BR = 0x01;
  98111. TGATools._ORIGIN_UL = 0x02;
  98112. TGATools._ORIGIN_UR = 0x03;
  98113. return TGATools;
  98114. }());
  98115. BABYLON.TGATools = TGATools;
  98116. })(BABYLON || (BABYLON = {}));
  98117. //# sourceMappingURL=babylon.tga.js.map
  98118. var BABYLON;
  98119. (function (BABYLON) {
  98120. /**
  98121. * Implementation of the TGA Texture Loader.
  98122. */
  98123. var TGATextureLoader = /** @class */ (function () {
  98124. function TGATextureLoader() {
  98125. /**
  98126. * Defines wether the loader supports cascade loading the different faces.
  98127. */
  98128. this.supportCascades = false;
  98129. }
  98130. /**
  98131. * This returns if the loader support the current file information.
  98132. * @param extension defines the file extension of the file being loaded
  98133. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98134. * @param fallback defines the fallback internal texture if any
  98135. * @param isBase64 defines whether the texture is encoded as a base64
  98136. * @param isBuffer defines whether the texture data are stored as a buffer
  98137. * @returns true if the loader can load the specified file
  98138. */
  98139. TGATextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98140. return extension.indexOf(".tga") === 0;
  98141. };
  98142. /**
  98143. * Transform the url before loading if required.
  98144. * @param rootUrl the url of the texture
  98145. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98146. * @returns the transformed texture
  98147. */
  98148. TGATextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98149. return rootUrl;
  98150. };
  98151. /**
  98152. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98153. * @param rootUrl the url of the texture
  98154. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98155. * @returns the fallback texture
  98156. */
  98157. TGATextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98158. return null;
  98159. };
  98160. /**
  98161. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98162. * @param data contains the texture data
  98163. * @param texture defines the BabylonJS internal texture
  98164. * @param createPolynomials will be true if polynomials have been requested
  98165. * @param onLoad defines the callback to trigger once the texture is ready
  98166. * @param onError defines the callback to trigger in case of error
  98167. */
  98168. TGATextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98169. throw ".env not supported in Cube.";
  98170. };
  98171. /**
  98172. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98173. * @param data contains the texture data
  98174. * @param texture defines the BabylonJS internal texture
  98175. * @param callback defines the method to call once ready to upload
  98176. */
  98177. TGATextureLoader.prototype.loadData = function (data, texture, callback) {
  98178. var uintData = new Uint8Array(data);
  98179. var header = BABYLON.TGATools.GetTGAHeader(uintData);
  98180. callback(header.width, header.height, texture.generateMipMaps, false, function () {
  98181. BABYLON.TGATools.UploadContent(texture, uintData);
  98182. });
  98183. };
  98184. return TGATextureLoader;
  98185. }());
  98186. // Register the loader.
  98187. BABYLON.Engine._TextureLoaders.push(new TGATextureLoader());
  98188. })(BABYLON || (BABYLON = {}));
  98189. //# sourceMappingURL=babylon.tgaTextureLoader.js.map
  98190. var BABYLON;
  98191. (function (BABYLON) {
  98192. /**
  98193. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  98194. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  98195. */
  98196. var KhronosTextureContainer = /** @class */ (function () {
  98197. /**
  98198. * Creates a new KhronosTextureContainer
  98199. * @param arrayBuffer contents of the KTX container file
  98200. * @param facesExpected should be either 1 or 6, based whether a cube texture or or
  98201. * @param threeDExpected provision for indicating that data should be a 3D texture, not implemented
  98202. * @param textureArrayExpected provision for indicating that data should be a texture array, not implemented
  98203. */
  98204. function KhronosTextureContainer(
  98205. /** contents of the KTX container file */
  98206. arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  98207. this.arrayBuffer = arrayBuffer;
  98208. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  98209. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  98210. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  98211. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  98212. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  98213. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  98214. BABYLON.Tools.Error("texture missing KTX identifier");
  98215. return;
  98216. }
  98217. // load the reset of the header in native 32 bit int
  98218. var header = new Int32Array(this.arrayBuffer, 12, 13);
  98219. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  98220. var oppositeEndianess = header[0] === 0x01020304;
  98221. // read all the header elements in order they exist in the file, without modification (sans endainness)
  98222. this.glType = oppositeEndianess ? this.switchEndianness(header[1]) : header[1]; // must be 0 for compressed textures
  98223. this.glTypeSize = oppositeEndianess ? this.switchEndianness(header[2]) : header[2]; // must be 1 for compressed textures
  98224. this.glFormat = oppositeEndianess ? this.switchEndianness(header[3]) : header[3]; // must be 0 for compressed textures
  98225. this.glInternalFormat = oppositeEndianess ? this.switchEndianness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  98226. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndianness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  98227. this.pixelWidth = oppositeEndianess ? this.switchEndianness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  98228. this.pixelHeight = oppositeEndianess ? this.switchEndianness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  98229. this.pixelDepth = oppositeEndianess ? this.switchEndianness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  98230. this.numberOfArrayElements = oppositeEndianess ? this.switchEndianness(header[9]) : header[9]; // used for texture arrays
  98231. this.numberOfFaces = oppositeEndianess ? this.switchEndianness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  98232. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndianness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  98233. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndianness(header[12]) : header[12]; // the amount of space after the header for meta-data
  98234. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  98235. if (this.glType !== 0) {
  98236. BABYLON.Tools.Error("only compressed formats currently supported");
  98237. return;
  98238. }
  98239. else {
  98240. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  98241. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  98242. }
  98243. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  98244. BABYLON.Tools.Error("only 2D textures currently supported");
  98245. return;
  98246. }
  98247. if (this.numberOfArrayElements !== 0) {
  98248. BABYLON.Tools.Error("texture arrays not currently supported");
  98249. return;
  98250. }
  98251. if (this.numberOfFaces !== facesExpected) {
  98252. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  98253. return;
  98254. }
  98255. // we now have a completely validated file, so could use existence of loadType as success
  98256. // would need to make this more elaborate & adjust checks above to support more than one load type
  98257. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  98258. }
  98259. //
  98260. /**
  98261. * Revert the endianness of a value.
  98262. * Not as fast hardware based, but will probably never need to use
  98263. * @param val defines the value to convert
  98264. * @returns the new value
  98265. */
  98266. KhronosTextureContainer.prototype.switchEndianness = function (val) {
  98267. return ((val & 0xFF) << 24)
  98268. | ((val & 0xFF00) << 8)
  98269. | ((val >> 8) & 0xFF00)
  98270. | ((val >> 24) & 0xFF);
  98271. };
  98272. /**
  98273. * Uploads KTX content to a Babylon Texture.
  98274. * It is assumed that the texture has already been created & is currently bound
  98275. * @hidden
  98276. */
  98277. KhronosTextureContainer.prototype.uploadLevels = function (texture, loadMipmaps) {
  98278. switch (this.loadType) {
  98279. case KhronosTextureContainer.COMPRESSED_2D:
  98280. this._upload2DCompressedLevels(texture, loadMipmaps);
  98281. break;
  98282. case KhronosTextureContainer.TEX_2D:
  98283. case KhronosTextureContainer.COMPRESSED_3D:
  98284. case KhronosTextureContainer.TEX_3D:
  98285. }
  98286. };
  98287. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (texture, loadMipmaps) {
  98288. // initialize width & height for level 1
  98289. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  98290. var width = this.pixelWidth;
  98291. var height = this.pixelHeight;
  98292. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  98293. for (var level = 0; level < mipmapCount; level++) {
  98294. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  98295. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  98296. for (var face = 0; face < this.numberOfFaces; face++) {
  98297. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  98298. var engine = texture.getEngine();
  98299. engine._uploadCompressedDataToTextureDirectly(texture, this.glInternalFormat, width, height, byteArray, face, level);
  98300. dataOffset += imageSize; // add size of the image for the next face/mipmap
  98301. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  98302. }
  98303. width = Math.max(1.0, width * 0.5);
  98304. height = Math.max(1.0, height * 0.5);
  98305. }
  98306. };
  98307. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  98308. // load types
  98309. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  98310. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  98311. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  98312. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  98313. return KhronosTextureContainer;
  98314. }());
  98315. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  98316. })(BABYLON || (BABYLON = {}));
  98317. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  98318. var BABYLON;
  98319. (function (BABYLON) {
  98320. /**
  98321. * Implementation of the KTX Texture Loader.
  98322. */
  98323. var KTXTextureLoader = /** @class */ (function () {
  98324. function KTXTextureLoader() {
  98325. /**
  98326. * Defines wether the loader supports cascade loading the different faces.
  98327. */
  98328. this.supportCascades = false;
  98329. }
  98330. /**
  98331. * This returns if the loader support the current file information.
  98332. * @param extension defines the file extension of the file being loaded
  98333. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98334. * @param fallback defines the fallback internal texture if any
  98335. * @param isBase64 defines whether the texture is encoded as a base64
  98336. * @param isBuffer defines whether the texture data are stored as a buffer
  98337. * @returns true if the loader can load the specified file
  98338. */
  98339. KTXTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98340. if (textureFormatInUse && !isBase64 && !fallback && !isBuffer) {
  98341. return true;
  98342. }
  98343. return false;
  98344. };
  98345. /**
  98346. * Transform the url before loading if required.
  98347. * @param rootUrl the url of the texture
  98348. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98349. * @returns the transformed texture
  98350. */
  98351. KTXTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98352. var lastDot = rootUrl.lastIndexOf('.');
  98353. return (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + textureFormatInUse;
  98354. };
  98355. /**
  98356. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98357. * @param rootUrl the url of the texture
  98358. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98359. * @returns the fallback texture
  98360. */
  98361. KTXTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98362. // remove the format appended to the rootUrl in the original createCubeTexture call.
  98363. var exp = new RegExp("" + textureFormatInUse + "$");
  98364. return rootUrl.replace(exp, "");
  98365. };
  98366. /**
  98367. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98368. * @param data contains the texture data
  98369. * @param texture defines the BabylonJS internal texture
  98370. * @param createPolynomials will be true if polynomials have been requested
  98371. * @param onLoad defines the callback to trigger once the texture is ready
  98372. * @param onError defines the callback to trigger in case of error
  98373. */
  98374. KTXTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98375. if (Array.isArray(data)) {
  98376. return;
  98377. }
  98378. var engine = texture.getEngine();
  98379. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  98380. var loadMipmap = ktx.numberOfMipmapLevels > 1 && texture.generateMipMaps;
  98381. engine._unpackFlipY(true);
  98382. ktx.uploadLevels(texture, texture.generateMipMaps);
  98383. texture.width = ktx.pixelWidth;
  98384. texture.height = ktx.pixelHeight;
  98385. engine._setCubeMapTextureParams(loadMipmap);
  98386. texture.isReady = true;
  98387. };
  98388. /**
  98389. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98390. * @param data contains the texture data
  98391. * @param texture defines the BabylonJS internal texture
  98392. * @param callback defines the method to call once ready to upload
  98393. */
  98394. KTXTextureLoader.prototype.loadData = function (data, texture, callback) {
  98395. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  98396. callback(ktx.pixelWidth, ktx.pixelHeight, false, true, function () {
  98397. ktx.uploadLevels(texture, texture.generateMipMaps);
  98398. });
  98399. };
  98400. return KTXTextureLoader;
  98401. }());
  98402. // Register the loader.
  98403. BABYLON.Engine._TextureLoaders.unshift(new KTXTextureLoader());
  98404. })(BABYLON || (BABYLON = {}));
  98405. //# sourceMappingURL=babylon.ktxTextureLoader.js.map
  98406. var BABYLON;
  98407. (function (BABYLON) {
  98408. /**
  98409. * Sets of helpers addressing the serialization and deserialization of environment texture
  98410. * stored in a BabylonJS env file.
  98411. * Those files are usually stored as .env files.
  98412. */
  98413. var EnvironmentTextureTools = /** @class */ (function () {
  98414. function EnvironmentTextureTools() {
  98415. }
  98416. /**
  98417. * Gets the environment info from an env file.
  98418. * @param data The array buffer containing the .env bytes.
  98419. * @returns the environment file info (the json header) if successfully parsed.
  98420. */
  98421. EnvironmentTextureTools.GetEnvInfo = function (data) {
  98422. var dataView = new DataView(data);
  98423. var pos = 0;
  98424. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98425. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  98426. BABYLON.Tools.Error('Not a babylon environment map');
  98427. return null;
  98428. }
  98429. }
  98430. // Read json manifest - collect characters up to null terminator
  98431. var manifestString = '';
  98432. var charCode = 0x00;
  98433. while ((charCode = dataView.getUint8(pos++))) {
  98434. manifestString += String.fromCharCode(charCode);
  98435. }
  98436. var manifest = JSON.parse(manifestString);
  98437. if (manifest.specular) {
  98438. // Extend the header with the position of the payload.
  98439. manifest.specular.specularDataPosition = pos;
  98440. // Fallback to 0.8 exactly if lodGenerationScale is not defined for backward compatibility.
  98441. manifest.specular.lodGenerationScale = manifest.specular.lodGenerationScale || 0.8;
  98442. }
  98443. return manifest;
  98444. };
  98445. /**
  98446. * Creates an environment texture from a loaded cube texture.
  98447. * @param texture defines the cube texture to convert in env file
  98448. * @return a promise containing the environment data if succesfull.
  98449. */
  98450. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  98451. var _this = this;
  98452. var internalTexture = texture.getInternalTexture();
  98453. if (!internalTexture) {
  98454. return Promise.reject("The cube texture is invalid.");
  98455. }
  98456. if (!texture._prefiltered) {
  98457. return Promise.reject("The cube texture is invalid (not prefiltered).");
  98458. }
  98459. var engine = internalTexture.getEngine();
  98460. if (engine && engine.premultipliedAlpha) {
  98461. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  98462. }
  98463. if (texture.textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  98464. return Promise.reject("The cube texture should allow HDR (Full Float or Half Float).");
  98465. }
  98466. var canvas = engine.getRenderingCanvas();
  98467. if (!canvas) {
  98468. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  98469. }
  98470. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98471. if (!engine.getCaps().textureFloatRender) {
  98472. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98473. if (!engine.getCaps().textureHalfFloatRender) {
  98474. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  98475. }
  98476. }
  98477. var cubeWidth = internalTexture.width;
  98478. var hostingScene = new BABYLON.Scene(engine);
  98479. var specularTextures = {};
  98480. var promises = [];
  98481. // Read and collect all mipmaps data from the cube.
  98482. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  98483. mipmapsCount = Math.round(mipmapsCount);
  98484. var _loop_1 = function (i) {
  98485. var faceWidth = Math.pow(2, mipmapsCount - i);
  98486. var _loop_2 = function (face) {
  98487. var data = texture.readPixels(face, i);
  98488. // Creates a temp texture with the face data.
  98489. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  98490. // And rgbdEncode them.
  98491. var promise = new Promise(function (resolve, reject) {
  98492. 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);
  98493. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98494. rgbdPostProcess.onApply = function (effect) {
  98495. effect._bindTexture("textureSampler", tempTexture);
  98496. };
  98497. // As the process needs to happen on the main canvas, keep track of the current size
  98498. var currentW = engine.getRenderWidth();
  98499. var currentH = engine.getRenderHeight();
  98500. // Set the desired size for the texture
  98501. engine.setSize(faceWidth, faceWidth);
  98502. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  98503. // Reading datas from WebGL
  98504. BABYLON.Tools.ToBlob(canvas, function (blob) {
  98505. var fileReader = new FileReader();
  98506. fileReader.onload = function (event) {
  98507. var arrayBuffer = event.target.result;
  98508. specularTextures[i * 6 + face] = arrayBuffer;
  98509. resolve();
  98510. };
  98511. fileReader.readAsArrayBuffer(blob);
  98512. });
  98513. // Reapply the previous canvas size
  98514. engine.setSize(currentW, currentH);
  98515. });
  98516. });
  98517. promises.push(promise);
  98518. };
  98519. // All faces of the cube.
  98520. for (var face = 0; face < 6; face++) {
  98521. _loop_2(face);
  98522. }
  98523. };
  98524. for (var i = 0; i <= mipmapsCount; i++) {
  98525. _loop_1(i);
  98526. }
  98527. // Once all the textures haves been collected as RGBD stored in PNGs
  98528. return Promise.all(promises).then(function () {
  98529. // We can delete the hosting scene keeping track of all the creation objects
  98530. hostingScene.dispose();
  98531. // Creates the json header for the env texture
  98532. var info = {
  98533. version: 1,
  98534. width: cubeWidth,
  98535. irradiance: _this._CreateEnvTextureIrradiance(texture),
  98536. specular: {
  98537. mipmaps: [],
  98538. lodGenerationScale: texture.lodGenerationScale
  98539. }
  98540. };
  98541. // Sets the specular image data information
  98542. var position = 0;
  98543. for (var i = 0; i <= mipmapsCount; i++) {
  98544. for (var face = 0; face < 6; face++) {
  98545. var byteLength = specularTextures[i * 6 + face].byteLength;
  98546. info.specular.mipmaps.push({
  98547. length: byteLength,
  98548. position: position
  98549. });
  98550. position += byteLength;
  98551. }
  98552. }
  98553. // Encode the JSON as an array buffer
  98554. var infoString = JSON.stringify(info);
  98555. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  98556. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  98557. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  98558. infoView[i] = infoString.charCodeAt(i);
  98559. }
  98560. // Ends up with a null terminator for easier parsing
  98561. infoView[infoString.length] = 0x00;
  98562. // Computes the final required size and creates the storage
  98563. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  98564. var finalBuffer = new ArrayBuffer(totalSize);
  98565. var finalBufferView = new Uint8Array(finalBuffer);
  98566. var dataView = new DataView(finalBuffer);
  98567. // Copy the magic bytes identifying the file in
  98568. var pos = 0;
  98569. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  98570. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  98571. }
  98572. // Add the json info
  98573. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  98574. pos += infoBuffer.byteLength;
  98575. // Finally inserts the texture data
  98576. for (var i = 0; i <= mipmapsCount; i++) {
  98577. for (var face = 0; face < 6; face++) {
  98578. var dataBuffer = specularTextures[i * 6 + face];
  98579. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  98580. pos += dataBuffer.byteLength;
  98581. }
  98582. }
  98583. // Voila
  98584. return finalBuffer;
  98585. });
  98586. };
  98587. /**
  98588. * Creates a JSON representation of the spherical data.
  98589. * @param texture defines the texture containing the polynomials
  98590. * @return the JSON representation of the spherical info
  98591. */
  98592. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  98593. var polynmials = texture.sphericalPolynomial;
  98594. if (polynmials == null) {
  98595. return null;
  98596. }
  98597. return {
  98598. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  98599. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  98600. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  98601. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  98602. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  98603. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  98604. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  98605. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  98606. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  98607. };
  98608. };
  98609. /**
  98610. * Uploads the texture info contained in the env file to the GPU.
  98611. * @param texture defines the internal texture to upload to
  98612. * @param arrayBuffer defines the buffer cotaining the data to load
  98613. * @param info defines the texture info retrieved through the GetEnvInfo method
  98614. * @returns a promise
  98615. */
  98616. EnvironmentTextureTools.UploadEnvLevelsAsync = function (texture, arrayBuffer, info) {
  98617. if (info.version !== 1) {
  98618. throw new Error("Unsupported babylon environment map version \"" + info.version + "\"");
  98619. }
  98620. var specularInfo = info.specular;
  98621. if (!specularInfo) {
  98622. // Nothing else parsed so far
  98623. return Promise.resolve();
  98624. }
  98625. // Double checks the enclosed info
  98626. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  98627. mipmapsCount = Math.round(mipmapsCount) + 1;
  98628. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  98629. throw new Error("Unsupported specular mipmaps number \"" + specularInfo.mipmaps.length + "\"");
  98630. }
  98631. texture._lodGenerationScale = specularInfo.lodGenerationScale;
  98632. var imageData = new Array(mipmapsCount);
  98633. for (var i = 0; i < mipmapsCount; i++) {
  98634. imageData[i] = new Array(6);
  98635. for (var face = 0; face < 6; face++) {
  98636. var imageInfo = specularInfo.mipmaps[i * 6 + face];
  98637. imageData[i][face] = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageInfo.position, imageInfo.length);
  98638. }
  98639. }
  98640. return EnvironmentTextureTools.UploadLevelsAsync(texture, imageData);
  98641. };
  98642. /**
  98643. * Uploads the levels of image data to the GPU.
  98644. * @param texture defines the internal texture to upload to
  98645. * @param imageData defines the array buffer views of image data [mipmap][face]
  98646. * @returns a promise
  98647. */
  98648. EnvironmentTextureTools.UploadLevelsAsync = function (texture, imageData) {
  98649. if (!BABYLON.Tools.IsExponentOfTwo(texture.width)) {
  98650. throw new Error("Texture size must be a power of two");
  98651. }
  98652. var mipmapsCount = Math.round(BABYLON.Scalar.Log2(texture.width)) + 1;
  98653. // Gets everything ready.
  98654. var engine = texture.getEngine();
  98655. var expandTexture = false;
  98656. var generateNonLODTextures = false;
  98657. var rgbdPostProcess = null;
  98658. var cubeRtt = null;
  98659. var lodTextures = null;
  98660. var caps = engine.getCaps();
  98661. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  98662. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  98663. texture.generateMipMaps = true;
  98664. engine.updateTextureSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE, texture);
  98665. // Add extra process if texture lod is not supported
  98666. if (!caps.textureLOD) {
  98667. expandTexture = false;
  98668. generateNonLODTextures = true;
  98669. lodTextures = {};
  98670. }
  98671. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  98672. else if (engine.webGLVersion < 2) {
  98673. expandTexture = false;
  98674. }
  98675. // If half float available we can uncompress the texture
  98676. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  98677. expandTexture = true;
  98678. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  98679. }
  98680. // If full float available we can uncompress the texture
  98681. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  98682. expandTexture = true;
  98683. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  98684. }
  98685. // Expand the texture if possible
  98686. if (expandTexture) {
  98687. // Simply run through the decode PP
  98688. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  98689. texture._isRGBD = false;
  98690. texture.invertY = false;
  98691. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  98692. generateDepthBuffer: false,
  98693. generateMipMaps: true,
  98694. generateStencilBuffer: false,
  98695. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  98696. type: texture.type,
  98697. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  98698. });
  98699. }
  98700. else {
  98701. texture._isRGBD = true;
  98702. texture.invertY = true;
  98703. // In case of missing support, applies the same patch than DDS files.
  98704. if (generateNonLODTextures) {
  98705. var mipSlices = 3;
  98706. var scale = texture._lodGenerationScale;
  98707. var offset = texture._lodGenerationOffset;
  98708. for (var i = 0; i < mipSlices; i++) {
  98709. //compute LOD from even spacing in smoothness (matching shader calculation)
  98710. var smoothness = i / (mipSlices - 1);
  98711. var roughness = 1 - smoothness;
  98712. var minLODIndex = offset; // roughness = 0
  98713. var maxLODIndex = (mipmapsCount - 1) * scale + offset; // roughness = 1 (mipmaps start from 0)
  98714. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  98715. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  98716. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  98717. glTextureFromLod.isCube = true;
  98718. glTextureFromLod.invertY = true;
  98719. glTextureFromLod.generateMipMaps = false;
  98720. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  98721. // Wrap in a base texture for easy binding.
  98722. var lodTexture = new BABYLON.BaseTexture(null);
  98723. lodTexture.isCube = true;
  98724. lodTexture._texture = glTextureFromLod;
  98725. lodTextures[mipmapIndex] = lodTexture;
  98726. switch (i) {
  98727. case 0:
  98728. texture._lodTextureLow = lodTexture;
  98729. break;
  98730. case 1:
  98731. texture._lodTextureMid = lodTexture;
  98732. break;
  98733. case 2:
  98734. texture._lodTextureHigh = lodTexture;
  98735. break;
  98736. }
  98737. }
  98738. }
  98739. }
  98740. var promises = [];
  98741. var _loop_3 = function (i) {
  98742. var _loop_4 = function (face) {
  98743. // Constructs an image element from image data
  98744. var bytes = imageData[i][face];
  98745. var blob = new Blob([bytes], { type: 'image/png' });
  98746. var url = URL.createObjectURL(blob);
  98747. var image = new Image();
  98748. image.src = url;
  98749. // Enqueue promise to upload to the texture.
  98750. var promise = new Promise(function (resolve, reject) {
  98751. image.onload = function () {
  98752. if (expandTexture) {
  98753. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  98754. reject(message);
  98755. }, image);
  98756. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  98757. // Uncompress the data to a RTT
  98758. rgbdPostProcess.onApply = function (effect) {
  98759. effect._bindTexture("textureSampler", tempTexture_1);
  98760. effect.setFloat2("scale", 1, 1);
  98761. };
  98762. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  98763. // Cleanup
  98764. engine.restoreDefaultFramebuffer();
  98765. tempTexture_1.dispose();
  98766. window.URL.revokeObjectURL(url);
  98767. resolve();
  98768. });
  98769. }
  98770. else {
  98771. engine._uploadImageToTexture(texture, image, face, i);
  98772. // Upload the face to the non lod texture support
  98773. if (generateNonLODTextures) {
  98774. var lodTexture = lodTextures[i];
  98775. if (lodTexture) {
  98776. engine._uploadImageToTexture(lodTexture._texture, image, face, 0);
  98777. }
  98778. }
  98779. resolve();
  98780. }
  98781. };
  98782. image.onerror = function (error) {
  98783. reject(error);
  98784. };
  98785. });
  98786. promises.push(promise);
  98787. };
  98788. // All faces
  98789. for (var face = 0; face < 6; face++) {
  98790. _loop_4(face);
  98791. }
  98792. };
  98793. // All mipmaps up to provided number of images
  98794. for (var i = 0; i < imageData.length; i++) {
  98795. _loop_3(i);
  98796. }
  98797. // Fill remaining mipmaps with black textures.
  98798. if (imageData.length < mipmapsCount) {
  98799. var data = void 0;
  98800. var size = Math.pow(2, mipmapsCount - 1 - imageData.length);
  98801. var dataLength = size * size * 4;
  98802. switch (texture.type) {
  98803. case BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT: {
  98804. data = new Uint8Array(dataLength);
  98805. break;
  98806. }
  98807. case BABYLON.Engine.TEXTURETYPE_HALF_FLOAT: {
  98808. data = new Uint16Array(dataLength);
  98809. break;
  98810. }
  98811. case BABYLON.Engine.TEXTURETYPE_FLOAT: {
  98812. data = new Float32Array(dataLength);
  98813. break;
  98814. }
  98815. }
  98816. for (var i = imageData.length; i < mipmapsCount; i++) {
  98817. for (var face = 0; face < 6; face++) {
  98818. engine._uploadArrayBufferViewToTexture(texture, data, face, i);
  98819. }
  98820. }
  98821. }
  98822. // Once all done, finishes the cleanup and return
  98823. return Promise.all(promises).then(function () {
  98824. // Release temp RTT.
  98825. if (cubeRtt) {
  98826. engine._releaseFramebufferObjects(cubeRtt);
  98827. cubeRtt._swapAndDie(texture);
  98828. }
  98829. // Release temp Post Process.
  98830. if (rgbdPostProcess) {
  98831. rgbdPostProcess.dispose();
  98832. }
  98833. // Flag internal texture as ready in case they are in use.
  98834. if (generateNonLODTextures) {
  98835. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  98836. texture._lodTextureHigh._texture.isReady = true;
  98837. }
  98838. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  98839. texture._lodTextureMid._texture.isReady = true;
  98840. }
  98841. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  98842. texture._lodTextureLow._texture.isReady = true;
  98843. }
  98844. }
  98845. });
  98846. };
  98847. /**
  98848. * Uploads spherical polynomials information to the texture.
  98849. * @param texture defines the texture we are trying to upload the information to
  98850. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  98851. */
  98852. EnvironmentTextureTools.UploadEnvSpherical = function (texture, info) {
  98853. if (info.version !== 1) {
  98854. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  98855. }
  98856. var irradianceInfo = info.irradiance;
  98857. if (!irradianceInfo) {
  98858. return;
  98859. }
  98860. var sp = new BABYLON.SphericalPolynomial();
  98861. BABYLON.Vector3.FromArrayToRef(irradianceInfo.x, 0, sp.x);
  98862. BABYLON.Vector3.FromArrayToRef(irradianceInfo.y, 0, sp.y);
  98863. BABYLON.Vector3.FromArrayToRef(irradianceInfo.z, 0, sp.z);
  98864. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xx, 0, sp.xx);
  98865. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yy, 0, sp.yy);
  98866. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zz, 0, sp.zz);
  98867. BABYLON.Vector3.FromArrayToRef(irradianceInfo.yz, 0, sp.yz);
  98868. BABYLON.Vector3.FromArrayToRef(irradianceInfo.zx, 0, sp.zx);
  98869. BABYLON.Vector3.FromArrayToRef(irradianceInfo.xy, 0, sp.xy);
  98870. texture._sphericalPolynomial = sp;
  98871. };
  98872. /**
  98873. * Magic number identifying the env file.
  98874. */
  98875. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  98876. return EnvironmentTextureTools;
  98877. }());
  98878. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  98879. })(BABYLON || (BABYLON = {}));
  98880. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  98881. var BABYLON;
  98882. (function (BABYLON) {
  98883. /**
  98884. * Implementation of the ENV Texture Loader.
  98885. */
  98886. var ENVTextureLoader = /** @class */ (function () {
  98887. function ENVTextureLoader() {
  98888. /**
  98889. * Defines wether the loader supports cascade loading the different faces.
  98890. */
  98891. this.supportCascades = false;
  98892. }
  98893. /**
  98894. * This returns if the loader support the current file information.
  98895. * @param extension defines the file extension of the file being loaded
  98896. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98897. * @param fallback defines the fallback internal texture if any
  98898. * @param isBase64 defines whether the texture is encoded as a base64
  98899. * @param isBuffer defines whether the texture data are stored as a buffer
  98900. * @returns true if the loader can load the specified file
  98901. */
  98902. ENVTextureLoader.prototype.canLoad = function (extension, textureFormatInUse, fallback, isBase64, isBuffer) {
  98903. return extension.indexOf(".env") === 0;
  98904. };
  98905. /**
  98906. * Transform the url before loading if required.
  98907. * @param rootUrl the url of the texture
  98908. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98909. * @returns the transformed texture
  98910. */
  98911. ENVTextureLoader.prototype.transformUrl = function (rootUrl, textureFormatInUse) {
  98912. return rootUrl;
  98913. };
  98914. /**
  98915. * Gets the fallback url in case the load fail. This can return null to allow the default fallback mecanism to work
  98916. * @param rootUrl the url of the texture
  98917. * @param textureFormatInUse defines the current compressed format in use iun the engine
  98918. * @returns the fallback texture
  98919. */
  98920. ENVTextureLoader.prototype.getFallbackTextureUrl = function (rootUrl, textureFormatInUse) {
  98921. return null;
  98922. };
  98923. /**
  98924. * Uploads the cube texture data to the WebGl Texture. It has alreday been bound.
  98925. * @param data contains the texture data
  98926. * @param texture defines the BabylonJS internal texture
  98927. * @param createPolynomials will be true if polynomials have been requested
  98928. * @param onLoad defines the callback to trigger once the texture is ready
  98929. * @param onError defines the callback to trigger in case of error
  98930. */
  98931. ENVTextureLoader.prototype.loadCubeData = function (data, texture, createPolynomials, onLoad, onError) {
  98932. if (Array.isArray(data)) {
  98933. return;
  98934. }
  98935. data = data;
  98936. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  98937. if (info) {
  98938. texture.width = info.width;
  98939. texture.height = info.width;
  98940. BABYLON.EnvironmentTextureTools.UploadEnvSpherical(texture, info);
  98941. BABYLON.EnvironmentTextureTools.UploadEnvLevelsAsync(texture, data, info).then(function () {
  98942. texture.isReady = true;
  98943. if (onLoad) {
  98944. onLoad();
  98945. }
  98946. });
  98947. }
  98948. else if (onError) {
  98949. onError("Can not parse the environment file", null);
  98950. }
  98951. };
  98952. /**
  98953. * Uploads the 2D texture data to the WebGl Texture. It has alreday been bound once in the callback.
  98954. * @param data contains the texture data
  98955. * @param texture defines the BabylonJS internal texture
  98956. * @param callback defines the method to call once ready to upload
  98957. */
  98958. ENVTextureLoader.prototype.loadData = function (data, texture, callback) {
  98959. throw ".env not supported in 2d.";
  98960. };
  98961. return ENVTextureLoader;
  98962. }());
  98963. // Register the loader.
  98964. BABYLON.Engine._TextureLoaders.push(new ENVTextureLoader());
  98965. })(BABYLON || (BABYLON = {}));
  98966. //# sourceMappingURL=babylon.envTextureLoader.js.map
  98967. var BABYLON;
  98968. (function (BABYLON) {
  98969. /**
  98970. * Renders a layer on top of an existing scene
  98971. */
  98972. var UtilityLayerRenderer = /** @class */ (function () {
  98973. /**
  98974. * Instantiates a UtilityLayerRenderer
  98975. * @param originalScene the original scene that will be rendered on top of
  98976. */
  98977. function UtilityLayerRenderer(
  98978. /** the original scene that will be rendered on top of */
  98979. originalScene) {
  98980. var _this = this;
  98981. this.originalScene = originalScene;
  98982. this._pointerCaptures = {};
  98983. this._lastPointerEvents = {};
  98984. /**
  98985. * If the utility layer should automatically be rendered on top of existing scene
  98986. */
  98987. this.shouldRender = true;
  98988. /**
  98989. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  98990. */
  98991. this.onlyCheckPointerDownEvents = true;
  98992. /**
  98993. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  98994. */
  98995. this.processAllEvents = false;
  98996. /**
  98997. * Observable raised when the pointer move from the utility layer scene to the main scene
  98998. */
  98999. this.onPointerOutObservable = new BABYLON.Observable();
  99000. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  99001. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  99002. this.utilityLayerScene.useRightHandedSystem = originalScene.useRightHandedSystem;
  99003. this.utilityLayerScene._allowPostProcessClearColor = false;
  99004. originalScene.getEngine().scenes.pop();
  99005. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  99006. this.utilityLayerScene.detachControl();
  99007. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  99008. if (!_this.processAllEvents) {
  99009. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  99010. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  99011. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  99012. return;
  99013. }
  99014. }
  99015. var pointerEvent = (prePointerInfo.event);
  99016. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  99017. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99018. return;
  99019. }
  99020. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  99021. if (!prePointerInfo.ray && utilityScenePick) {
  99022. prePointerInfo.ray = utilityScenePick.ray;
  99023. }
  99024. // always fire the prepointer oversvable
  99025. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  99026. // allow every non pointer down event to flow to the utility layer
  99027. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  99028. if (!prePointerInfo.skipOnPointerObservable) {
  99029. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99030. }
  99031. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  99032. _this._pointerCaptures[pointerEvent.pointerId] = false;
  99033. }
  99034. return;
  99035. }
  99036. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  99037. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  99038. if (utilityScenePick && utilityScenePick.hit) {
  99039. if (!prePointerInfo.skipOnPointerObservable) {
  99040. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  99041. }
  99042. prePointerInfo.skipOnPointerObservable = true;
  99043. }
  99044. }
  99045. else {
  99046. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  99047. var pointerEvent_1 = (prePointerInfo.event);
  99048. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  99049. if (originalScenePick && utilityScenePick) {
  99050. // No pick in utility scene
  99051. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  99052. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99053. // We touched an utility mesh present in the main scene
  99054. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99055. prePointerInfo.skipOnPointerObservable = true;
  99056. }
  99057. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99058. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  99059. }
  99060. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99061. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99062. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99063. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99064. }
  99065. }
  99066. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  99067. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  99068. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  99069. // If a previous utility layer set this, do not unset this
  99070. if (!prePointerInfo.skipOnPointerObservable) {
  99071. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  99072. }
  99073. }
  99074. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  99075. // We have a pick in both scenes but main is closer than utility
  99076. // We touched an utility mesh present in the main scene
  99077. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  99078. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  99079. prePointerInfo.skipOnPointerObservable = true;
  99080. }
  99081. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  99082. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  99083. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  99084. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  99085. }
  99086. }
  99087. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  99088. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  99089. }
  99090. }
  99091. }
  99092. });
  99093. // Render directly on top of existing scene without clearing
  99094. this.utilityLayerScene.autoClear = false;
  99095. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  99096. if (_this.shouldRender) {
  99097. _this.render();
  99098. }
  99099. });
  99100. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  99101. _this.dispose();
  99102. });
  99103. this._updateCamera();
  99104. }
  99105. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  99106. /**
  99107. * 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)
  99108. */
  99109. get: function () {
  99110. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  99111. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99112. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99113. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99114. });
  99115. }
  99116. return UtilityLayerRenderer._DefaultUtilityLayer;
  99117. },
  99118. enumerable: true,
  99119. configurable: true
  99120. });
  99121. Object.defineProperty(UtilityLayerRenderer, "DefaultKeepDepthUtilityLayer", {
  99122. /**
  99123. * 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)
  99124. */
  99125. get: function () {
  99126. if (UtilityLayerRenderer._DefaultKeepDepthUtilityLayer == null) {
  99127. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  99128. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  99129. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer.originalScene.onDisposeObservable.addOnce(function () {
  99130. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99131. });
  99132. }
  99133. return UtilityLayerRenderer._DefaultKeepDepthUtilityLayer;
  99134. },
  99135. enumerable: true,
  99136. configurable: true
  99137. });
  99138. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  99139. if (!prePointerInfo.skipOnPointerObservable) {
  99140. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  99141. this._lastPointerEvents[pointerEvent.pointerId] = true;
  99142. }
  99143. };
  99144. /**
  99145. * Renders the utility layers scene on top of the original scene
  99146. */
  99147. UtilityLayerRenderer.prototype.render = function () {
  99148. this._updateCamera();
  99149. if (this.utilityLayerScene.activeCamera) {
  99150. // Set the camera's scene to utility layers scene
  99151. var oldScene = this.utilityLayerScene.activeCamera.getScene();
  99152. var camera = this.utilityLayerScene.activeCamera;
  99153. camera._scene = this.utilityLayerScene;
  99154. if (camera.leftCamera) {
  99155. camera.leftCamera._scene = this.utilityLayerScene;
  99156. }
  99157. if (camera.rightCamera) {
  99158. camera.rightCamera._scene = this.utilityLayerScene;
  99159. }
  99160. this.utilityLayerScene.render(false);
  99161. // Reset camera's scene back to original
  99162. camera._scene = oldScene;
  99163. if (camera.leftCamera) {
  99164. camera.leftCamera._scene = oldScene;
  99165. }
  99166. if (camera.rightCamera) {
  99167. camera.rightCamera._scene = oldScene;
  99168. }
  99169. }
  99170. };
  99171. /**
  99172. * Disposes of the renderer
  99173. */
  99174. UtilityLayerRenderer.prototype.dispose = function () {
  99175. this.onPointerOutObservable.clear();
  99176. if (this._afterRenderObserver) {
  99177. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  99178. }
  99179. if (this._sceneDisposeObserver) {
  99180. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  99181. }
  99182. if (this._originalPointerObserver) {
  99183. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  99184. }
  99185. this.utilityLayerScene.dispose();
  99186. };
  99187. UtilityLayerRenderer.prototype._updateCamera = function () {
  99188. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  99189. };
  99190. UtilityLayerRenderer._DefaultUtilityLayer = null;
  99191. UtilityLayerRenderer._DefaultKeepDepthUtilityLayer = null;
  99192. return UtilityLayerRenderer;
  99193. }());
  99194. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  99195. })(BABYLON || (BABYLON = {}));
  99196. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  99197. //# sourceMappingURL=babylon.behavior.js.map
  99198. var BABYLON;
  99199. (function (BABYLON) {
  99200. /**
  99201. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  99202. */
  99203. var PointerDragBehavior = /** @class */ (function () {
  99204. /**
  99205. * Creates a pointer drag behavior that can be attached to a mesh
  99206. * @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)
  99207. */
  99208. function PointerDragBehavior(options) {
  99209. /**
  99210. * 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)
  99211. */
  99212. this.maxDragAngle = 0;
  99213. /**
  99214. * @hidden
  99215. */
  99216. this._useAlternatePickedPointAboveMaxDragAngle = false;
  99217. /**
  99218. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99219. */
  99220. this.currentDraggingPointerID = -1;
  99221. /**
  99222. * If the behavior is currently in a dragging state
  99223. */
  99224. this.dragging = false;
  99225. /**
  99226. * 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)
  99227. */
  99228. this.dragDeltaRatio = 0.2;
  99229. /**
  99230. * If the drag plane orientation should be updated during the dragging (Default: true)
  99231. */
  99232. this.updateDragPlane = true;
  99233. // Debug mode will display drag planes to help visualize behavior
  99234. this._debugMode = false;
  99235. this._moving = false;
  99236. /**
  99237. * Fires each time the attached mesh is dragged with the pointer
  99238. * * delta between last drag position and current drag position in world space
  99239. * * dragDistance along the drag axis
  99240. * * dragPlaneNormal normal of the current drag plane used during the drag
  99241. * * dragPlanePoint in world space where the drag intersects the drag plane
  99242. */
  99243. this.onDragObservable = new BABYLON.Observable();
  99244. /**
  99245. * Fires each time a drag begins (eg. mouse down on mesh)
  99246. */
  99247. this.onDragStartObservable = new BABYLON.Observable();
  99248. /**
  99249. * Fires each time a drag ends (eg. mouse release after drag)
  99250. */
  99251. this.onDragEndObservable = new BABYLON.Observable();
  99252. /**
  99253. * If the attached mesh should be moved when dragged
  99254. */
  99255. this.moveAttached = true;
  99256. /**
  99257. * If the drag behavior will react to drag events (Default: true)
  99258. */
  99259. this.enabled = true;
  99260. /**
  99261. * If camera controls should be detached during the drag
  99262. */
  99263. this.detachCameraControls = true;
  99264. /**
  99265. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  99266. */
  99267. this.useObjectOrienationForDragging = true;
  99268. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  99269. this._alternatePickedPoint = new BABYLON.Vector3(0, 0, 0);
  99270. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  99271. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99272. this._attachedElement = null;
  99273. this._startDragRay = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99274. this._lastPointerRay = {};
  99275. this._dragDelta = new BABYLON.Vector3();
  99276. // Variables to avoid instantiation in the below method
  99277. this._pointA = new BABYLON.Vector3(0, 0, 0);
  99278. this._pointB = new BABYLON.Vector3(0, 0, 0);
  99279. this._pointC = new BABYLON.Vector3(0, 0, 0);
  99280. this._lineA = new BABYLON.Vector3(0, 0, 0);
  99281. this._lineB = new BABYLON.Vector3(0, 0, 0);
  99282. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  99283. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  99284. this._options = options ? options : {};
  99285. var optionCount = 0;
  99286. if (this._options.dragAxis) {
  99287. optionCount++;
  99288. }
  99289. if (this._options.dragPlaneNormal) {
  99290. optionCount++;
  99291. }
  99292. if (optionCount > 1) {
  99293. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  99294. }
  99295. }
  99296. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  99297. /**
  99298. * The name of the behavior
  99299. */
  99300. get: function () {
  99301. return "PointerDrag";
  99302. },
  99303. enumerable: true,
  99304. configurable: true
  99305. });
  99306. /**
  99307. * Initializes the behavior
  99308. */
  99309. PointerDragBehavior.prototype.init = function () { };
  99310. /**
  99311. * Attaches the drag behavior the passed in mesh
  99312. * @param ownerNode The mesh that will be dragged around once attached
  99313. */
  99314. PointerDragBehavior.prototype.attach = function (ownerNode) {
  99315. var _this = this;
  99316. this._scene = ownerNode.getScene();
  99317. this._attachedNode = ownerNode;
  99318. // Initialize drag plane to not interfere with existing scene
  99319. if (!PointerDragBehavior._planeScene) {
  99320. if (this._debugMode) {
  99321. PointerDragBehavior._planeScene = this._scene;
  99322. }
  99323. else {
  99324. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  99325. PointerDragBehavior._planeScene.detachControl();
  99326. this._scene.getEngine().scenes.pop();
  99327. this._scene.onDisposeObservable.addOnce(function () {
  99328. PointerDragBehavior._planeScene.dispose();
  99329. PointerDragBehavior._planeScene = null;
  99330. });
  99331. }
  99332. }
  99333. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  99334. // State of the drag
  99335. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  99336. var pickPredicate = function (m) {
  99337. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  99338. };
  99339. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99340. if (!_this.enabled) {
  99341. return;
  99342. }
  99343. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99344. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99345. _this._startDrag(pointerInfo.event.pointerId, pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  99346. }
  99347. }
  99348. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99349. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99350. _this.releaseDrag();
  99351. }
  99352. }
  99353. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99354. var pointerId = pointerInfo.event.pointerId;
  99355. // If drag was started with anyMouseID specified, set pointerID to the next mouse that moved
  99356. if (_this.currentDraggingPointerID === PointerDragBehavior._AnyMouseID && pointerId !== PointerDragBehavior._AnyMouseID && pointerInfo.event.pointerType == "mouse") {
  99357. if (_this._lastPointerRay[_this.currentDraggingPointerID]) {
  99358. _this._lastPointerRay[pointerId] = _this._lastPointerRay[_this.currentDraggingPointerID];
  99359. delete _this._lastPointerRay[_this.currentDraggingPointerID];
  99360. }
  99361. _this.currentDraggingPointerID = pointerId;
  99362. }
  99363. // Keep track of last pointer ray, this is used simulating the start of a drag in startDrag()
  99364. if (!_this._lastPointerRay[pointerId]) {
  99365. _this._lastPointerRay[pointerId] = new BABYLON.Ray(new BABYLON.Vector3(), new BABYLON.Vector3());
  99366. }
  99367. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  99368. _this._lastPointerRay[pointerId].origin.copyFrom(pointerInfo.pickInfo.ray.origin);
  99369. _this._lastPointerRay[pointerId].direction.copyFrom(pointerInfo.pickInfo.ray.direction);
  99370. if (_this.currentDraggingPointerID == pointerId && _this.dragging) {
  99371. _this._moveDrag(pointerInfo.pickInfo.ray);
  99372. }
  99373. }
  99374. }
  99375. });
  99376. this._beforeRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99377. if (_this._moving && _this.moveAttached) {
  99378. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(_this._attachedNode);
  99379. // Slowly move mesh to avoid jitter
  99380. _this._targetPosition.subtractToRef((_this._attachedNode).absolutePosition, _this._tmpVector);
  99381. _this._tmpVector.scaleInPlace(_this.dragDeltaRatio);
  99382. (_this._attachedNode).getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  99383. (_this._attachedNode).setAbsolutePosition(_this._tmpVector);
  99384. BABYLON.BoundingBoxGizmo._RestorePivotPoint(_this._attachedNode);
  99385. }
  99386. });
  99387. };
  99388. /**
  99389. * Force relase the drag action by code.
  99390. */
  99391. PointerDragBehavior.prototype.releaseDrag = function () {
  99392. this.dragging = false;
  99393. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  99394. this.currentDraggingPointerID = -1;
  99395. this._moving = false;
  99396. // Reattach camera controls
  99397. if (this.detachCameraControls && this._attachedElement && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99398. this._scene.activeCamera.attachControl(this._attachedElement, true);
  99399. }
  99400. };
  99401. /**
  99402. * Simulates the start of a pointer drag event on the behavior
  99403. * @param pointerId pointerID of the pointer that should be simulated (Default: Any mouse pointer ID)
  99404. * @param fromRay initial ray of the pointer to be simulated (Default: Ray from camera to attached mesh)
  99405. * @param startPickedPoint picked point of the pointer to be simulated (Default: attached mesh position)
  99406. */
  99407. PointerDragBehavior.prototype.startDrag = function (pointerId, fromRay, startPickedPoint) {
  99408. if (pointerId === void 0) { pointerId = PointerDragBehavior._AnyMouseID; }
  99409. this._startDrag(pointerId, fromRay, startPickedPoint);
  99410. var lastRay = this._lastPointerRay[pointerId];
  99411. if (pointerId === PointerDragBehavior._AnyMouseID) {
  99412. lastRay = this._lastPointerRay[Object.keys(this._lastPointerRay)[0]];
  99413. }
  99414. if (lastRay) {
  99415. // if there was a last pointer ray drag the object there
  99416. this._moveDrag(lastRay);
  99417. }
  99418. };
  99419. PointerDragBehavior.prototype._startDrag = function (pointerId, fromRay, startPickedPoint) {
  99420. if (!this._scene.activeCamera || this.dragging || !this._attachedNode) {
  99421. return;
  99422. }
  99423. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(this._attachedNode);
  99424. // Create start ray from the camera to the object
  99425. if (fromRay) {
  99426. this._startDragRay.direction.copyFrom(fromRay.direction);
  99427. this._startDragRay.origin.copyFrom(fromRay.origin);
  99428. }
  99429. else {
  99430. this._startDragRay.origin.copyFrom(this._scene.activeCamera.position);
  99431. this._attachedNode.getWorldMatrix().getTranslationToRef(this._tmpVector);
  99432. this._tmpVector.subtractToRef(this._scene.activeCamera.position, this._startDragRay.direction);
  99433. }
  99434. this._updateDragPlanePosition(this._startDragRay, startPickedPoint ? startPickedPoint : this._tmpVector);
  99435. var pickedPoint = this._pickWithRayOnDragPlane(this._startDragRay);
  99436. if (pickedPoint) {
  99437. this.dragging = true;
  99438. this.currentDraggingPointerID = pointerId;
  99439. this.lastDragPosition.copyFrom(pickedPoint);
  99440. this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: this.currentDraggingPointerID });
  99441. this._targetPosition.copyFrom((this._attachedNode).absolutePosition);
  99442. // Detatch camera controls
  99443. if (this.detachCameraControls && this._scene.activeCamera && !this._scene.activeCamera.leftCamera) {
  99444. if (this._scene.activeCamera.inputs.attachedElement) {
  99445. this._attachedElement = this._scene.activeCamera.inputs.attachedElement;
  99446. this._scene.activeCamera.detachControl(this._scene.activeCamera.inputs.attachedElement);
  99447. }
  99448. else {
  99449. this._attachedElement = null;
  99450. }
  99451. }
  99452. }
  99453. BABYLON.BoundingBoxGizmo._RestorePivotPoint(this._attachedNode);
  99454. };
  99455. PointerDragBehavior.prototype._moveDrag = function (ray) {
  99456. this._moving = true;
  99457. var pickedPoint = this._pickWithRayOnDragPlane(ray);
  99458. if (pickedPoint) {
  99459. if (this.updateDragPlane) {
  99460. this._updateDragPlanePosition(ray, pickedPoint);
  99461. }
  99462. var dragLength = 0;
  99463. // depending on the drag mode option drag accordingly
  99464. if (this._options.dragAxis) {
  99465. // Convert local drag axis to world
  99466. BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._worldDragAxis);
  99467. // Project delta drag from the drag plane onto the drag axis
  99468. pickedPoint.subtractToRef(this.lastDragPosition, this._tmpVector);
  99469. dragLength = BABYLON.Vector3.Dot(this._tmpVector, this._worldDragAxis);
  99470. this._worldDragAxis.scaleToRef(dragLength, this._dragDelta);
  99471. }
  99472. else {
  99473. dragLength = this._dragDelta.length();
  99474. pickedPoint.subtractToRef(this.lastDragPosition, this._dragDelta);
  99475. }
  99476. this._targetPosition.addInPlace(this._dragDelta);
  99477. this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: this._dragDelta, dragPlanePoint: pickedPoint, dragPlaneNormal: this._dragPlane.forward, pointerId: this.currentDraggingPointerID });
  99478. this.lastDragPosition.copyFrom(pickedPoint);
  99479. }
  99480. };
  99481. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  99482. var _this = this;
  99483. if (!ray) {
  99484. return null;
  99485. }
  99486. // Calculate angle between plane normal and ray
  99487. var angle = Math.acos(BABYLON.Vector3.Dot(this._dragPlane.forward, ray.direction));
  99488. // Correct if ray is casted from oposite side
  99489. if (angle > Math.PI / 2) {
  99490. angle = Math.PI - angle;
  99491. }
  99492. // If the angle is too perpendicular to the plane pick another point on the plane where it is looking
  99493. if (this.maxDragAngle > 0 && angle > this.maxDragAngle) {
  99494. if (this._useAlternatePickedPointAboveMaxDragAngle) {
  99495. // Invert ray direction along the towards object axis
  99496. this._tmpVector.copyFrom(ray.direction);
  99497. (this._attachedNode).absolutePosition.subtractToRef(ray.origin, this._alternatePickedPoint);
  99498. this._alternatePickedPoint.normalize();
  99499. this._alternatePickedPoint.scaleInPlace(-2 * BABYLON.Vector3.Dot(this._alternatePickedPoint, this._tmpVector));
  99500. this._tmpVector.addInPlace(this._alternatePickedPoint);
  99501. // Project resulting vector onto the drag plane and add it to the attached nodes absolute position to get a picked point
  99502. var dot = BABYLON.Vector3.Dot(this._dragPlane.forward, this._tmpVector);
  99503. this._dragPlane.forward.scaleToRef(-dot, this._alternatePickedPoint);
  99504. this._alternatePickedPoint.addInPlace(this._tmpVector);
  99505. this._alternatePickedPoint.addInPlace((this._attachedNode).absolutePosition);
  99506. return this._alternatePickedPoint;
  99507. }
  99508. else {
  99509. return null;
  99510. }
  99511. }
  99512. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  99513. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  99514. return pickResult.pickedPoint;
  99515. }
  99516. else {
  99517. return null;
  99518. }
  99519. };
  99520. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  99521. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  99522. this._pointA.copyFrom(dragPlanePosition);
  99523. if (this._options.dragAxis) {
  99524. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragAxis);
  99525. // Calculate plane normal in direction of camera but perpendicular to drag axis
  99526. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  99527. ray.origin.subtractToRef(this._pointA, this._pointC);
  99528. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  99529. // Get perpendicular line from direction to camera and drag axis
  99530. this._pointB.subtractToRef(this._pointA, this._lineA);
  99531. this._pointC.subtractToRef(this._pointA, this._lineB);
  99532. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  99533. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  99534. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  99535. this._lookAt.normalize();
  99536. this._dragPlane.position.copyFrom(this._pointA);
  99537. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  99538. this._dragPlane.lookAt(this._lookAt);
  99539. }
  99540. else if (this._options.dragPlaneNormal) {
  99541. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this._options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this._options.dragPlaneNormal);
  99542. this._dragPlane.position.copyFrom(this._pointA);
  99543. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  99544. this._dragPlane.lookAt(this._lookAt);
  99545. }
  99546. else {
  99547. this._dragPlane.position.copyFrom(this._pointA);
  99548. this._dragPlane.lookAt(ray.origin);
  99549. }
  99550. this._dragPlane.computeWorldMatrix(true);
  99551. };
  99552. /**
  99553. * Detaches the behavior from the mesh
  99554. */
  99555. PointerDragBehavior.prototype.detach = function () {
  99556. if (this._pointerObserver) {
  99557. this._scene.onPointerObservable.remove(this._pointerObserver);
  99558. }
  99559. if (this._beforeRenderObserver) {
  99560. this._scene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  99561. }
  99562. };
  99563. PointerDragBehavior._AnyMouseID = -2;
  99564. return PointerDragBehavior;
  99565. }());
  99566. BABYLON.PointerDragBehavior = PointerDragBehavior;
  99567. })(BABYLON || (BABYLON = {}));
  99568. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  99569. var BABYLON;
  99570. (function (BABYLON) {
  99571. /**
  99572. * A behavior that when attached to a mesh will allow the mesh to be scaled
  99573. */
  99574. var MultiPointerScaleBehavior = /** @class */ (function () {
  99575. /**
  99576. * Instantiate a new behavior that when attached to a mesh will allow the mesh to be scaled
  99577. */
  99578. function MultiPointerScaleBehavior() {
  99579. this._startDistance = 0;
  99580. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  99581. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  99582. this._sceneRenderObserver = null;
  99583. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  99584. this._dragBehaviorA.moveAttached = false;
  99585. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  99586. this._dragBehaviorB.moveAttached = false;
  99587. }
  99588. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  99589. /**
  99590. * The name of the behavior
  99591. */
  99592. get: function () {
  99593. return "MultiPointerScale";
  99594. },
  99595. enumerable: true,
  99596. configurable: true
  99597. });
  99598. /**
  99599. * Initializes the behavior
  99600. */
  99601. MultiPointerScaleBehavior.prototype.init = function () { };
  99602. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  99603. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  99604. };
  99605. /**
  99606. * Attaches the scale behavior the passed in mesh
  99607. * @param ownerNode The mesh that will be scaled around once attached
  99608. */
  99609. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  99610. var _this = this;
  99611. this._ownerNode = ownerNode;
  99612. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  99613. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  99614. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99615. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99616. _this._dragBehaviorA.releaseDrag();
  99617. }
  99618. else {
  99619. _this._initialScale.copyFrom(ownerNode.scaling);
  99620. _this._startDistance = _this._getCurrentDistance();
  99621. }
  99622. }
  99623. });
  99624. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  99625. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99626. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  99627. _this._dragBehaviorB.releaseDrag();
  99628. }
  99629. else {
  99630. _this._initialScale.copyFrom(ownerNode.scaling);
  99631. _this._startDistance = _this._getCurrentDistance();
  99632. }
  99633. }
  99634. });
  99635. // Once both drag behaviors are active scale based on the distance between the two pointers
  99636. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99637. behavior.onDragObservable.add(function () {
  99638. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99639. var ratio = _this._getCurrentDistance() / _this._startDistance;
  99640. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  99641. }
  99642. });
  99643. });
  99644. ownerNode.addBehavior(this._dragBehaviorA);
  99645. ownerNode.addBehavior(this._dragBehaviorB);
  99646. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99647. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99648. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  99649. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  99650. if (change.length() > 0.01) {
  99651. ownerNode.scaling.addInPlace(change);
  99652. }
  99653. }
  99654. });
  99655. };
  99656. /**
  99657. * Detaches the behavior from the mesh
  99658. */
  99659. MultiPointerScaleBehavior.prototype.detach = function () {
  99660. var _this = this;
  99661. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99662. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  99663. behavior.onDragStartObservable.clear();
  99664. behavior.onDragObservable.clear();
  99665. _this._ownerNode.removeBehavior(behavior);
  99666. });
  99667. };
  99668. return MultiPointerScaleBehavior;
  99669. }());
  99670. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  99671. })(BABYLON || (BABYLON = {}));
  99672. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  99673. var BABYLON;
  99674. (function (BABYLON) {
  99675. /**
  99676. * 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
  99677. */
  99678. var SixDofDragBehavior = /** @class */ (function () {
  99679. /**
  99680. * 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
  99681. */
  99682. function SixDofDragBehavior() {
  99683. this._sceneRenderObserver = null;
  99684. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  99685. this._moving = false;
  99686. this._startingOrientation = new BABYLON.Quaternion();
  99687. /**
  99688. * 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)
  99689. */
  99690. this.zDragFactor = 3;
  99691. /**
  99692. * If the behavior is currently in a dragging state
  99693. */
  99694. this.dragging = false;
  99695. /**
  99696. * 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)
  99697. */
  99698. this.dragDeltaRatio = 0.2;
  99699. /**
  99700. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  99701. */
  99702. this.currentDraggingPointerID = -1;
  99703. /**
  99704. * If camera controls should be detached during the drag
  99705. */
  99706. this.detachCameraControls = true;
  99707. /**
  99708. * Fires each time a drag starts
  99709. */
  99710. this.onDragStartObservable = new BABYLON.Observable();
  99711. /**
  99712. * Fires each time a drag ends (eg. mouse release after drag)
  99713. */
  99714. this.onDragEndObservable = new BABYLON.Observable();
  99715. }
  99716. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  99717. /**
  99718. * The name of the behavior
  99719. */
  99720. get: function () {
  99721. return "SixDofDrag";
  99722. },
  99723. enumerable: true,
  99724. configurable: true
  99725. });
  99726. /**
  99727. * Initializes the behavior
  99728. */
  99729. SixDofDragBehavior.prototype.init = function () { };
  99730. /**
  99731. * Attaches the scale behavior the passed in mesh
  99732. * @param ownerNode The mesh that will be scaled around once attached
  99733. */
  99734. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  99735. var _this = this;
  99736. this._ownerNode = ownerNode;
  99737. this._scene = this._ownerNode.getScene();
  99738. if (!SixDofDragBehavior._virtualScene) {
  99739. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  99740. this._scene.getEngine().scenes.pop();
  99741. }
  99742. var pickedMesh = null;
  99743. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  99744. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  99745. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  99746. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  99747. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  99748. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  99749. var pickPredicate = function (m) {
  99750. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  99751. };
  99752. var attachedElement = null;
  99753. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  99754. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  99755. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  99756. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  99757. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  99758. }
  99759. pickedMesh = _this._ownerNode;
  99760. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  99761. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  99762. // Set position and orientation of the controller
  99763. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  99764. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  99765. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  99766. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99767. pickedMesh.computeWorldMatrix();
  99768. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  99769. if (!pickedMesh.rotationQuaternion) {
  99770. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  99771. }
  99772. var oldParent = pickedMesh.parent;
  99773. pickedMesh.setParent(null);
  99774. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  99775. pickedMesh.setParent(oldParent);
  99776. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  99777. // Update state
  99778. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  99779. _this.dragging = true;
  99780. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  99781. // Detatch camera controls
  99782. if (_this.detachCameraControls && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  99783. if (_this._scene.activeCamera.inputs.attachedElement) {
  99784. attachedElement = _this._scene.activeCamera.inputs.attachedElement;
  99785. _this._scene.activeCamera.detachControl(_this._scene.activeCamera.inputs.attachedElement);
  99786. }
  99787. else {
  99788. attachedElement = null;
  99789. }
  99790. }
  99791. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  99792. _this.onDragStartObservable.notifyObservers({});
  99793. }
  99794. }
  99795. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  99796. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  99797. _this.dragging = false;
  99798. _this._moving = false;
  99799. _this.currentDraggingPointerID = -1;
  99800. pickedMesh = null;
  99801. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99802. // Reattach camera controls
  99803. if (_this.detachCameraControls && attachedElement && _this._scene.activeCamera && !_this._scene.activeCamera.leftCamera) {
  99804. _this._scene.activeCamera.attachControl(attachedElement, true);
  99805. }
  99806. _this.onDragEndObservable.notifyObservers({});
  99807. }
  99808. }
  99809. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  99810. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  99811. var zDragFactor = _this.zDragFactor;
  99812. if (_this._scene.activeCamera && _this._scene.activeCamera.cameraRigMode == BABYLON.Camera.RIG_MODE_NONE) {
  99813. pointerInfo.pickInfo.ray.origin.copyFrom(_this._scene.activeCamera.position);
  99814. zDragFactor = 0;
  99815. }
  99816. // Calculate controller drag distance in controller space
  99817. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  99818. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  99819. var localOriginDragDifference = -BABYLON.Vector3.Dot(originDragDifference, pointerInfo.pickInfo.ray.direction);
  99820. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  99821. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  99822. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? localOriginDragDifference * _this.zDragFactor : localOriginDragDifference * zDragFactor * _this._virtualDragMesh.position.z;
  99823. if (_this._virtualDragMesh.position.z < 0) {
  99824. _this._virtualDragMesh.position.z = 0;
  99825. }
  99826. // Update the controller position
  99827. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  99828. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  99829. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  99830. // Move the virtualObjectsPosition into the picked mesh's space if needed
  99831. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  99832. if (pickedMesh.parent) {
  99833. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  99834. }
  99835. if (!_this._moving) {
  99836. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  99837. }
  99838. _this._moving = true;
  99839. }
  99840. }
  99841. });
  99842. var tmpQuaternion = new BABYLON.Quaternion();
  99843. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  99844. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  99845. if (_this.dragging && _this._moving && pickedMesh) {
  99846. BABYLON.BoundingBoxGizmo._RemoveAndStorePivotPoint(pickedMesh);
  99847. // Slowly move mesh to avoid jitter
  99848. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  99849. // Get change in rotation
  99850. tmpQuaternion.copyFrom(_this._startingOrientation);
  99851. tmpQuaternion.x = -tmpQuaternion.x;
  99852. tmpQuaternion.y = -tmpQuaternion.y;
  99853. tmpQuaternion.z = -tmpQuaternion.z;
  99854. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  99855. // Convert change in rotation to only y axis rotation
  99856. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  99857. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  99858. // Slowly move mesh to avoid jitter
  99859. var oldParent = pickedMesh.parent;
  99860. pickedMesh.setParent(null);
  99861. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  99862. pickedMesh.setParent(oldParent);
  99863. BABYLON.BoundingBoxGizmo._RestorePivotPoint(pickedMesh);
  99864. }
  99865. });
  99866. };
  99867. /**
  99868. * Detaches the behavior from the mesh
  99869. */
  99870. SixDofDragBehavior.prototype.detach = function () {
  99871. if (this._scene) {
  99872. this._scene.onPointerObservable.remove(this._pointerObserver);
  99873. }
  99874. if (this._ownerNode) {
  99875. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  99876. }
  99877. if (this._virtualOriginMesh) {
  99878. this._virtualOriginMesh.dispose();
  99879. }
  99880. if (this._virtualDragMesh) {
  99881. this._virtualDragMesh.dispose();
  99882. }
  99883. this.onDragEndObservable.clear();
  99884. this.onDragStartObservable.clear();
  99885. };
  99886. return SixDofDragBehavior;
  99887. }());
  99888. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  99889. })(BABYLON || (BABYLON = {}));
  99890. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  99891. var BABYLON;
  99892. (function (BABYLON) {
  99893. /**
  99894. * @hidden
  99895. */
  99896. var FaceDirectionInfo = /** @class */ (function () {
  99897. function FaceDirectionInfo(direction, rotatedDirection, diff, ignore) {
  99898. if (rotatedDirection === void 0) { rotatedDirection = new BABYLON.Vector3(); }
  99899. if (diff === void 0) { diff = 0; }
  99900. if (ignore === void 0) { ignore = false; }
  99901. this.direction = direction;
  99902. this.rotatedDirection = rotatedDirection;
  99903. this.diff = diff;
  99904. this.ignore = ignore;
  99905. }
  99906. return FaceDirectionInfo;
  99907. }());
  99908. /**
  99909. * A behavior that when attached to a mesh will will place a specified node on the meshes face pointing towards the camera
  99910. */
  99911. var AttachToBoxBehavior = /** @class */ (function () {
  99912. /**
  99913. * Creates the AttachToBoxBehavior, used to attach UI to the closest face of the box to a camera
  99914. * @param ui The transform node that should be attched to the mesh
  99915. */
  99916. function AttachToBoxBehavior(ui) {
  99917. this.ui = ui;
  99918. /**
  99919. * The name of the behavior
  99920. */
  99921. this.name = "AttachToBoxBehavior";
  99922. /**
  99923. * The distance away from the face of the mesh that the UI should be attached to (default: 0.15)
  99924. */
  99925. this.distanceAwayFromFace = 0.15;
  99926. /**
  99927. * The distance from the bottom of the face that the UI should be attached to (default: 0.15)
  99928. */
  99929. this.distanceAwayFromBottomOfFace = 0.15;
  99930. 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))];
  99931. this._tmpMatrix = new BABYLON.Matrix();
  99932. this._tmpVector = new BABYLON.Vector3();
  99933. this._zeroVector = BABYLON.Vector3.Zero();
  99934. this._lookAtTmpMatrix = new BABYLON.Matrix();
  99935. /* Does nothing */
  99936. }
  99937. /**
  99938. * Initializes the behavior
  99939. */
  99940. AttachToBoxBehavior.prototype.init = function () {
  99941. /* Does nothing */
  99942. };
  99943. AttachToBoxBehavior.prototype._closestFace = function (targetDirection) {
  99944. var _this = this;
  99945. // Go over each face and calculate the angle between the face's normal and targetDirection
  99946. this._faceVectors.forEach(function (v) {
  99947. if (!_this._target.rotationQuaternion) {
  99948. _this._target.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._target.rotation.y, _this._target.rotation.x, _this._target.rotation.z);
  99949. }
  99950. _this._target.rotationQuaternion.toRotationMatrix(_this._tmpMatrix);
  99951. BABYLON.Vector3.TransformCoordinatesToRef(v.direction, _this._tmpMatrix, v.rotatedDirection);
  99952. v.diff = BABYLON.Vector3.GetAngleBetweenVectors(v.rotatedDirection, targetDirection, BABYLON.Vector3.Cross(v.rotatedDirection, targetDirection));
  99953. });
  99954. // Return the face information of the one with the normal closeset to target direction
  99955. return this._faceVectors.reduce(function (min, p) {
  99956. if (min.ignore) {
  99957. return p;
  99958. }
  99959. else if (p.ignore) {
  99960. return min;
  99961. }
  99962. else {
  99963. return min.diff < p.diff ? min : p;
  99964. }
  99965. }, this._faceVectors[0]);
  99966. };
  99967. AttachToBoxBehavior.prototype._lookAtToRef = function (pos, up, ref) {
  99968. if (up === void 0) { up = new BABYLON.Vector3(0, 1, 0); }
  99969. BABYLON.Matrix.LookAtLHToRef(this._zeroVector, pos, up, this._lookAtTmpMatrix);
  99970. this._lookAtTmpMatrix.invert();
  99971. BABYLON.Quaternion.FromRotationMatrixToRef(this._lookAtTmpMatrix, ref);
  99972. };
  99973. /**
  99974. * Attaches the AttachToBoxBehavior to the passed in mesh
  99975. * @param target The mesh that the specified node will be attached to
  99976. */
  99977. AttachToBoxBehavior.prototype.attach = function (target) {
  99978. var _this = this;
  99979. this._target = target;
  99980. this._scene = this._target.getScene();
  99981. // Every frame, update the app bars position
  99982. this._onRenderObserver = this._scene.onBeforeRenderObservable.add(function () {
  99983. if (!_this._scene.activeCamera) {
  99984. return;
  99985. }
  99986. // Find the face closest to the cameras position
  99987. var cameraPos = _this._scene.activeCamera.position;
  99988. if (_this._scene.activeCamera.devicePosition) {
  99989. cameraPos = _this._scene.activeCamera.devicePosition;
  99990. }
  99991. var facing = _this._closestFace(cameraPos.subtract(target.position));
  99992. if (_this._scene.activeCamera.leftCamera) {
  99993. _this._scene.activeCamera.leftCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  99994. }
  99995. else {
  99996. _this._scene.activeCamera.computeWorldMatrix().getRotationMatrixToRef(_this._tmpMatrix);
  99997. }
  99998. // Get camera up direction
  99999. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Vector3.Up(), _this._tmpMatrix, _this._tmpVector);
  100000. // Ignore faces to not select a parrelel face for the up vector of the UI
  100001. _this._faceVectors.forEach(function (v) {
  100002. if (facing.direction.x && v.direction.x) {
  100003. v.ignore = true;
  100004. }
  100005. if (facing.direction.y && v.direction.y) {
  100006. v.ignore = true;
  100007. }
  100008. if (facing.direction.z && v.direction.z) {
  100009. v.ignore = true;
  100010. }
  100011. });
  100012. var facingUp = _this._closestFace(_this._tmpVector);
  100013. // Unignore faces
  100014. _this._faceVectors.forEach(function (v) {
  100015. v.ignore = false;
  100016. });
  100017. // Position the app bar on that face
  100018. _this.ui.position.copyFrom(target.position);
  100019. if (facing.direction.x) {
  100020. facing.rotatedDirection.scaleToRef((target.scaling.x / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100021. _this.ui.position.addInPlace(_this._tmpVector);
  100022. }
  100023. if (facing.direction.y) {
  100024. facing.rotatedDirection.scaleToRef((target.scaling.y / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100025. _this.ui.position.addInPlace(_this._tmpVector);
  100026. }
  100027. if (facing.direction.z) {
  100028. facing.rotatedDirection.scaleToRef((target.scaling.z / 2) + _this.distanceAwayFromFace, _this._tmpVector);
  100029. _this.ui.position.addInPlace(_this._tmpVector);
  100030. }
  100031. // Rotate to be oriented properly to the camera
  100032. if (!_this.ui.rotationQuaternion) {
  100033. _this.ui.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.ui.rotation.y, _this.ui.rotation.x, _this.ui.rotation.z);
  100034. }
  100035. facing.rotatedDirection.scaleToRef(-1, _this._tmpVector);
  100036. _this._lookAtToRef(_this._tmpVector, facingUp.rotatedDirection, _this.ui.rotationQuaternion);
  100037. // Place ui the correct distance from the bottom of the mesh
  100038. if (facingUp.direction.x) {
  100039. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.x / 2, _this._tmpVector);
  100040. }
  100041. if (facingUp.direction.y) {
  100042. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.y / 2, _this._tmpVector);
  100043. }
  100044. if (facingUp.direction.z) {
  100045. _this.ui.up.scaleToRef(_this.distanceAwayFromBottomOfFace - target.scaling.z / 2, _this._tmpVector);
  100046. }
  100047. _this.ui.position.addInPlace(_this._tmpVector);
  100048. });
  100049. };
  100050. /**
  100051. * Detaches the behavior from the mesh
  100052. */
  100053. AttachToBoxBehavior.prototype.detach = function () {
  100054. this._scene.onBeforeRenderObservable.remove(this._onRenderObserver);
  100055. };
  100056. return AttachToBoxBehavior;
  100057. }());
  100058. BABYLON.AttachToBoxBehavior = AttachToBoxBehavior;
  100059. })(BABYLON || (BABYLON = {}));
  100060. //# sourceMappingURL=babylon.attachToBoxBehavior.js.map
  100061. var BABYLON;
  100062. (function (BABYLON) {
  100063. /**
  100064. * A behavior that when attached to a mesh will allow the mesh to fade in and out
  100065. */
  100066. var FadeInOutBehavior = /** @class */ (function () {
  100067. /**
  100068. * Instatiates the FadeInOutBehavior
  100069. */
  100070. function FadeInOutBehavior() {
  100071. var _this = this;
  100072. /**
  100073. * Time in milliseconds to delay before fading in (Default: 0)
  100074. */
  100075. this.delay = 0;
  100076. /**
  100077. * Time in milliseconds for the mesh to fade in (Default: 300)
  100078. */
  100079. this.fadeInTime = 300;
  100080. this._millisecondsPerFrame = 1000 / 60;
  100081. this._hovered = false;
  100082. this._hoverValue = 0;
  100083. this._ownerNode = null;
  100084. this._update = function () {
  100085. if (_this._ownerNode) {
  100086. _this._hoverValue += _this._hovered ? _this._millisecondsPerFrame : -_this._millisecondsPerFrame;
  100087. _this._setAllVisibility(_this._ownerNode, (_this._hoverValue - _this.delay) / _this.fadeInTime);
  100088. if (_this._ownerNode.visibility > 1) {
  100089. _this._setAllVisibility(_this._ownerNode, 1);
  100090. _this._hoverValue = _this.fadeInTime + _this.delay;
  100091. return;
  100092. }
  100093. else if (_this._ownerNode.visibility < 0) {
  100094. _this._setAllVisibility(_this._ownerNode, 0);
  100095. if (_this._hoverValue < 0) {
  100096. _this._hoverValue = 0;
  100097. return;
  100098. }
  100099. }
  100100. setTimeout(_this._update, _this._millisecondsPerFrame);
  100101. }
  100102. };
  100103. }
  100104. Object.defineProperty(FadeInOutBehavior.prototype, "name", {
  100105. /**
  100106. * The name of the behavior
  100107. */
  100108. get: function () {
  100109. return "FadeInOut";
  100110. },
  100111. enumerable: true,
  100112. configurable: true
  100113. });
  100114. /**
  100115. * Initializes the behavior
  100116. */
  100117. FadeInOutBehavior.prototype.init = function () {
  100118. };
  100119. /**
  100120. * Attaches the fade behavior on the passed in mesh
  100121. * @param ownerNode The mesh that will be faded in/out once attached
  100122. */
  100123. FadeInOutBehavior.prototype.attach = function (ownerNode) {
  100124. this._ownerNode = ownerNode;
  100125. this._setAllVisibility(this._ownerNode, 0);
  100126. };
  100127. /**
  100128. * Detaches the behavior from the mesh
  100129. */
  100130. FadeInOutBehavior.prototype.detach = function () {
  100131. this._ownerNode = null;
  100132. };
  100133. /**
  100134. * Triggers the mesh to begin fading in or out
  100135. * @param value if the object should fade in or out (true to fade in)
  100136. */
  100137. FadeInOutBehavior.prototype.fadeIn = function (value) {
  100138. this._hovered = value;
  100139. this._update();
  100140. };
  100141. FadeInOutBehavior.prototype._setAllVisibility = function (mesh, value) {
  100142. var _this = this;
  100143. mesh.visibility = value;
  100144. mesh.getChildMeshes().forEach(function (c) {
  100145. _this._setAllVisibility(c, value);
  100146. });
  100147. };
  100148. return FadeInOutBehavior;
  100149. }());
  100150. BABYLON.FadeInOutBehavior = FadeInOutBehavior;
  100151. })(BABYLON || (BABYLON = {}));
  100152. //# sourceMappingURL=babylon.fadeInOutBehavior.js.map
  100153. var BABYLON;
  100154. (function (BABYLON) {
  100155. /**
  100156. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  100157. */
  100158. var Gizmo = /** @class */ (function () {
  100159. /**
  100160. * Creates a gizmo
  100161. * @param gizmoLayer The utility layer the gizmo will be added to
  100162. */
  100163. function Gizmo(
  100164. /** The utility layer the gizmo will be added to */
  100165. gizmoLayer) {
  100166. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100167. var _this = this;
  100168. this.gizmoLayer = gizmoLayer;
  100169. /**
  100170. * Ratio for the scale of the gizmo (Default: 1)
  100171. */
  100172. this.scaleRatio = 1;
  100173. this._tmpMatrix = new BABYLON.Matrix();
  100174. /**
  100175. * If a custom mesh has been set (Default: false)
  100176. */
  100177. this._customMeshSet = false;
  100178. /**
  100179. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  100180. */
  100181. this.updateGizmoRotationToMatchAttachedMesh = true;
  100182. /**
  100183. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  100184. */
  100185. this.updateGizmoPositionToMatchAttachedMesh = true;
  100186. /**
  100187. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  100188. */
  100189. this._updateScale = true;
  100190. this._interactionsEnabled = true;
  100191. this._tempVector = new BABYLON.Vector3();
  100192. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  100193. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  100194. _this._update();
  100195. });
  100196. this.attachedMesh = null;
  100197. }
  100198. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  100199. /**
  100200. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  100201. * * When set, interactions will be enabled
  100202. */
  100203. get: function () {
  100204. return this._attachedMesh;
  100205. },
  100206. set: function (value) {
  100207. this._attachedMesh = value;
  100208. this._rootMesh.setEnabled(value ? true : false);
  100209. this._attachedMeshChanged(value);
  100210. },
  100211. enumerable: true,
  100212. configurable: true
  100213. });
  100214. /**
  100215. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100216. * @param mesh The mesh to replace the default mesh of the gizmo
  100217. */
  100218. Gizmo.prototype.setCustomMesh = function (mesh) {
  100219. if (mesh.getScene() != this.gizmoLayer.utilityLayerScene) {
  100220. throw "When setting a custom mesh on a gizmo, the custom meshes scene must be the same as the gizmos (eg. gizmo.gizmoLayer.utilityLayerScene)";
  100221. }
  100222. this._rootMesh.getChildMeshes().forEach(function (c) {
  100223. c.dispose();
  100224. });
  100225. mesh.parent = this._rootMesh;
  100226. this._customMeshSet = true;
  100227. };
  100228. Gizmo.prototype._attachedMeshChanged = function (value) {
  100229. };
  100230. /**
  100231. * @hidden
  100232. * Updates the gizmo to match the attached mesh's position/rotation
  100233. */
  100234. Gizmo.prototype._update = function () {
  100235. if (this.attachedMesh) {
  100236. if (this.updateGizmoRotationToMatchAttachedMesh) {
  100237. if (!this._rootMesh.rotationQuaternion) {
  100238. this._rootMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._rootMesh.rotation.y, this._rootMesh.rotation.x, this._rootMesh.rotation.z);
  100239. }
  100240. // Remove scaling before getting rotation matrix to get rotation matrix unmodified by scale
  100241. this._tempVector.copyFrom(this.attachedMesh.scaling);
  100242. if (this.attachedMesh.scaling.x < 0) {
  100243. this.attachedMesh.scaling.x *= -1;
  100244. }
  100245. if (this.attachedMesh.scaling.y < 0) {
  100246. this.attachedMesh.scaling.y *= -1;
  100247. }
  100248. if (this.attachedMesh.scaling.z < 0) {
  100249. this.attachedMesh.scaling.z *= -1;
  100250. }
  100251. this.attachedMesh.computeWorldMatrix().getRotationMatrixToRef(this._tmpMatrix);
  100252. this.attachedMesh.scaling.copyFrom(this._tempVector);
  100253. this.attachedMesh.computeWorldMatrix();
  100254. BABYLON.Quaternion.FromRotationMatrixToRef(this._tmpMatrix, this._rootMesh.rotationQuaternion);
  100255. }
  100256. else if (this._rootMesh.rotationQuaternion) {
  100257. this._rootMesh.rotationQuaternion.set(0, 0, 0, 1);
  100258. }
  100259. if (this.updateGizmoPositionToMatchAttachedMesh) {
  100260. this._rootMesh.position.copyFrom(this.attachedMesh.absolutePosition);
  100261. }
  100262. if (this._updateScale && this.gizmoLayer.utilityLayerScene.activeCamera && this.attachedMesh) {
  100263. var cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.position;
  100264. if (this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition) {
  100265. cameraPosition = this.gizmoLayer.utilityLayerScene.activeCamera.devicePosition;
  100266. }
  100267. this._rootMesh.position.subtractToRef(cameraPosition, this._tempVector);
  100268. var dist = this._tempVector.length() * this.scaleRatio;
  100269. this._rootMesh.scaling.set(dist, dist, dist);
  100270. }
  100271. }
  100272. };
  100273. /**
  100274. * Disposes of the gizmo
  100275. */
  100276. Gizmo.prototype.dispose = function () {
  100277. this._rootMesh.dispose();
  100278. if (this._beforeRenderObserver) {
  100279. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  100280. }
  100281. };
  100282. return Gizmo;
  100283. }());
  100284. BABYLON.Gizmo = Gizmo;
  100285. })(BABYLON || (BABYLON = {}));
  100286. //# sourceMappingURL=babylon.gizmo.js.map
  100287. var BABYLON;
  100288. (function (BABYLON) {
  100289. /**
  100290. * Single axis drag gizmo
  100291. */
  100292. var AxisDragGizmo = /** @class */ (function (_super) {
  100293. __extends(AxisDragGizmo, _super);
  100294. /**
  100295. * Creates an AxisDragGizmo
  100296. * @param gizmoLayer The utility layer the gizmo will be added to
  100297. * @param dragAxis The axis which the gizmo will be able to drag on
  100298. * @param color The color of the gizmo
  100299. */
  100300. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  100301. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100302. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100303. var _this = _super.call(this, gizmoLayer) || this;
  100304. _this._pointerObserver = null;
  100305. /**
  100306. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100307. */
  100308. _this.snapDistance = 0;
  100309. /**
  100310. * Event that fires each time the gizmo snaps to a new location.
  100311. * * snapDistance is the the change in distance
  100312. */
  100313. _this.onSnapObservable = new BABYLON.Observable();
  100314. // Create Material
  100315. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100316. coloredMaterial.disableLighting = true;
  100317. coloredMaterial.emissiveColor = color;
  100318. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100319. hoverMaterial.disableLighting = true;
  100320. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100321. // Build mesh on root node
  100322. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100323. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 1.5, diameterBottom: 0.75, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  100324. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100325. arrowTail.color = coloredMaterial.emissiveColor;
  100326. arrow.addChild(arrowMesh);
  100327. arrow.addChild(arrowTail);
  100328. // Position arrow pointing in its drag axis
  100329. arrowMesh.scaling.scaleInPlace(0.05);
  100330. arrowMesh.material = coloredMaterial;
  100331. arrowMesh.rotation.x = Math.PI / 2;
  100332. arrowMesh.position.z += 0.3;
  100333. arrowTail.scaling.scaleInPlace(0.26);
  100334. arrowTail.rotation.x = Math.PI / 2;
  100335. arrowTail.material = coloredMaterial;
  100336. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100337. arrow.scaling.scaleInPlace(1 / 3);
  100338. _this._rootMesh.addChild(arrow);
  100339. var currentSnapDragDistance = 0;
  100340. var tmpVector = new BABYLON.Vector3();
  100341. var tmpSnapEvent = { snapDistance: 0 };
  100342. // Add drag behavior to handle events when the gizmo is dragged
  100343. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100344. _this.dragBehavior.moveAttached = false;
  100345. _this._rootMesh.addBehavior(_this.dragBehavior);
  100346. var localDelta = new BABYLON.Vector3();
  100347. var tmpMatrix = new BABYLON.Matrix();
  100348. _this.dragBehavior.onDragObservable.add(function (event) {
  100349. if (_this.attachedMesh) {
  100350. // Convert delta to local translation if it has a parent
  100351. if (_this.attachedMesh.parent) {
  100352. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100353. tmpMatrix.setTranslationFromFloats(0, 0, 0);
  100354. BABYLON.Vector3.TransformCoordinatesToRef(event.delta, tmpMatrix, localDelta);
  100355. }
  100356. else {
  100357. localDelta.copyFrom(event.delta);
  100358. }
  100359. // Snapping logic
  100360. if (_this.snapDistance == 0) {
  100361. _this.attachedMesh.position.addInPlace(localDelta);
  100362. }
  100363. else {
  100364. currentSnapDragDistance += event.dragDistance;
  100365. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100366. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  100367. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100368. localDelta.normalizeToRef(tmpVector);
  100369. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  100370. _this.attachedMesh.position.addInPlace(tmpVector);
  100371. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100372. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100373. }
  100374. }
  100375. }
  100376. });
  100377. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100378. if (_this._customMeshSet) {
  100379. return;
  100380. }
  100381. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100382. var material = isHovered ? hoverMaterial : coloredMaterial;
  100383. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100384. m.material = material;
  100385. if (m.color) {
  100386. m.color = material.emissiveColor;
  100387. }
  100388. });
  100389. });
  100390. return _this;
  100391. }
  100392. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  100393. if (this.dragBehavior) {
  100394. this.dragBehavior.enabled = value ? true : false;
  100395. }
  100396. };
  100397. /**
  100398. * Disposes of the gizmo
  100399. */
  100400. AxisDragGizmo.prototype.dispose = function () {
  100401. this.onSnapObservable.clear();
  100402. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100403. this.dragBehavior.detach();
  100404. _super.prototype.dispose.call(this);
  100405. };
  100406. return AxisDragGizmo;
  100407. }(BABYLON.Gizmo));
  100408. BABYLON.AxisDragGizmo = AxisDragGizmo;
  100409. })(BABYLON || (BABYLON = {}));
  100410. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  100411. var BABYLON;
  100412. (function (BABYLON) {
  100413. /**
  100414. * Single axis scale gizmo
  100415. */
  100416. var AxisScaleGizmo = /** @class */ (function (_super) {
  100417. __extends(AxisScaleGizmo, _super);
  100418. /**
  100419. * Creates an AxisScaleGizmo
  100420. * @param gizmoLayer The utility layer the gizmo will be added to
  100421. * @param dragAxis The axis which the gizmo will be able to scale on
  100422. * @param color The color of the gizmo
  100423. */
  100424. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  100425. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100426. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100427. var _this = _super.call(this, gizmoLayer) || this;
  100428. _this._pointerObserver = null;
  100429. /**
  100430. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100431. */
  100432. _this.snapDistance = 0;
  100433. /**
  100434. * Event that fires each time the gizmo snaps to a new location.
  100435. * * snapDistance is the the change in distance
  100436. */
  100437. _this.onSnapObservable = new BABYLON.Observable();
  100438. /**
  100439. * If the scaling operation should be done on all axis (default: false)
  100440. */
  100441. _this.uniformScaling = false;
  100442. // Create Material
  100443. _this._coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100444. _this._coloredMaterial.disableLighting = true;
  100445. _this._coloredMaterial.emissiveColor = color;
  100446. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100447. hoverMaterial.disableLighting = true;
  100448. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100449. // Build mesh on root node
  100450. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100451. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.4 }, gizmoLayer.utilityLayerScene);
  100452. var arrowTail = BABYLON.MeshBuilder.CreateLines("yPosMesh", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 1.1, 0)] }, gizmoLayer.utilityLayerScene);
  100453. arrowTail.color = _this._coloredMaterial.emissiveColor;
  100454. arrow.addChild(arrowMesh);
  100455. arrow.addChild(arrowTail);
  100456. // Position arrow pointing in its drag axis
  100457. arrowMesh.scaling.scaleInPlace(0.1);
  100458. arrowMesh.material = _this._coloredMaterial;
  100459. arrowMesh.rotation.x = Math.PI / 2;
  100460. arrowMesh.position.z += 0.3;
  100461. arrowTail.scaling.scaleInPlace(0.26);
  100462. arrowTail.rotation.x = Math.PI / 2;
  100463. arrowTail.material = _this._coloredMaterial;
  100464. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  100465. _this._rootMesh.addChild(arrow);
  100466. arrow.scaling.scaleInPlace(1 / 3);
  100467. // Add drag behavior to handle events when the gizmo is dragged
  100468. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  100469. _this.dragBehavior.moveAttached = false;
  100470. _this._rootMesh.addBehavior(_this.dragBehavior);
  100471. var currentSnapDragDistance = 0;
  100472. var tmpVector = new BABYLON.Vector3();
  100473. var tmpSnapEvent = { snapDistance: 0 };
  100474. _this.dragBehavior.onDragObservable.add(function (event) {
  100475. if (_this.attachedMesh) {
  100476. // Snapping logic
  100477. var snapped = false;
  100478. var dragSteps = 0;
  100479. if (_this.uniformScaling) {
  100480. _this.attachedMesh.scaling.normalizeToRef(tmpVector);
  100481. if (tmpVector.y < 0) {
  100482. tmpVector.scaleInPlace(-1);
  100483. }
  100484. }
  100485. else {
  100486. tmpVector.copyFrom(dragAxis);
  100487. }
  100488. if (_this.snapDistance == 0) {
  100489. tmpVector.scaleToRef(event.dragDistance, tmpVector);
  100490. }
  100491. else {
  100492. currentSnapDragDistance += event.dragDistance;
  100493. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100494. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100495. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100496. tmpVector.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  100497. snapped = true;
  100498. }
  100499. else {
  100500. tmpVector.scaleInPlace(0);
  100501. }
  100502. }
  100503. _this.attachedMesh.scaling.addInPlace(tmpVector);
  100504. if (snapped) {
  100505. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  100506. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100507. }
  100508. }
  100509. });
  100510. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100511. if (_this._customMeshSet) {
  100512. return;
  100513. }
  100514. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100515. var material = isHovered ? hoverMaterial : _this._coloredMaterial;
  100516. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100517. m.material = material;
  100518. if (m.color) {
  100519. m.color = material.emissiveColor;
  100520. }
  100521. });
  100522. });
  100523. return _this;
  100524. }
  100525. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  100526. if (this.dragBehavior) {
  100527. this.dragBehavior.enabled = value ? true : false;
  100528. }
  100529. };
  100530. /**
  100531. * Disposes of the gizmo
  100532. */
  100533. AxisScaleGizmo.prototype.dispose = function () {
  100534. this.onSnapObservable.clear();
  100535. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100536. this.dragBehavior.detach();
  100537. _super.prototype.dispose.call(this);
  100538. };
  100539. /**
  100540. * Disposes and replaces the current meshes in the gizmo with the specified mesh
  100541. * @param mesh The mesh to replace the default mesh of the gizmo
  100542. * @param useGizmoMaterial If the gizmo's default material should be used (default: false)
  100543. */
  100544. AxisScaleGizmo.prototype.setCustomMesh = function (mesh, useGizmoMaterial) {
  100545. var _this = this;
  100546. if (useGizmoMaterial === void 0) { useGizmoMaterial = false; }
  100547. _super.prototype.setCustomMesh.call(this, mesh);
  100548. if (useGizmoMaterial) {
  100549. this._rootMesh.getChildMeshes().forEach(function (m) {
  100550. m.material = _this._coloredMaterial;
  100551. if (m.color) {
  100552. m.color = _this._coloredMaterial.emissiveColor;
  100553. }
  100554. });
  100555. this._customMeshSet = false;
  100556. }
  100557. };
  100558. return AxisScaleGizmo;
  100559. }(BABYLON.Gizmo));
  100560. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  100561. })(BABYLON || (BABYLON = {}));
  100562. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  100563. var BABYLON;
  100564. (function (BABYLON) {
  100565. /**
  100566. * Single plane rotation gizmo
  100567. */
  100568. var PlaneRotationGizmo = /** @class */ (function (_super) {
  100569. __extends(PlaneRotationGizmo, _super);
  100570. /**
  100571. * Creates a PlaneRotationGizmo
  100572. * @param gizmoLayer The utility layer the gizmo will be added to
  100573. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  100574. * @param color The color of the gizmo
  100575. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100576. */
  100577. function PlaneRotationGizmo(planeNormal, color, gizmoLayer, tessellation) {
  100578. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  100579. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100580. if (tessellation === void 0) { tessellation = 32; }
  100581. var _this = _super.call(this, gizmoLayer) || this;
  100582. _this._pointerObserver = null;
  100583. /**
  100584. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  100585. */
  100586. _this.snapDistance = 0;
  100587. /**
  100588. * Event that fires each time the gizmo snaps to a new location.
  100589. * * snapDistance is the the change in distance
  100590. */
  100591. _this.onSnapObservable = new BABYLON.Observable();
  100592. // Create Material
  100593. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100594. coloredMaterial.disableLighting = true;
  100595. coloredMaterial.emissiveColor = color;
  100596. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  100597. hoverMaterial.disableLighting = true;
  100598. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.3, 0.3, 0.3));
  100599. // Build mesh on root node
  100600. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  100601. // Create circle out of lines
  100602. var radius = 0.8;
  100603. var points = new Array();
  100604. for (var i = 0; i < tessellation; i++) {
  100605. var radian = (2 * Math.PI) * (i / (tessellation - 1));
  100606. points.push(new BABYLON.Vector3(radius * Math.sin(radian), 0, radius * Math.cos(radian)));
  100607. }
  100608. var rotationMesh = BABYLON.Mesh.CreateLines("", points, gizmoLayer.utilityLayerScene);
  100609. rotationMesh.color = coloredMaterial.emissiveColor;
  100610. // Position arrow pointing in its drag axis
  100611. rotationMesh.scaling.scaleInPlace(0.26);
  100612. rotationMesh.material = coloredMaterial;
  100613. rotationMesh.rotation.x = Math.PI / 2;
  100614. parentMesh.addChild(rotationMesh);
  100615. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  100616. _this._rootMesh.addChild(parentMesh);
  100617. parentMesh.scaling.scaleInPlace(1 / 3);
  100618. // Add drag behavior to handle events when the gizmo is dragged
  100619. _this.dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  100620. _this.dragBehavior.moveAttached = false;
  100621. _this.dragBehavior.maxDragAngle = Math.PI * 9 / 20;
  100622. _this.dragBehavior._useAlternatePickedPointAboveMaxDragAngle = true;
  100623. _this._rootMesh.addBehavior(_this.dragBehavior);
  100624. var lastDragPosition = new BABYLON.Vector3();
  100625. _this.dragBehavior.onDragStartObservable.add(function (e) {
  100626. if (_this.attachedMesh) {
  100627. lastDragPosition.copyFrom(e.dragPlanePoint);
  100628. }
  100629. });
  100630. var rotationMatrix = new BABYLON.Matrix();
  100631. var planeNormalTowardsCamera = new BABYLON.Vector3();
  100632. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  100633. var tmpSnapEvent = { snapDistance: 0 };
  100634. var currentSnapDragDistance = 0;
  100635. var tmpMatrix = new BABYLON.Matrix();
  100636. var tmpVector = new BABYLON.Vector3();
  100637. var amountToRotate = new BABYLON.Quaternion();
  100638. _this.dragBehavior.onDragObservable.add(function (event) {
  100639. if (_this.attachedMesh) {
  100640. if (!_this.attachedMesh.rotationQuaternion) {
  100641. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  100642. }
  100643. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  100644. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.absolutePosition).normalize();
  100645. var originalVector = lastDragPosition.subtract(_this.attachedMesh.absolutePosition).normalize();
  100646. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  100647. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  100648. var angle = Math.atan2(cross.length(), dot);
  100649. planeNormalTowardsCamera.copyFrom(planeNormal);
  100650. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  100651. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100652. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  100653. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  100654. }
  100655. // Flip up vector depending on which side the camera is on
  100656. if (gizmoLayer.utilityLayerScene.activeCamera) {
  100657. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  100658. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  100659. planeNormalTowardsCamera.scaleInPlace(-1);
  100660. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  100661. }
  100662. }
  100663. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  100664. if (halfCircleSide)
  100665. angle = -angle;
  100666. // Snapping logic
  100667. var snapped = false;
  100668. if (_this.snapDistance != 0) {
  100669. currentSnapDragDistance += angle;
  100670. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  100671. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  100672. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  100673. angle = _this.snapDistance * dragSteps;
  100674. snapped = true;
  100675. }
  100676. else {
  100677. angle = 0;
  100678. }
  100679. }
  100680. // If the mesh has a parent, convert needed world rotation to local rotation
  100681. tmpMatrix.reset();
  100682. if (_this.attachedMesh.parent) {
  100683. _this.attachedMesh.parent.computeWorldMatrix().invertToRef(tmpMatrix);
  100684. tmpMatrix.getRotationMatrixToRef(tmpMatrix);
  100685. BABYLON.Vector3.TransformCoordinatesToRef(planeNormalTowardsCamera, tmpMatrix, planeNormalTowardsCamera);
  100686. }
  100687. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  100688. var quaternionCoefficient = Math.sin(angle / 2);
  100689. amountToRotate.set(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  100690. // 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
  100691. if (tmpMatrix.determinant() > 0) {
  100692. amountToRotate.toEulerAnglesToRef(tmpVector);
  100693. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpVector.y, -tmpVector.x, -tmpVector.z, amountToRotate);
  100694. }
  100695. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  100696. // Rotate selected mesh quaternion over fixed axis
  100697. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  100698. }
  100699. else {
  100700. // Rotate selected mesh quaternion over rotated axis
  100701. amountToRotate.multiplyToRef(_this.attachedMesh.rotationQuaternion, _this.attachedMesh.rotationQuaternion);
  100702. }
  100703. lastDragPosition.copyFrom(event.dragPlanePoint);
  100704. if (snapped) {
  100705. tmpSnapEvent.snapDistance = angle;
  100706. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  100707. }
  100708. }
  100709. });
  100710. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  100711. if (_this._customMeshSet) {
  100712. return;
  100713. }
  100714. var isHovered = pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1);
  100715. var material = isHovered ? hoverMaterial : coloredMaterial;
  100716. _this._rootMesh.getChildMeshes().forEach(function (m) {
  100717. m.material = material;
  100718. if (m.color) {
  100719. m.color = material.emissiveColor;
  100720. }
  100721. });
  100722. });
  100723. return _this;
  100724. }
  100725. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  100726. if (this.dragBehavior) {
  100727. this.dragBehavior.enabled = value ? true : false;
  100728. }
  100729. };
  100730. /**
  100731. * Disposes of the gizmo
  100732. */
  100733. PlaneRotationGizmo.prototype.dispose = function () {
  100734. this.onSnapObservable.clear();
  100735. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  100736. this.dragBehavior.detach();
  100737. _super.prototype.dispose.call(this);
  100738. };
  100739. return PlaneRotationGizmo;
  100740. }(BABYLON.Gizmo));
  100741. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  100742. })(BABYLON || (BABYLON = {}));
  100743. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  100744. var BABYLON;
  100745. (function (BABYLON) {
  100746. /**
  100747. * Gizmo that enables dragging a mesh along 3 axis
  100748. */
  100749. var PositionGizmo = /** @class */ (function (_super) {
  100750. __extends(PositionGizmo, _super);
  100751. /**
  100752. * Creates a PositionGizmo
  100753. * @param gizmoLayer The utility layer the gizmo will be added to
  100754. */
  100755. function PositionGizmo(gizmoLayer) {
  100756. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100757. var _this = _super.call(this, gizmoLayer) || this;
  100758. _this.xGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100759. _this.yGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100760. _this.zGizmo = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100761. _this.attachedMesh = null;
  100762. return _this;
  100763. }
  100764. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  100765. set: function (mesh) {
  100766. if (this.xGizmo) {
  100767. this.xGizmo.attachedMesh = mesh;
  100768. this.yGizmo.attachedMesh = mesh;
  100769. this.zGizmo.attachedMesh = mesh;
  100770. }
  100771. },
  100772. enumerable: true,
  100773. configurable: true
  100774. });
  100775. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100776. get: function () {
  100777. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100778. },
  100779. set: function (value) {
  100780. if (this.xGizmo) {
  100781. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100782. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100783. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100784. }
  100785. },
  100786. enumerable: true,
  100787. configurable: true
  100788. });
  100789. Object.defineProperty(PositionGizmo.prototype, "snapDistance", {
  100790. get: function () {
  100791. return this.xGizmo.snapDistance;
  100792. },
  100793. /**
  100794. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100795. */
  100796. set: function (value) {
  100797. if (this.xGizmo) {
  100798. this.xGizmo.snapDistance = value;
  100799. this.yGizmo.snapDistance = value;
  100800. this.zGizmo.snapDistance = value;
  100801. }
  100802. },
  100803. enumerable: true,
  100804. configurable: true
  100805. });
  100806. Object.defineProperty(PositionGizmo.prototype, "scaleRatio", {
  100807. get: function () {
  100808. return this.xGizmo.scaleRatio;
  100809. },
  100810. /**
  100811. * Ratio for the scale of the gizmo (Default: 1)
  100812. */
  100813. set: function (value) {
  100814. if (this.xGizmo) {
  100815. this.xGizmo.scaleRatio = value;
  100816. this.yGizmo.scaleRatio = value;
  100817. this.zGizmo.scaleRatio = value;
  100818. }
  100819. },
  100820. enumerable: true,
  100821. configurable: true
  100822. });
  100823. /**
  100824. * Disposes of the gizmo
  100825. */
  100826. PositionGizmo.prototype.dispose = function () {
  100827. this.xGizmo.dispose();
  100828. this.yGizmo.dispose();
  100829. this.zGizmo.dispose();
  100830. };
  100831. /**
  100832. * CustomMeshes are not supported by this gizmo
  100833. * @param mesh The mesh to replace the default mesh of the gizmo
  100834. */
  100835. PositionGizmo.prototype.setCustomMesh = function (mesh) {
  100836. 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)");
  100837. };
  100838. return PositionGizmo;
  100839. }(BABYLON.Gizmo));
  100840. BABYLON.PositionGizmo = PositionGizmo;
  100841. })(BABYLON || (BABYLON = {}));
  100842. //# sourceMappingURL=babylon.positionGizmo.js.map
  100843. var BABYLON;
  100844. (function (BABYLON) {
  100845. /**
  100846. * Gizmo that enables rotating a mesh along 3 axis
  100847. */
  100848. var RotationGizmo = /** @class */ (function (_super) {
  100849. __extends(RotationGizmo, _super);
  100850. /**
  100851. * Creates a RotationGizmo
  100852. * @param gizmoLayer The utility layer the gizmo will be added to
  100853. * @param tessellation Amount of tessellation to be used when creating rotation circles
  100854. */
  100855. function RotationGizmo(gizmoLayer, tessellation) {
  100856. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100857. if (tessellation === void 0) { tessellation = 32; }
  100858. var _this = _super.call(this, gizmoLayer) || this;
  100859. _this.xGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer, tessellation);
  100860. _this.yGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer, tessellation);
  100861. _this.zGizmo = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer, tessellation);
  100862. _this.attachedMesh = null;
  100863. return _this;
  100864. }
  100865. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  100866. set: function (mesh) {
  100867. if (this.xGizmo) {
  100868. this.xGizmo.attachedMesh = mesh;
  100869. this.yGizmo.attachedMesh = mesh;
  100870. this.zGizmo.attachedMesh = mesh;
  100871. }
  100872. },
  100873. enumerable: true,
  100874. configurable: true
  100875. });
  100876. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100877. get: function () {
  100878. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100879. },
  100880. set: function (value) {
  100881. if (this.xGizmo) {
  100882. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100883. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100884. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100885. }
  100886. },
  100887. enumerable: true,
  100888. configurable: true
  100889. });
  100890. Object.defineProperty(RotationGizmo.prototype, "snapDistance", {
  100891. get: function () {
  100892. return this.xGizmo.snapDistance;
  100893. },
  100894. /**
  100895. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  100896. */
  100897. set: function (value) {
  100898. if (this.xGizmo) {
  100899. this.xGizmo.snapDistance = value;
  100900. this.yGizmo.snapDistance = value;
  100901. this.zGizmo.snapDistance = value;
  100902. }
  100903. },
  100904. enumerable: true,
  100905. configurable: true
  100906. });
  100907. Object.defineProperty(RotationGizmo.prototype, "scaleRatio", {
  100908. get: function () {
  100909. return this.xGizmo.scaleRatio;
  100910. },
  100911. /**
  100912. * Ratio for the scale of the gizmo (Default: 1)
  100913. */
  100914. set: function (value) {
  100915. if (this.xGizmo) {
  100916. this.xGizmo.scaleRatio = value;
  100917. this.yGizmo.scaleRatio = value;
  100918. this.zGizmo.scaleRatio = value;
  100919. }
  100920. },
  100921. enumerable: true,
  100922. configurable: true
  100923. });
  100924. /**
  100925. * Disposes of the gizmo
  100926. */
  100927. RotationGizmo.prototype.dispose = function () {
  100928. this.xGizmo.dispose();
  100929. this.yGizmo.dispose();
  100930. this.zGizmo.dispose();
  100931. };
  100932. /**
  100933. * CustomMeshes are not supported by this gizmo
  100934. * @param mesh The mesh to replace the default mesh of the gizmo
  100935. */
  100936. RotationGizmo.prototype.setCustomMesh = function (mesh) {
  100937. 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)");
  100938. };
  100939. return RotationGizmo;
  100940. }(BABYLON.Gizmo));
  100941. BABYLON.RotationGizmo = RotationGizmo;
  100942. })(BABYLON || (BABYLON = {}));
  100943. //# sourceMappingURL=babylon.rotationGizmo.js.map
  100944. var BABYLON;
  100945. (function (BABYLON) {
  100946. /**
  100947. * Gizmo that enables scaling a mesh along 3 axis
  100948. */
  100949. var ScaleGizmo = /** @class */ (function (_super) {
  100950. __extends(ScaleGizmo, _super);
  100951. /**
  100952. * Creates a ScaleGizmo
  100953. * @param gizmoLayer The utility layer the gizmo will be added to
  100954. */
  100955. function ScaleGizmo(gizmoLayer) {
  100956. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  100957. var _this = _super.call(this, gizmoLayer) || this;
  100958. _this.xGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  100959. _this.yGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  100960. _this.zGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  100961. // Create uniform scale gizmo
  100962. _this.uniformScaleGizmo = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Yellow().scale(0.5), gizmoLayer);
  100963. _this.uniformScaleGizmo.updateGizmoRotationToMatchAttachedMesh = false;
  100964. _this.uniformScaleGizmo.uniformScaling = true;
  100965. var uniformScalingMesh = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  100966. uniformScalingMesh.scaling.scaleInPlace(0.02);
  100967. uniformScalingMesh.visibility = 0;
  100968. var octahedron = BABYLON.Mesh.CreatePolyhedron("", { type: 1 }, _this.uniformScaleGizmo.gizmoLayer.utilityLayerScene);
  100969. octahedron.scaling.scaleInPlace(0.007);
  100970. uniformScalingMesh.addChild(octahedron);
  100971. _this.uniformScaleGizmo.setCustomMesh(uniformScalingMesh, true);
  100972. _this.attachedMesh = null;
  100973. return _this;
  100974. }
  100975. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  100976. set: function (mesh) {
  100977. if (this.xGizmo) {
  100978. this.xGizmo.attachedMesh = mesh;
  100979. this.yGizmo.attachedMesh = mesh;
  100980. this.zGizmo.attachedMesh = mesh;
  100981. this.uniformScaleGizmo.attachedMesh = mesh;
  100982. }
  100983. },
  100984. enumerable: true,
  100985. configurable: true
  100986. });
  100987. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  100988. get: function () {
  100989. return this.xGizmo.updateGizmoRotationToMatchAttachedMesh;
  100990. },
  100991. set: function (value) {
  100992. if (!value) {
  100993. BABYLON.Tools.Warn("Setting updateGizmoRotationToMatchAttachedMesh = false on scaling gizmo is not supported.");
  100994. }
  100995. if (this.xGizmo) {
  100996. this.xGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100997. this.yGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100998. this.zGizmo.updateGizmoRotationToMatchAttachedMesh = value;
  100999. }
  101000. },
  101001. enumerable: true,
  101002. configurable: true
  101003. });
  101004. Object.defineProperty(ScaleGizmo.prototype, "snapDistance", {
  101005. get: function () {
  101006. return this.xGizmo.snapDistance;
  101007. },
  101008. /**
  101009. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  101010. */
  101011. set: function (value) {
  101012. if (this.xGizmo) {
  101013. this.xGizmo.snapDistance = value;
  101014. this.yGizmo.snapDistance = value;
  101015. this.zGizmo.snapDistance = value;
  101016. this.uniformScaleGizmo.snapDistance = value;
  101017. }
  101018. },
  101019. enumerable: true,
  101020. configurable: true
  101021. });
  101022. Object.defineProperty(ScaleGizmo.prototype, "scaleRatio", {
  101023. get: function () {
  101024. return this.xGizmo.scaleRatio;
  101025. },
  101026. /**
  101027. * Ratio for the scale of the gizmo (Default: 1)
  101028. */
  101029. set: function (value) {
  101030. if (this.xGizmo) {
  101031. this.xGizmo.scaleRatio = value;
  101032. this.yGizmo.scaleRatio = value;
  101033. this.zGizmo.scaleRatio = value;
  101034. this.uniformScaleGizmo.scaleRatio = value;
  101035. }
  101036. },
  101037. enumerable: true,
  101038. configurable: true
  101039. });
  101040. /**
  101041. * Disposes of the gizmo
  101042. */
  101043. ScaleGizmo.prototype.dispose = function () {
  101044. this.xGizmo.dispose();
  101045. this.yGizmo.dispose();
  101046. this.zGizmo.dispose();
  101047. this.uniformScaleGizmo.dispose();
  101048. };
  101049. return ScaleGizmo;
  101050. }(BABYLON.Gizmo));
  101051. BABYLON.ScaleGizmo = ScaleGizmo;
  101052. })(BABYLON || (BABYLON = {}));
  101053. //# sourceMappingURL=babylon.scaleGizmo.js.map
  101054. var BABYLON;
  101055. (function (BABYLON) {
  101056. /**
  101057. * Bounding box gizmo
  101058. */
  101059. var BoundingBoxGizmo = /** @class */ (function (_super) {
  101060. __extends(BoundingBoxGizmo, _super);
  101061. /**
  101062. * Creates an BoundingBoxGizmo
  101063. * @param gizmoLayer The utility layer the gizmo will be added to
  101064. * @param color The color of the gizmo
  101065. */
  101066. function BoundingBoxGizmo(color, gizmoLayer) {
  101067. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  101068. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultKeepDepthUtilityLayer; }
  101069. var _this = _super.call(this, gizmoLayer) || this;
  101070. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  101071. _this._renderObserver = null;
  101072. _this._pointerObserver = null;
  101073. _this._scaleDragSpeed = 0.2;
  101074. _this._tmpQuaternion = new BABYLON.Quaternion();
  101075. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  101076. _this._tmpRotationMatrix = new BABYLON.Matrix();
  101077. /**
  101078. * 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)
  101079. */
  101080. _this.ignoreChildren = false;
  101081. /**
  101082. * 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)
  101083. */
  101084. _this.includeChildPredicate = null;
  101085. /**
  101086. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  101087. */
  101088. _this.rotationSphereSize = 0.1;
  101089. /**
  101090. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  101091. */
  101092. _this.scaleBoxSize = 0.1;
  101093. /**
  101094. * 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)
  101095. */
  101096. _this.fixedDragMeshScreenSize = false;
  101097. /**
  101098. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  101099. */
  101100. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  101101. /**
  101102. * Fired when a rotation sphere or scale box is dragged
  101103. */
  101104. _this.onDragStartObservable = new BABYLON.Observable();
  101105. /**
  101106. * Fired when a scale box is dragged
  101107. */
  101108. _this.onScaleBoxDragObservable = new BABYLON.Observable();
  101109. /**
  101110. * Fired when a scale box drag is ended
  101111. */
  101112. _this.onScaleBoxDragEndObservable = new BABYLON.Observable();
  101113. /**
  101114. * Fired when a rotation sphere is dragged
  101115. */
  101116. _this.onRotationSphereDragObservable = new BABYLON.Observable();
  101117. /**
  101118. * Fired when a rotation sphere drag is ended
  101119. */
  101120. _this.onRotationSphereDragEndObservable = new BABYLON.Observable();
  101121. /**
  101122. * 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)
  101123. */
  101124. _this.scalePivot = null;
  101125. _this._existingMeshScale = new BABYLON.Vector3();
  101126. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  101127. _this._updateScale = false;
  101128. _this._anchorMesh = new BABYLON.AbstractMesh("anchor", gizmoLayer.utilityLayerScene);
  101129. // Create Materials
  101130. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101131. coloredMaterial.disableLighting = true;
  101132. coloredMaterial.emissiveColor = color;
  101133. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  101134. hoverColoredMaterial.disableLighting = true;
  101135. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.3, 0.3, 0.3));
  101136. // Build bounding box out of lines
  101137. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101138. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  101139. var lines = [];
  101140. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  101141. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  101142. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  101143. 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));
  101144. 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));
  101145. 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));
  101146. 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));
  101147. 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));
  101148. 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));
  101149. 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));
  101150. 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));
  101151. 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));
  101152. lines.forEach(function (l) {
  101153. l.color = color;
  101154. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  101155. l.isPickable = false;
  101156. _this._lineBoundingBox.addChild(l);
  101157. });
  101158. _this._rootMesh.addChild(_this._lineBoundingBox);
  101159. // Create rotation spheres
  101160. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101161. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  101162. var _loop_1 = function (i_1) {
  101163. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  101164. sphere.rotationQuaternion = new BABYLON.Quaternion();
  101165. sphere.material = coloredMaterial;
  101166. // Drag behavior
  101167. _dragBehavior = new BABYLON.PointerDragBehavior({});
  101168. _dragBehavior.moveAttached = false;
  101169. _dragBehavior.updateDragPlane = false;
  101170. sphere.addBehavior(_dragBehavior);
  101171. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  101172. var totalTurnAmountOfDrag = 0;
  101173. _dragBehavior.onDragStartObservable.add(function (event) {
  101174. startingTurnDirection.copyFrom(sphere.forward);
  101175. totalTurnAmountOfDrag = 0;
  101176. });
  101177. _dragBehavior.onDragObservable.add(function (event) {
  101178. _this.onRotationSphereDragObservable.notifyObservers({});
  101179. if (_this.attachedMesh) {
  101180. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101181. var worldDragDirection = startingTurnDirection;
  101182. // Project the world right on to the drag plane
  101183. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  101184. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  101185. // project drag delta on to the resulting drag axis and rotate based on that
  101186. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  101187. // Make rotation relative to size of mesh.
  101188. projectDist = (projectDist / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101189. // Rotate based on axis
  101190. if (!_this.attachedMesh.rotationQuaternion) {
  101191. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  101192. }
  101193. if (!_this._anchorMesh.rotationQuaternion) {
  101194. _this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this._anchorMesh.rotation.y, _this._anchorMesh.rotation.x, _this._anchorMesh.rotation.z);
  101195. }
  101196. // Do not allow the object to turn more than a full circle
  101197. totalTurnAmountOfDrag += projectDist;
  101198. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  101199. if (i_1 >= 8) {
  101200. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  101201. }
  101202. else if (i_1 >= 4) {
  101203. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  101204. }
  101205. else {
  101206. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  101207. }
  101208. // Rotate around center of bounding box
  101209. _this._anchorMesh.addChild(_this.attachedMesh);
  101210. _this._anchorMesh.rotationQuaternion.multiplyToRef(_this._tmpQuaternion, _this._anchorMesh.rotationQuaternion);
  101211. _this._anchorMesh.removeChild(_this.attachedMesh);
  101212. }
  101213. _this.updateBoundingBox();
  101214. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101215. }
  101216. });
  101217. // Selection/deselection
  101218. _dragBehavior.onDragStartObservable.add(function () {
  101219. _this.onDragStartObservable.notifyObservers({});
  101220. _this._selectNode(sphere);
  101221. });
  101222. _dragBehavior.onDragEndObservable.add(function () {
  101223. _this.onRotationSphereDragEndObservable.notifyObservers({});
  101224. _this._selectNode(null);
  101225. });
  101226. this_1._rotateSpheresParent.addChild(sphere);
  101227. };
  101228. var this_1 = this, _dragBehavior;
  101229. for (var i_1 = 0; i_1 < 12; i_1++) {
  101230. _loop_1(i_1);
  101231. }
  101232. _this._rootMesh.addChild(_this._rotateSpheresParent);
  101233. // Create scale cubes
  101234. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  101235. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  101236. for (var i = 0; i < 2; i++) {
  101237. for (var j = 0; j < 2; j++) {
  101238. var _loop_2 = function () {
  101239. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  101240. box.material = coloredMaterial;
  101241. // Dragging logic
  101242. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  101243. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  101244. _dragBehavior.moveAttached = false;
  101245. box.addBehavior(_dragBehavior);
  101246. _dragBehavior.onDragObservable.add(function (event) {
  101247. _this.onScaleBoxDragObservable.notifyObservers({});
  101248. if (_this.attachedMesh) {
  101249. BoundingBoxGizmo._RemoveAndStorePivotPoint(_this.attachedMesh);
  101250. var relativeDragDistance = (event.dragDistance / _this._boundingDimensions.length()) * _this._anchorMesh.scaling.length();
  101251. var deltaScale = new BABYLON.Vector3(relativeDragDistance, relativeDragDistance, relativeDragDistance);
  101252. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  101253. _this.updateBoundingBox();
  101254. if (_this.scalePivot) {
  101255. _this.attachedMesh.getWorldMatrix().getRotationMatrixToRef(_this._tmpRotationMatrix);
  101256. // Move anchor to desired pivot point (Bottom left corner + dimension/2)
  101257. _this._boundingDimensions.scaleToRef(0.5, _this._tmpVector);
  101258. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101259. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101260. _this._boundingDimensions.multiplyToRef(_this.scalePivot, _this._tmpVector);
  101261. BABYLON.Vector3.TransformCoordinatesToRef(_this._tmpVector, _this._tmpRotationMatrix, _this._tmpVector);
  101262. _this._anchorMesh.position.addInPlace(_this._tmpVector);
  101263. }
  101264. else {
  101265. // Scale from the position of the opposite corner
  101266. box.absolutePosition.subtractToRef(_this._anchorMesh.position, _this._tmpVector);
  101267. _this._anchorMesh.position.subtractInPlace(_this._tmpVector);
  101268. }
  101269. _this._anchorMesh.addChild(_this.attachedMesh);
  101270. _this._anchorMesh.scaling.addInPlace(deltaScale);
  101271. if (_this._anchorMesh.scaling.x < 0 || _this._anchorMesh.scaling.y < 0 || _this._anchorMesh.scaling.z < 0) {
  101272. _this._anchorMesh.scaling.subtractInPlace(deltaScale);
  101273. }
  101274. _this._anchorMesh.removeChild(_this.attachedMesh);
  101275. BoundingBoxGizmo._RestorePivotPoint(_this.attachedMesh);
  101276. }
  101277. });
  101278. // Selection/deselection
  101279. _dragBehavior.onDragStartObservable.add(function () {
  101280. _this.onDragStartObservable.notifyObservers({});
  101281. _this._selectNode(box);
  101282. });
  101283. _dragBehavior.onDragEndObservable.add(function () {
  101284. _this.onScaleBoxDragEndObservable.notifyObservers({});
  101285. _this._selectNode(null);
  101286. });
  101287. this_2._scaleBoxesParent.addChild(box);
  101288. };
  101289. var this_2 = this, _dragBehavior;
  101290. for (var k = 0; k < 2; k++) {
  101291. _loop_2();
  101292. }
  101293. }
  101294. }
  101295. _this._rootMesh.addChild(_this._scaleBoxesParent);
  101296. // Hover color change
  101297. var pointerIds = new Array();
  101298. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  101299. if (!pointerIds[pointerInfo.event.pointerId]) {
  101300. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  101301. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  101302. pointerIds[pointerInfo.event.pointerId] = mesh;
  101303. mesh.material = hoverColoredMaterial;
  101304. }
  101305. });
  101306. }
  101307. else {
  101308. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  101309. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  101310. delete pointerIds[pointerInfo.event.pointerId];
  101311. }
  101312. }
  101313. });
  101314. // Update bounding box positions
  101315. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  101316. // Only update the bouding box if scaling has changed
  101317. if (_this.attachedMesh && !_this._existingMeshScale.equals(_this.attachedMesh.scaling)) {
  101318. _this.updateBoundingBox();
  101319. }
  101320. });
  101321. _this.updateBoundingBox();
  101322. return _this;
  101323. }
  101324. /** @hidden */
  101325. BoundingBoxGizmo._RemoveAndStorePivotPoint = function (mesh) {
  101326. if (mesh && BoundingBoxGizmo._PivotCached === 0) {
  101327. // Save old pivot and set pivot to 0,0,0
  101328. mesh.getPivotPointToRef(BoundingBoxGizmo._OldPivotPoint);
  101329. if (!BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0)) {
  101330. mesh.setPivotMatrix(BABYLON.Matrix.IdentityReadOnly);
  101331. BoundingBoxGizmo._OldPivotPoint.subtractToRef(mesh.getPivotPoint(), BoundingBoxGizmo._PivotTranslation);
  101332. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101333. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101334. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101335. mesh.position.addInPlace(BoundingBoxGizmo._PivotTmpVector);
  101336. }
  101337. }
  101338. BoundingBoxGizmo._PivotCached++;
  101339. };
  101340. /** @hidden */
  101341. BoundingBoxGizmo._RestorePivotPoint = function (mesh) {
  101342. if (mesh && !BoundingBoxGizmo._OldPivotPoint.equalsToFloats(0, 0, 0) && BoundingBoxGizmo._PivotCached === 1) {
  101343. mesh.setPivotPoint(BoundingBoxGizmo._OldPivotPoint);
  101344. BoundingBoxGizmo._PivotTmpVector.copyFromFloats(1, 1, 1);
  101345. BoundingBoxGizmo._PivotTmpVector.subtractInPlace(mesh.scaling);
  101346. BoundingBoxGizmo._PivotTmpVector.multiplyInPlace(BoundingBoxGizmo._PivotTranslation);
  101347. mesh.position.subtractInPlace(BoundingBoxGizmo._PivotTmpVector);
  101348. }
  101349. this._PivotCached--;
  101350. };
  101351. BoundingBoxGizmo.prototype._attachedMeshChanged = function (value) {
  101352. if (value) {
  101353. // Reset anchor mesh to match attached mesh's scale
  101354. // This is needed to avoid invalid box/sphere position on first drag
  101355. BoundingBoxGizmo._RemoveAndStorePivotPoint(value);
  101356. this._anchorMesh.addChild(value);
  101357. this._anchorMesh.removeChild(value);
  101358. BoundingBoxGizmo._RestorePivotPoint(value);
  101359. this.updateBoundingBox();
  101360. }
  101361. };
  101362. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  101363. this._rotateSpheresParent.getChildMeshes()
  101364. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  101365. m.isVisible = (!selectedMesh || m == selectedMesh);
  101366. });
  101367. };
  101368. /**
  101369. * Updates the bounding box information for the Gizmo
  101370. */
  101371. BoundingBoxGizmo.prototype.updateBoundingBox = function () {
  101372. if (this.attachedMesh) {
  101373. BoundingBoxGizmo._RemoveAndStorePivotPoint(this.attachedMesh);
  101374. this._update();
  101375. // Rotate based on axis
  101376. if (!this.attachedMesh.rotationQuaternion) {
  101377. this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.attachedMesh.rotation.y, this.attachedMesh.rotation.x, this.attachedMesh.rotation.z);
  101378. }
  101379. if (!this._anchorMesh.rotationQuaternion) {
  101380. this._anchorMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this._anchorMesh.rotation.y, this._anchorMesh.rotation.x, this._anchorMesh.rotation.z);
  101381. }
  101382. this._anchorMesh.rotationQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101383. // Store original position and reset mesh to origin before computing the bounding box
  101384. this._tmpQuaternion.copyFrom(this.attachedMesh.rotationQuaternion);
  101385. this._tmpVector.copyFrom(this.attachedMesh.position);
  101386. this.attachedMesh.rotationQuaternion.set(0, 0, 0, 1);
  101387. this.attachedMesh.position.set(0, 0, 0);
  101388. // Update bounding dimensions/positions
  101389. var boundingMinMax = this.attachedMesh.getHierarchyBoundingVectors(!this.ignoreChildren, this.includeChildPredicate);
  101390. boundingMinMax.max.subtractToRef(boundingMinMax.min, this._boundingDimensions);
  101391. // Update gizmo to match bounding box scaling and rotation
  101392. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  101393. 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);
  101394. this._rotateSpheresParent.position.copyFrom(this._lineBoundingBox.position);
  101395. this._scaleBoxesParent.position.copyFrom(this._lineBoundingBox.position);
  101396. this._lineBoundingBox.computeWorldMatrix();
  101397. this._anchorMesh.position.copyFrom(this._lineBoundingBox.absolutePosition);
  101398. // restore position/rotation values
  101399. this.attachedMesh.rotationQuaternion.copyFrom(this._tmpQuaternion);
  101400. this.attachedMesh.position.copyFrom(this._tmpVector);
  101401. }
  101402. // Update rotation sphere locations
  101403. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  101404. for (var i = 0; i < 3; i++) {
  101405. for (var j = 0; j < 2; j++) {
  101406. for (var k = 0; k < 2; k++) {
  101407. var index = ((i * 4) + (j * 2)) + k;
  101408. if (i == 0) {
  101409. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101410. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101411. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101412. }
  101413. if (i == 1) {
  101414. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  101415. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101416. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101417. }
  101418. if (i == 2) {
  101419. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  101420. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101421. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  101422. }
  101423. if (this.fixedDragMeshScreenSize) {
  101424. this._rootMesh.computeWorldMatrix();
  101425. this._rotateSpheresParent.computeWorldMatrix();
  101426. rotateSpheres[index].computeWorldMatrix();
  101427. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101428. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101429. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101430. }
  101431. else {
  101432. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  101433. }
  101434. }
  101435. }
  101436. }
  101437. // Update scale box locations
  101438. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  101439. for (var i = 0; i < 2; i++) {
  101440. for (var j = 0; j < 2; j++) {
  101441. for (var k = 0; k < 2; k++) {
  101442. var index = ((i * 4) + (j * 2)) + k;
  101443. if (scaleBoxes[index]) {
  101444. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  101445. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  101446. if (this.fixedDragMeshScreenSize) {
  101447. this._rootMesh.computeWorldMatrix();
  101448. this._scaleBoxesParent.computeWorldMatrix();
  101449. scaleBoxes[index].computeWorldMatrix();
  101450. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  101451. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  101452. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  101453. }
  101454. else {
  101455. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  101456. }
  101457. }
  101458. }
  101459. }
  101460. }
  101461. if (this.attachedMesh) {
  101462. this._existingMeshScale.copyFrom(this.attachedMesh.scaling);
  101463. BoundingBoxGizmo._RestorePivotPoint(this.attachedMesh);
  101464. }
  101465. };
  101466. /**
  101467. * Enables rotation on the specified axis and disables rotation on the others
  101468. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  101469. */
  101470. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  101471. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  101472. if (i < 4) {
  101473. m.setEnabled(axis.indexOf("x") != -1);
  101474. }
  101475. else if (i < 8) {
  101476. m.setEnabled(axis.indexOf("y") != -1);
  101477. }
  101478. else {
  101479. m.setEnabled(axis.indexOf("z") != -1);
  101480. }
  101481. });
  101482. };
  101483. /**
  101484. * Disposes of the gizmo
  101485. */
  101486. BoundingBoxGizmo.prototype.dispose = function () {
  101487. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  101488. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  101489. this._lineBoundingBox.dispose();
  101490. this._rotateSpheresParent.dispose();
  101491. this._scaleBoxesParent.dispose();
  101492. _super.prototype.dispose.call(this);
  101493. };
  101494. /**
  101495. * 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)
  101496. * @param mesh the mesh to wrap in the bounding box mesh and make not pickable
  101497. * @returns the bounding box mesh with the passed in mesh as a child
  101498. */
  101499. BoundingBoxGizmo.MakeNotPickableAndWrapInBoundingBox = function (mesh) {
  101500. var makeNotPickable = function (root) {
  101501. root.isPickable = false;
  101502. root.getChildMeshes().forEach(function (c) {
  101503. makeNotPickable(c);
  101504. });
  101505. };
  101506. makeNotPickable(mesh);
  101507. // Reset position to get boudning box from origin with no rotation
  101508. if (!mesh.rotationQuaternion) {
  101509. mesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(mesh.rotation.y, mesh.rotation.x, mesh.rotation.z);
  101510. }
  101511. var oldPos = mesh.position.clone();
  101512. var oldRot = mesh.rotationQuaternion.clone();
  101513. mesh.rotationQuaternion.set(0, 0, 0, 1);
  101514. mesh.position.set(0, 0, 0);
  101515. // Update bounding dimensions/positions
  101516. var box = BABYLON.MeshBuilder.CreateBox("box", { size: 1 }, mesh.getScene());
  101517. var boundingMinMax = mesh.getHierarchyBoundingVectors();
  101518. boundingMinMax.max.subtractToRef(boundingMinMax.min, box.scaling);
  101519. box.position.set((boundingMinMax.max.x + boundingMinMax.min.x) / 2, (boundingMinMax.max.y + boundingMinMax.min.y) / 2, (boundingMinMax.max.z + boundingMinMax.min.z) / 2);
  101520. // Restore original positions
  101521. mesh.addChild(box);
  101522. mesh.rotationQuaternion.copyFrom(oldRot);
  101523. mesh.position.copyFrom(oldPos);
  101524. // Reverse parenting
  101525. mesh.removeChild(box);
  101526. box.addChild(mesh);
  101527. box.visibility = 0;
  101528. return box;
  101529. };
  101530. /**
  101531. * CustomMeshes are not supported by this gizmo
  101532. * @param mesh The mesh to replace the default mesh of the gizmo
  101533. */
  101534. BoundingBoxGizmo.prototype.setCustomMesh = function (mesh) {
  101535. BABYLON.Tools.Error("Custom meshes are not supported on this gizmo");
  101536. };
  101537. // Stores the state of the pivot cache (_oldPivotPoint, _pivotTranslation)
  101538. // store/remove pivot point should only be applied during their outermost calls
  101539. BoundingBoxGizmo._PivotCached = 0;
  101540. BoundingBoxGizmo._OldPivotPoint = new BABYLON.Vector3();
  101541. BoundingBoxGizmo._PivotTranslation = new BABYLON.Vector3();
  101542. BoundingBoxGizmo._PivotTmpVector = new BABYLON.Vector3();
  101543. return BoundingBoxGizmo;
  101544. }(BABYLON.Gizmo));
  101545. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  101546. })(BABYLON || (BABYLON = {}));
  101547. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  101548. var BABYLON;
  101549. (function (BABYLON) {
  101550. /**
  101551. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  101552. */
  101553. var GizmoManager = /** @class */ (function () {
  101554. /**
  101555. * Instatiates a gizmo manager
  101556. * @param scene the scene to overlay the gizmos on top of
  101557. */
  101558. function GizmoManager(scene) {
  101559. var _this = this;
  101560. this.scene = scene;
  101561. this._gizmosEnabled = { positionGizmo: false, rotationGizmo: false, scaleGizmo: false, boundingBoxGizmo: false };
  101562. this._pointerObserver = null;
  101563. this._attachedMesh = null;
  101564. this._boundingBoxColor = BABYLON.Color3.FromHexString("#0984e3");
  101565. /**
  101566. * When bounding box gizmo is enabled, this can be used to track drag/end events
  101567. */
  101568. this.boundingBoxDragBehavior = new BABYLON.SixDofDragBehavior();
  101569. /**
  101570. * Array of meshes which will have the gizmo attached when a pointer selected them. If null, all meshes are attachable. (Default: null)
  101571. */
  101572. this.attachableMeshes = null;
  101573. /**
  101574. * If pointer events should perform attaching/detaching a gizmo, if false this can be done manually via attachToMesh. (Default: true)
  101575. */
  101576. this.usePointerToAttachGizmos = true;
  101577. this._defaultKeepDepthUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101578. this._defaultKeepDepthUtilityLayer.utilityLayerScene.autoClearDepthAndStencil = false;
  101579. this._defaultUtilityLayer = new BABYLON.UtilityLayerRenderer(scene);
  101580. this.gizmos = { positionGizmo: null, rotationGizmo: null, scaleGizmo: null, boundingBoxGizmo: null };
  101581. // Instatiate/dispose gizmos based on pointer actions
  101582. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  101583. if (!_this.usePointerToAttachGizmos) {
  101584. return;
  101585. }
  101586. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  101587. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  101588. var node = pointerInfo.pickInfo.pickedMesh;
  101589. if (_this.attachableMeshes == null) {
  101590. // Attach to the most parent node
  101591. while (node && node.parent != null) {
  101592. node = node.parent;
  101593. }
  101594. }
  101595. else {
  101596. // Attach to the parent node that is an attachableMesh
  101597. var found = false;
  101598. _this.attachableMeshes.forEach(function (mesh) {
  101599. if (node && (node == mesh || node.isDescendantOf(mesh))) {
  101600. node = mesh;
  101601. found = true;
  101602. }
  101603. });
  101604. if (!found) {
  101605. node = null;
  101606. }
  101607. }
  101608. if (node instanceof BABYLON.AbstractMesh) {
  101609. _this.attachToMesh(node);
  101610. }
  101611. else {
  101612. _this.attachToMesh(null);
  101613. }
  101614. }
  101615. else {
  101616. _this.attachToMesh(null);
  101617. }
  101618. }
  101619. });
  101620. }
  101621. /**
  101622. * Attaches a set of gizmos to the specified mesh
  101623. * @param mesh The mesh the gizmo's should be attached to
  101624. */
  101625. GizmoManager.prototype.attachToMesh = function (mesh) {
  101626. if (this._attachedMesh) {
  101627. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101628. }
  101629. this._attachedMesh = mesh;
  101630. for (var key in this.gizmos) {
  101631. var gizmo = (this.gizmos[key]);
  101632. if (gizmo && this._gizmosEnabled[key]) {
  101633. gizmo.attachedMesh = mesh;
  101634. }
  101635. }
  101636. if (this.boundingBoxGizmoEnabled && this._attachedMesh) {
  101637. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101638. }
  101639. };
  101640. Object.defineProperty(GizmoManager.prototype, "positionGizmoEnabled", {
  101641. get: function () {
  101642. return this._gizmosEnabled.positionGizmo;
  101643. },
  101644. /**
  101645. * If the position gizmo is enabled
  101646. */
  101647. set: function (value) {
  101648. if (value) {
  101649. if (!this.gizmos.positionGizmo) {
  101650. this.gizmos.positionGizmo = new BABYLON.PositionGizmo(this._defaultUtilityLayer);
  101651. }
  101652. this.gizmos.positionGizmo.attachedMesh = this._attachedMesh;
  101653. }
  101654. else if (this.gizmos.positionGizmo) {
  101655. this.gizmos.positionGizmo.attachedMesh = null;
  101656. }
  101657. this._gizmosEnabled.positionGizmo = value;
  101658. },
  101659. enumerable: true,
  101660. configurable: true
  101661. });
  101662. Object.defineProperty(GizmoManager.prototype, "rotationGizmoEnabled", {
  101663. get: function () {
  101664. return this._gizmosEnabled.rotationGizmo;
  101665. },
  101666. /**
  101667. * If the rotation gizmo is enabled
  101668. */
  101669. set: function (value) {
  101670. if (value) {
  101671. if (!this.gizmos.rotationGizmo) {
  101672. this.gizmos.rotationGizmo = new BABYLON.RotationGizmo(this._defaultUtilityLayer);
  101673. }
  101674. this.gizmos.rotationGizmo.attachedMesh = this._attachedMesh;
  101675. }
  101676. else if (this.gizmos.rotationGizmo) {
  101677. this.gizmos.rotationGizmo.attachedMesh = null;
  101678. }
  101679. this._gizmosEnabled.rotationGizmo = value;
  101680. },
  101681. enumerable: true,
  101682. configurable: true
  101683. });
  101684. Object.defineProperty(GizmoManager.prototype, "scaleGizmoEnabled", {
  101685. get: function () {
  101686. return this._gizmosEnabled.scaleGizmo;
  101687. },
  101688. /**
  101689. * If the scale gizmo is enabled
  101690. */
  101691. set: function (value) {
  101692. if (value) {
  101693. this.gizmos.scaleGizmo = this.gizmos.scaleGizmo || new BABYLON.ScaleGizmo(this._defaultUtilityLayer);
  101694. this.gizmos.scaleGizmo.attachedMesh = this._attachedMesh;
  101695. }
  101696. else if (this.gizmos.scaleGizmo) {
  101697. this.gizmos.scaleGizmo.attachedMesh = null;
  101698. }
  101699. this._gizmosEnabled.scaleGizmo = value;
  101700. },
  101701. enumerable: true,
  101702. configurable: true
  101703. });
  101704. Object.defineProperty(GizmoManager.prototype, "boundingBoxGizmoEnabled", {
  101705. get: function () {
  101706. return this._gizmosEnabled.boundingBoxGizmo;
  101707. },
  101708. /**
  101709. * If the boundingBox gizmo is enabled
  101710. */
  101711. set: function (value) {
  101712. if (value) {
  101713. this.gizmos.boundingBoxGizmo = this.gizmos.boundingBoxGizmo || new BABYLON.BoundingBoxGizmo(this._boundingBoxColor, this._defaultKeepDepthUtilityLayer);
  101714. this.gizmos.boundingBoxGizmo.attachedMesh = this._attachedMesh;
  101715. if (this._attachedMesh) {
  101716. this._attachedMesh.removeBehavior(this.boundingBoxDragBehavior);
  101717. this._attachedMesh.addBehavior(this.boundingBoxDragBehavior);
  101718. }
  101719. }
  101720. else if (this.gizmos.boundingBoxGizmo) {
  101721. this.gizmos.boundingBoxGizmo.attachedMesh = null;
  101722. }
  101723. this._gizmosEnabled.boundingBoxGizmo = value;
  101724. },
  101725. enumerable: true,
  101726. configurable: true
  101727. });
  101728. /**
  101729. * Disposes of the gizmo manager
  101730. */
  101731. GizmoManager.prototype.dispose = function () {
  101732. this.scene.onPointerObservable.remove(this._pointerObserver);
  101733. for (var key in this.gizmos) {
  101734. var gizmo = (this.gizmos[key]);
  101735. if (gizmo) {
  101736. gizmo.dispose();
  101737. }
  101738. }
  101739. this._defaultKeepDepthUtilityLayer.dispose();
  101740. this._defaultUtilityLayer.dispose();
  101741. this.boundingBoxDragBehavior.detach();
  101742. };
  101743. return GizmoManager;
  101744. }());
  101745. BABYLON.GizmoManager = GizmoManager;
  101746. })(BABYLON || (BABYLON = {}));
  101747. //# sourceMappingURL=babylon.gizmoManager.js.map
  101748. var BABYLON;
  101749. (function (BABYLON) {
  101750. /**
  101751. * Defines a target to use with MorphTargetManager
  101752. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  101753. */
  101754. var MorphTarget = /** @class */ (function () {
  101755. /**
  101756. * Creates a new MorphTarget
  101757. * @param name defines the name of the target
  101758. * @param influence defines the influence to use
  101759. */
  101760. function MorphTarget(
  101761. /** defines the name of the target */
  101762. name, influence, scene) {
  101763. if (influence === void 0) { influence = 0; }
  101764. if (scene === void 0) { scene = null; }
  101765. this.name = name;
  101766. /**
  101767. * Gets or sets the list of animations
  101768. */
  101769. this.animations = new Array();
  101770. this._positions = null;
  101771. this._normals = null;
  101772. this._tangents = null;
  101773. /**
  101774. * Observable raised when the influence changes
  101775. */
  101776. this.onInfluenceChanged = new BABYLON.Observable();
  101777. this._animationPropertiesOverride = null;
  101778. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  101779. this.influence = influence;
  101780. }
  101781. Object.defineProperty(MorphTarget.prototype, "influence", {
  101782. /**
  101783. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  101784. */
  101785. get: function () {
  101786. return this._influence;
  101787. },
  101788. set: function (influence) {
  101789. if (this._influence === influence) {
  101790. return;
  101791. }
  101792. var previous = this._influence;
  101793. this._influence = influence;
  101794. if (this.onInfluenceChanged.hasObservers) {
  101795. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  101796. }
  101797. },
  101798. enumerable: true,
  101799. configurable: true
  101800. });
  101801. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  101802. /**
  101803. * Gets or sets the animation properties override
  101804. */
  101805. get: function () {
  101806. if (!this._animationPropertiesOverride && this._scene) {
  101807. return this._scene.animationPropertiesOverride;
  101808. }
  101809. return this._animationPropertiesOverride;
  101810. },
  101811. set: function (value) {
  101812. this._animationPropertiesOverride = value;
  101813. },
  101814. enumerable: true,
  101815. configurable: true
  101816. });
  101817. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  101818. /**
  101819. * Gets a boolean defining if the target contains position data
  101820. */
  101821. get: function () {
  101822. return !!this._positions;
  101823. },
  101824. enumerable: true,
  101825. configurable: true
  101826. });
  101827. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  101828. /**
  101829. * Gets a boolean defining if the target contains normal data
  101830. */
  101831. get: function () {
  101832. return !!this._normals;
  101833. },
  101834. enumerable: true,
  101835. configurable: true
  101836. });
  101837. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  101838. /**
  101839. * Gets a boolean defining if the target contains tangent data
  101840. */
  101841. get: function () {
  101842. return !!this._tangents;
  101843. },
  101844. enumerable: true,
  101845. configurable: true
  101846. });
  101847. /**
  101848. * Affects position data to this target
  101849. * @param data defines the position data to use
  101850. */
  101851. MorphTarget.prototype.setPositions = function (data) {
  101852. this._positions = data;
  101853. };
  101854. /**
  101855. * Gets the position data stored in this target
  101856. * @returns a FloatArray containing the position data (or null if not present)
  101857. */
  101858. MorphTarget.prototype.getPositions = function () {
  101859. return this._positions;
  101860. };
  101861. /**
  101862. * Affects normal data to this target
  101863. * @param data defines the normal data to use
  101864. */
  101865. MorphTarget.prototype.setNormals = function (data) {
  101866. this._normals = data;
  101867. };
  101868. /**
  101869. * Gets the normal data stored in this target
  101870. * @returns a FloatArray containing the normal data (or null if not present)
  101871. */
  101872. MorphTarget.prototype.getNormals = function () {
  101873. return this._normals;
  101874. };
  101875. /**
  101876. * Affects tangent data to this target
  101877. * @param data defines the tangent data to use
  101878. */
  101879. MorphTarget.prototype.setTangents = function (data) {
  101880. this._tangents = data;
  101881. };
  101882. /**
  101883. * Gets the tangent data stored in this target
  101884. * @returns a FloatArray containing the tangent data (or null if not present)
  101885. */
  101886. MorphTarget.prototype.getTangents = function () {
  101887. return this._tangents;
  101888. };
  101889. /**
  101890. * Serializes the current target into a Serialization object
  101891. * @returns the serialized object
  101892. */
  101893. MorphTarget.prototype.serialize = function () {
  101894. var serializationObject = {};
  101895. serializationObject.name = this.name;
  101896. serializationObject.influence = this.influence;
  101897. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  101898. if (this.hasNormals) {
  101899. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  101900. }
  101901. if (this.hasTangents) {
  101902. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  101903. }
  101904. // Animations
  101905. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  101906. return serializationObject;
  101907. };
  101908. // Statics
  101909. /**
  101910. * Creates a new target from serialized data
  101911. * @param serializationObject defines the serialized data to use
  101912. * @returns a new MorphTarget
  101913. */
  101914. MorphTarget.Parse = function (serializationObject) {
  101915. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  101916. result.setPositions(serializationObject.positions);
  101917. if (serializationObject.normals) {
  101918. result.setNormals(serializationObject.normals);
  101919. }
  101920. if (serializationObject.tangents) {
  101921. result.setTangents(serializationObject.tangents);
  101922. }
  101923. // Animations
  101924. if (serializationObject.animations) {
  101925. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  101926. var parsedAnimation = serializationObject.animations[animationIndex];
  101927. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  101928. }
  101929. }
  101930. return result;
  101931. };
  101932. /**
  101933. * Creates a MorphTarget from mesh data
  101934. * @param mesh defines the source mesh
  101935. * @param name defines the name to use for the new target
  101936. * @param influence defines the influence to attach to the target
  101937. * @returns a new MorphTarget
  101938. */
  101939. MorphTarget.FromMesh = function (mesh, name, influence) {
  101940. if (!name) {
  101941. name = mesh.name;
  101942. }
  101943. var result = new MorphTarget(name, influence, mesh.getScene());
  101944. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  101945. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101946. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  101947. }
  101948. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  101949. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  101950. }
  101951. return result;
  101952. };
  101953. return MorphTarget;
  101954. }());
  101955. BABYLON.MorphTarget = MorphTarget;
  101956. })(BABYLON || (BABYLON = {}));
  101957. //# sourceMappingURL=babylon.morphTarget.js.map
  101958. var BABYLON;
  101959. (function (BABYLON) {
  101960. /**
  101961. * This class is used to deform meshes using morphing between different targets
  101962. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  101963. */
  101964. var MorphTargetManager = /** @class */ (function () {
  101965. /**
  101966. * Creates a new MorphTargetManager
  101967. * @param scene defines the current scene
  101968. */
  101969. function MorphTargetManager(scene) {
  101970. if (scene === void 0) { scene = null; }
  101971. this._targets = new Array();
  101972. this._targetObservable = new Array();
  101973. this._activeTargets = new BABYLON.SmartArray(16);
  101974. this._supportsNormals = false;
  101975. this._supportsTangents = false;
  101976. this._vertexCount = 0;
  101977. this._uniqueId = 0;
  101978. this._tempInfluences = new Array();
  101979. if (!scene) {
  101980. scene = BABYLON.Engine.LastCreatedScene;
  101981. }
  101982. this._scene = scene;
  101983. if (this._scene) {
  101984. this._scene.morphTargetManagers.push(this);
  101985. this._uniqueId = this._scene.getUniqueId();
  101986. }
  101987. }
  101988. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  101989. /**
  101990. * Gets the unique ID of this manager
  101991. */
  101992. get: function () {
  101993. return this._uniqueId;
  101994. },
  101995. enumerable: true,
  101996. configurable: true
  101997. });
  101998. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  101999. /**
  102000. * Gets the number of vertices handled by this manager
  102001. */
  102002. get: function () {
  102003. return this._vertexCount;
  102004. },
  102005. enumerable: true,
  102006. configurable: true
  102007. });
  102008. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  102009. /**
  102010. * Gets a boolean indicating if this manager supports morphing of normals
  102011. */
  102012. get: function () {
  102013. return this._supportsNormals;
  102014. },
  102015. enumerable: true,
  102016. configurable: true
  102017. });
  102018. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  102019. /**
  102020. * Gets a boolean indicating if this manager supports morphing of tangents
  102021. */
  102022. get: function () {
  102023. return this._supportsTangents;
  102024. },
  102025. enumerable: true,
  102026. configurable: true
  102027. });
  102028. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  102029. /**
  102030. * Gets the number of targets stored in this manager
  102031. */
  102032. get: function () {
  102033. return this._targets.length;
  102034. },
  102035. enumerable: true,
  102036. configurable: true
  102037. });
  102038. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  102039. /**
  102040. * Gets the number of influencers (ie. the number of targets with influences > 0)
  102041. */
  102042. get: function () {
  102043. return this._activeTargets.length;
  102044. },
  102045. enumerable: true,
  102046. configurable: true
  102047. });
  102048. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  102049. /**
  102050. * Gets the list of influences (one per target)
  102051. */
  102052. get: function () {
  102053. return this._influences;
  102054. },
  102055. enumerable: true,
  102056. configurable: true
  102057. });
  102058. /**
  102059. * Gets the active target at specified index. An active target is a target with an influence > 0
  102060. * @param index defines the index to check
  102061. * @returns the requested target
  102062. */
  102063. MorphTargetManager.prototype.getActiveTarget = function (index) {
  102064. return this._activeTargets.data[index];
  102065. };
  102066. /**
  102067. * Gets the target at specified index
  102068. * @param index defines the index to check
  102069. * @returns the requested target
  102070. */
  102071. MorphTargetManager.prototype.getTarget = function (index) {
  102072. return this._targets[index];
  102073. };
  102074. /**
  102075. * Add a new target to this manager
  102076. * @param target defines the target to add
  102077. */
  102078. MorphTargetManager.prototype.addTarget = function (target) {
  102079. var _this = this;
  102080. this._targets.push(target);
  102081. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  102082. _this._syncActiveTargets(needUpdate);
  102083. }));
  102084. this._syncActiveTargets(true);
  102085. };
  102086. /**
  102087. * Removes a target from the manager
  102088. * @param target defines the target to remove
  102089. */
  102090. MorphTargetManager.prototype.removeTarget = function (target) {
  102091. var index = this._targets.indexOf(target);
  102092. if (index >= 0) {
  102093. this._targets.splice(index, 1);
  102094. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  102095. this._syncActiveTargets(true);
  102096. }
  102097. };
  102098. /**
  102099. * Serializes the current manager into a Serialization object
  102100. * @returns the serialized object
  102101. */
  102102. MorphTargetManager.prototype.serialize = function () {
  102103. var serializationObject = {};
  102104. serializationObject.id = this.uniqueId;
  102105. serializationObject.targets = [];
  102106. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102107. var target = _a[_i];
  102108. serializationObject.targets.push(target.serialize());
  102109. }
  102110. return serializationObject;
  102111. };
  102112. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  102113. var influenceCount = 0;
  102114. this._activeTargets.reset();
  102115. this._supportsNormals = true;
  102116. this._supportsTangents = true;
  102117. this._vertexCount = 0;
  102118. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  102119. var target = _a[_i];
  102120. this._activeTargets.push(target);
  102121. this._tempInfluences[influenceCount++] = target.influence;
  102122. var positions = target.getPositions();
  102123. if (positions) {
  102124. this._supportsNormals = this._supportsNormals && target.hasNormals;
  102125. this._supportsTangents = this._supportsTangents && target.hasTangents;
  102126. var vertexCount = positions.length / 3;
  102127. if (this._vertexCount === 0) {
  102128. this._vertexCount = vertexCount;
  102129. }
  102130. else if (this._vertexCount !== vertexCount) {
  102131. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  102132. return;
  102133. }
  102134. }
  102135. }
  102136. if (!this._influences || this._influences.length !== influenceCount) {
  102137. this._influences = new Float32Array(influenceCount);
  102138. }
  102139. for (var index = 0; index < influenceCount; index++) {
  102140. this._influences[index] = this._tempInfluences[index];
  102141. }
  102142. if (needUpdate) {
  102143. this.synchronize();
  102144. }
  102145. };
  102146. /**
  102147. * Syncrhonize the targets with all the meshes using this morph target manager
  102148. */
  102149. MorphTargetManager.prototype.synchronize = function () {
  102150. if (!this._scene) {
  102151. return;
  102152. }
  102153. // Flag meshes as dirty to resync with the active targets
  102154. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  102155. var mesh = _a[_i];
  102156. if (mesh.morphTargetManager === this) {
  102157. mesh._syncGeometryWithMorphTargetManager();
  102158. }
  102159. }
  102160. };
  102161. // Statics
  102162. /**
  102163. * Creates a new MorphTargetManager from serialized data
  102164. * @param serializationObject defines the serialized data
  102165. * @param scene defines the hosting scene
  102166. * @returns the new MorphTargetManager
  102167. */
  102168. MorphTargetManager.Parse = function (serializationObject, scene) {
  102169. var result = new MorphTargetManager(scene);
  102170. result._uniqueId = serializationObject.id;
  102171. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  102172. var targetData = _a[_i];
  102173. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  102174. }
  102175. return result;
  102176. };
  102177. return MorphTargetManager;
  102178. }());
  102179. BABYLON.MorphTargetManager = MorphTargetManager;
  102180. })(BABYLON || (BABYLON = {}));
  102181. //# sourceMappingURL=babylon.morphTargetManager.js.map
  102182. var BABYLON;
  102183. (function (BABYLON) {
  102184. /**
  102185. * Octrees are a really powerful data structure that can quickly select entities based on space coordinates.
  102186. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102187. */
  102188. var Octree = /** @class */ (function () {
  102189. /**
  102190. * Creates a octree
  102191. * @see https://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102192. * @param creationFunc function to be used to instatiate the octree
  102193. * @param maxBlockCapacity defines the maximum number of meshes you want on your octree's leaves (default: 64)
  102194. * @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.)
  102195. */
  102196. function Octree(creationFunc, maxBlockCapacity,
  102197. /** 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.) */
  102198. maxDepth) {
  102199. if (maxDepth === void 0) { maxDepth = 2; }
  102200. this.maxDepth = maxDepth;
  102201. /**
  102202. * Content stored in the octree
  102203. */
  102204. this.dynamicContent = new Array();
  102205. this._maxBlockCapacity = maxBlockCapacity || 64;
  102206. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  102207. this._creationFunc = creationFunc;
  102208. }
  102209. // Methods
  102210. /**
  102211. * Updates the octree by adding blocks for the passed in meshes within the min and max world parameters
  102212. * @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);
  102213. * @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);
  102214. * @param entries meshes to be added to the octree blocks
  102215. */
  102216. Octree.prototype.update = function (worldMin, worldMax, entries) {
  102217. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  102218. };
  102219. /**
  102220. * Adds a mesh to the octree
  102221. * @param entry Mesh to add to the octree
  102222. */
  102223. Octree.prototype.addMesh = function (entry) {
  102224. for (var index = 0; index < this.blocks.length; index++) {
  102225. var block = this.blocks[index];
  102226. block.addEntry(entry);
  102227. }
  102228. };
  102229. /**
  102230. * Selects an array of meshes within the frustum
  102231. * @param frustumPlanes The frustum planes to use which will select all meshes within it
  102232. * @param allowDuplicate If duplicate objects are allowed in the resulting object array
  102233. * @returns array of meshes within the frustum
  102234. */
  102235. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  102236. this._selectionContent.reset();
  102237. for (var index = 0; index < this.blocks.length; index++) {
  102238. var block = this.blocks[index];
  102239. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  102240. }
  102241. if (allowDuplicate) {
  102242. this._selectionContent.concat(this.dynamicContent);
  102243. }
  102244. else {
  102245. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102246. }
  102247. return this._selectionContent;
  102248. };
  102249. /**
  102250. * Test if the octree intersect with the given bounding sphere and if yes, then add its content to the selection array
  102251. * @param sphereCenter defines the bounding sphere center
  102252. * @param sphereRadius defines the bounding sphere radius
  102253. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102254. * @returns an array of objects that intersect the sphere
  102255. */
  102256. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  102257. this._selectionContent.reset();
  102258. for (var index = 0; index < this.blocks.length; index++) {
  102259. var block = this.blocks[index];
  102260. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  102261. }
  102262. if (allowDuplicate) {
  102263. this._selectionContent.concat(this.dynamicContent);
  102264. }
  102265. else {
  102266. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102267. }
  102268. return this._selectionContent;
  102269. };
  102270. /**
  102271. * Test if the octree intersect with the given ray and if yes, then add its content to resulting array
  102272. * @param ray defines the ray to test with
  102273. * @returns array of intersected objects
  102274. */
  102275. Octree.prototype.intersectsRay = function (ray) {
  102276. this._selectionContent.reset();
  102277. for (var index = 0; index < this.blocks.length; index++) {
  102278. var block = this.blocks[index];
  102279. block.intersectsRay(ray, this._selectionContent);
  102280. }
  102281. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  102282. return this._selectionContent;
  102283. };
  102284. /**
  102285. * @hidden
  102286. */
  102287. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  102288. target.blocks = new Array();
  102289. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  102290. // Segmenting space
  102291. for (var x = 0; x < 2; x++) {
  102292. for (var y = 0; y < 2; y++) {
  102293. for (var z = 0; z < 2; z++) {
  102294. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  102295. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  102296. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  102297. block.addEntries(entries);
  102298. target.blocks.push(block);
  102299. }
  102300. }
  102301. }
  102302. };
  102303. /**
  102304. * Adds a mesh into the octree block if it intersects the block
  102305. */
  102306. Octree.CreationFuncForMeshes = function (entry, block) {
  102307. var boundingInfo = entry.getBoundingInfo();
  102308. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102309. block.entries.push(entry);
  102310. }
  102311. };
  102312. /**
  102313. * Adds a submesh into the octree block if it intersects the block
  102314. */
  102315. Octree.CreationFuncForSubMeshes = function (entry, block) {
  102316. var boundingInfo = entry.getBoundingInfo();
  102317. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  102318. block.entries.push(entry);
  102319. }
  102320. };
  102321. return Octree;
  102322. }());
  102323. BABYLON.Octree = Octree;
  102324. })(BABYLON || (BABYLON = {}));
  102325. //# sourceMappingURL=babylon.octree.js.map
  102326. var BABYLON;
  102327. (function (BABYLON) {
  102328. /**
  102329. * Class used to store a cell in an octree
  102330. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102331. */
  102332. var OctreeBlock = /** @class */ (function () {
  102333. /**
  102334. * Creates a new block
  102335. * @param minPoint defines the minimum vector (in world space) of the block's bounding box
  102336. * @param maxPoint defines the maximum vector (in world space) of the block's bounding box
  102337. * @param capacity defines the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102338. * @param depth defines the current depth of this block in the octree
  102339. * @param maxDepth defines the maximal depth allowed (beyond this value, the capacity is ignored)
  102340. * @param creationFunc defines a callback to call when an element is added to the block
  102341. */
  102342. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  102343. /**
  102344. * Gets the content of the current block
  102345. */
  102346. this.entries = new Array();
  102347. this._boundingVectors = new Array();
  102348. this._capacity = capacity;
  102349. this._depth = depth;
  102350. this._maxDepth = maxDepth;
  102351. this._creationFunc = creationFunc;
  102352. this._minPoint = minPoint;
  102353. this._maxPoint = maxPoint;
  102354. this._boundingVectors.push(minPoint.clone());
  102355. this._boundingVectors.push(maxPoint.clone());
  102356. this._boundingVectors.push(minPoint.clone());
  102357. this._boundingVectors[2].x = maxPoint.x;
  102358. this._boundingVectors.push(minPoint.clone());
  102359. this._boundingVectors[3].y = maxPoint.y;
  102360. this._boundingVectors.push(minPoint.clone());
  102361. this._boundingVectors[4].z = maxPoint.z;
  102362. this._boundingVectors.push(maxPoint.clone());
  102363. this._boundingVectors[5].z = minPoint.z;
  102364. this._boundingVectors.push(maxPoint.clone());
  102365. this._boundingVectors[6].x = minPoint.x;
  102366. this._boundingVectors.push(maxPoint.clone());
  102367. this._boundingVectors[7].y = minPoint.y;
  102368. }
  102369. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  102370. // Property
  102371. /**
  102372. * Gets the maximum capacity of this block (if capacity is reached the block will be split into sub blocks)
  102373. */
  102374. get: function () {
  102375. return this._capacity;
  102376. },
  102377. enumerable: true,
  102378. configurable: true
  102379. });
  102380. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  102381. /**
  102382. * Gets the minimum vector (in world space) of the block's bounding box
  102383. */
  102384. get: function () {
  102385. return this._minPoint;
  102386. },
  102387. enumerable: true,
  102388. configurable: true
  102389. });
  102390. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  102391. /**
  102392. * Gets the maximum vector (in world space) of the block's bounding box
  102393. */
  102394. get: function () {
  102395. return this._maxPoint;
  102396. },
  102397. enumerable: true,
  102398. configurable: true
  102399. });
  102400. // Methods
  102401. /**
  102402. * Add a new element to this block
  102403. * @param entry defines the element to add
  102404. */
  102405. OctreeBlock.prototype.addEntry = function (entry) {
  102406. if (this.blocks) {
  102407. for (var index = 0; index < this.blocks.length; index++) {
  102408. var block = this.blocks[index];
  102409. block.addEntry(entry);
  102410. }
  102411. return;
  102412. }
  102413. this._creationFunc(entry, this);
  102414. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  102415. this.createInnerBlocks();
  102416. }
  102417. };
  102418. /**
  102419. * Add an array of elements to this block
  102420. * @param entries defines the array of elements to add
  102421. */
  102422. OctreeBlock.prototype.addEntries = function (entries) {
  102423. for (var index = 0; index < entries.length; index++) {
  102424. var mesh = entries[index];
  102425. this.addEntry(mesh);
  102426. }
  102427. };
  102428. /**
  102429. * Test if the current block intersects the furstum planes and if yes, then add its content to the selection array
  102430. * @param frustumPlanes defines the frustum planes to test
  102431. * @param selection defines the array to store current content if selection is positive
  102432. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102433. */
  102434. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  102435. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  102436. if (this.blocks) {
  102437. for (var index = 0; index < this.blocks.length; index++) {
  102438. var block = this.blocks[index];
  102439. block.select(frustumPlanes, selection, allowDuplicate);
  102440. }
  102441. return;
  102442. }
  102443. if (allowDuplicate) {
  102444. selection.concat(this.entries);
  102445. }
  102446. else {
  102447. selection.concatWithNoDuplicate(this.entries);
  102448. }
  102449. }
  102450. };
  102451. /**
  102452. * Test if the current block intersect with the given bounding sphere and if yes, then add its content to the selection array
  102453. * @param sphereCenter defines the bounding sphere center
  102454. * @param sphereRadius defines the bounding sphere radius
  102455. * @param selection defines the array to store current content if selection is positive
  102456. * @param allowDuplicate defines if the selection array can contains duplicated entries
  102457. */
  102458. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  102459. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  102460. if (this.blocks) {
  102461. for (var index = 0; index < this.blocks.length; index++) {
  102462. var block = this.blocks[index];
  102463. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  102464. }
  102465. return;
  102466. }
  102467. if (allowDuplicate) {
  102468. selection.concat(this.entries);
  102469. }
  102470. else {
  102471. selection.concatWithNoDuplicate(this.entries);
  102472. }
  102473. }
  102474. };
  102475. /**
  102476. * Test if the current block intersect with the given ray and if yes, then add its content to the selection array
  102477. * @param ray defines the ray to test with
  102478. * @param selection defines the array to store current content if selection is positive
  102479. */
  102480. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  102481. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  102482. if (this.blocks) {
  102483. for (var index = 0; index < this.blocks.length; index++) {
  102484. var block = this.blocks[index];
  102485. block.intersectsRay(ray, selection);
  102486. }
  102487. return;
  102488. }
  102489. selection.concatWithNoDuplicate(this.entries);
  102490. }
  102491. };
  102492. /**
  102493. * Subdivide the content into child blocks (this block will then be empty)
  102494. */
  102495. OctreeBlock.prototype.createInnerBlocks = function () {
  102496. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  102497. };
  102498. return OctreeBlock;
  102499. }());
  102500. BABYLON.OctreeBlock = OctreeBlock;
  102501. })(BABYLON || (BABYLON = {}));
  102502. //# sourceMappingURL=babylon.octreeBlock.js.map
  102503. var BABYLON;
  102504. (function (BABYLON) {
  102505. BABYLON.Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  102506. if (maxCapacity === void 0) { maxCapacity = 64; }
  102507. if (maxDepth === void 0) { maxDepth = 2; }
  102508. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102509. if (!component) {
  102510. component = new OctreeSceneComponent(this);
  102511. this._addComponent(component);
  102512. }
  102513. if (!this._selectionOctree) {
  102514. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  102515. }
  102516. var worldExtends = this.getWorldExtends();
  102517. // Update octree
  102518. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  102519. return this._selectionOctree;
  102520. };
  102521. Object.defineProperty(BABYLON.Scene.prototype, "selectionOctree", {
  102522. get: function () {
  102523. return this._selectionOctree;
  102524. },
  102525. enumerable: true,
  102526. configurable: true
  102527. });
  102528. /**
  102529. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  102530. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  102531. * @param maxCapacity defines the maximum size of each block (64 by default)
  102532. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  102533. * @returns the new octree
  102534. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  102535. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  102536. */
  102537. BABYLON.AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  102538. if (maxCapacity === void 0) { maxCapacity = 64; }
  102539. if (maxDepth === void 0) { maxDepth = 2; }
  102540. var scene = this.getScene();
  102541. var component = scene._getComponent(BABYLON.SceneComponentConstants.NAME_OCTREE);
  102542. if (!component) {
  102543. component = new OctreeSceneComponent(scene);
  102544. scene._addComponent(component);
  102545. }
  102546. if (!this._submeshesOctree) {
  102547. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  102548. }
  102549. this.computeWorldMatrix(true);
  102550. var boundingInfo = this.getBoundingInfo();
  102551. // Update octree
  102552. var bbox = boundingInfo.boundingBox;
  102553. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  102554. return this._submeshesOctree;
  102555. };
  102556. /**
  102557. * Defines the octree scene component responsible to manage any octrees
  102558. * in a given scene.
  102559. */
  102560. var OctreeSceneComponent = /** @class */ (function () {
  102561. /**
  102562. * Creates a new instance of the component for the given scene
  102563. * @param scene Defines the scene to register the component in
  102564. */
  102565. function OctreeSceneComponent(scene) {
  102566. /**
  102567. * The component name helpfull to identify the component in the list of scene components.
  102568. */
  102569. this.name = BABYLON.SceneComponentConstants.NAME_OCTREE;
  102570. /**
  102571. * Indicates if the meshes have been checked to make sure they are isEnabled()
  102572. */
  102573. this.checksIsEnabled = true;
  102574. this._tempRay = new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(1, 1, 1));
  102575. this.scene = scene;
  102576. this.scene.getActiveMeshCandidates = this.getActiveMeshCandidates.bind(this);
  102577. this.scene.getActiveSubMeshCandidates = this.getActiveSubMeshCandidates.bind(this);
  102578. this.scene.getCollidingSubMeshCandidates = this.getCollidingSubMeshCandidates.bind(this);
  102579. this.scene.getIntersectingSubMeshCandidates = this.getIntersectingSubMeshCandidates.bind(this);
  102580. }
  102581. /**
  102582. * Registers the component in a given scene
  102583. */
  102584. OctreeSceneComponent.prototype.register = function () {
  102585. var _this = this;
  102586. this.scene.onMeshRemovedObservable.add(function (mesh) {
  102587. var sceneOctree = _this.scene.selectionOctree;
  102588. if (sceneOctree !== undefined && sceneOctree !== null) {
  102589. var index = sceneOctree.dynamicContent.indexOf(mesh);
  102590. if (index !== -1) {
  102591. sceneOctree.dynamicContent.splice(index, 1);
  102592. }
  102593. }
  102594. });
  102595. this.scene.onMeshImportedObservable.add(function (mesh) {
  102596. var sceneOctree = _this.scene.selectionOctree;
  102597. if (sceneOctree !== undefined && sceneOctree !== null) {
  102598. sceneOctree.addMesh(mesh);
  102599. }
  102600. });
  102601. };
  102602. /**
  102603. * Return the list of active meshes
  102604. * @returns the list of active meshes
  102605. */
  102606. OctreeSceneComponent.prototype.getActiveMeshCandidates = function () {
  102607. if (this.scene._selectionOctree) {
  102608. var selection = this.scene._selectionOctree.select(this.scene.frustumPlanes);
  102609. return selection;
  102610. }
  102611. return this.scene._getDefaultMeshCandidates();
  102612. };
  102613. /**
  102614. * Return the list of active sub meshes
  102615. * @param mesh The mesh to get the candidates sub meshes from
  102616. * @returns the list of active sub meshes
  102617. */
  102618. OctreeSceneComponent.prototype.getActiveSubMeshCandidates = function (mesh) {
  102619. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  102620. var intersections = mesh._submeshesOctree.select(this.scene.frustumPlanes);
  102621. return intersections;
  102622. }
  102623. return this.scene._getDefaultSubMeshCandidates(mesh);
  102624. };
  102625. /**
  102626. * Return the list of sub meshes intersecting with a given local ray
  102627. * @param mesh defines the mesh to find the submesh for
  102628. * @param localRay defines the ray in local space
  102629. * @returns the list of intersecting sub meshes
  102630. */
  102631. OctreeSceneComponent.prototype.getIntersectingSubMeshCandidates = function (mesh, localRay) {
  102632. if (mesh._submeshesOctree && mesh.useOctreeForPicking) {
  102633. BABYLON.Ray.TransformToRef(localRay, mesh.getWorldMatrix(), this._tempRay);
  102634. var intersections = mesh._submeshesOctree.intersectsRay(this._tempRay);
  102635. return intersections;
  102636. }
  102637. return this.scene._getDefaultSubMeshCandidates(mesh);
  102638. };
  102639. /**
  102640. * Return the list of sub meshes colliding with a collider
  102641. * @param mesh defines the mesh to find the submesh for
  102642. * @param collider defines the collider to evaluate the collision against
  102643. * @returns the list of colliding sub meshes
  102644. */
  102645. OctreeSceneComponent.prototype.getCollidingSubMeshCandidates = function (mesh, collider) {
  102646. if (mesh._submeshesOctree && mesh.useOctreeForCollisions) {
  102647. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  102648. var intersections = mesh._submeshesOctree.intersects(collider._basePointWorld, radius);
  102649. return intersections;
  102650. }
  102651. return this.scene._getDefaultSubMeshCandidates(mesh);
  102652. };
  102653. /**
  102654. * Rebuilds the elements related to this component in case of
  102655. * context lost for instance.
  102656. */
  102657. OctreeSceneComponent.prototype.rebuild = function () {
  102658. // Nothing to do here.
  102659. };
  102660. /**
  102661. * Disposes the component and the associated ressources.
  102662. */
  102663. OctreeSceneComponent.prototype.dispose = function () {
  102664. // Nothing to do here.
  102665. };
  102666. return OctreeSceneComponent;
  102667. }());
  102668. BABYLON.OctreeSceneComponent = OctreeSceneComponent;
  102669. })(BABYLON || (BABYLON = {}));
  102670. //# sourceMappingURL=babylon.octreeSceneComponent.js.map
  102671. var BABYLON;
  102672. (function (BABYLON) {
  102673. /**
  102674. * Postprocess used to generate anaglyphic rendering
  102675. */
  102676. var AnaglyphPostProcess = /** @class */ (function (_super) {
  102677. __extends(AnaglyphPostProcess, _super);
  102678. /**
  102679. * Creates a new AnaglyphPostProcess
  102680. * @param name defines postprocess name
  102681. * @param options defines creation options or target ratio scale
  102682. * @param rigCameras defines cameras using this postprocess
  102683. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  102684. * @param engine defines hosting engine
  102685. * @param reusable defines if the postprocess will be reused multiple times per frame
  102686. */
  102687. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  102688. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  102689. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102690. _this.onApplyObservable.add(function (effect) {
  102691. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  102692. });
  102693. return _this;
  102694. }
  102695. return AnaglyphPostProcess;
  102696. }(BABYLON.PostProcess));
  102697. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  102698. })(BABYLON || (BABYLON = {}));
  102699. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  102700. var BABYLON;
  102701. (function (BABYLON) {
  102702. BABYLON.Node.AddNodeConstructor("AnaglyphArcRotateCamera", function (name, scene, options) {
  102703. return function () { return new AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102704. });
  102705. /**
  102706. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  102707. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102708. */
  102709. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  102710. __extends(AnaglyphArcRotateCamera, _super);
  102711. /**
  102712. * Creates a new AnaglyphArcRotateCamera
  102713. * @param name defines camera name
  102714. * @param alpha defines alpha angle (in radians)
  102715. * @param beta defines beta angle (in radians)
  102716. * @param radius defines radius
  102717. * @param target defines camera target
  102718. * @param interaxialDistance defines distance between each color axis
  102719. * @param scene defines the hosting scene
  102720. */
  102721. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  102722. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102723. _this.interaxialDistance = interaxialDistance;
  102724. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102725. return _this;
  102726. }
  102727. /**
  102728. * Gets camera class name
  102729. * @returns AnaglyphArcRotateCamera
  102730. */
  102731. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  102732. return "AnaglyphArcRotateCamera";
  102733. };
  102734. return AnaglyphArcRotateCamera;
  102735. }(BABYLON.ArcRotateCamera));
  102736. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  102737. })(BABYLON || (BABYLON = {}));
  102738. //# sourceMappingURL=babylon.anaglyphArcRotateCamera.js.map
  102739. var BABYLON;
  102740. (function (BABYLON) {
  102741. BABYLON.Node.AddNodeConstructor("AnaglyphFreeCamera", function (name, scene, options) {
  102742. return function () { return new AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102743. });
  102744. /**
  102745. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  102746. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102747. */
  102748. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  102749. __extends(AnaglyphFreeCamera, _super);
  102750. /**
  102751. * Creates a new AnaglyphFreeCamera
  102752. * @param name defines camera name
  102753. * @param position defines initial position
  102754. * @param interaxialDistance defines distance between each color axis
  102755. * @param scene defines the hosting scene
  102756. */
  102757. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  102758. var _this = _super.call(this, name, position, scene) || this;
  102759. _this.interaxialDistance = interaxialDistance;
  102760. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102761. return _this;
  102762. }
  102763. /**
  102764. * Gets camera class name
  102765. * @returns AnaglyphFreeCamera
  102766. */
  102767. AnaglyphFreeCamera.prototype.getClassName = function () {
  102768. return "AnaglyphFreeCamera";
  102769. };
  102770. return AnaglyphFreeCamera;
  102771. }(BABYLON.FreeCamera));
  102772. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  102773. })(BABYLON || (BABYLON = {}));
  102774. //# sourceMappingURL=babylon.anaglyphFreeCamera.js.map
  102775. var BABYLON;
  102776. (function (BABYLON) {
  102777. BABYLON.Node.AddNodeConstructor("AnaglyphGamepadCamera", function (name, scene, options) {
  102778. return function () { return new AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102779. });
  102780. /**
  102781. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  102782. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102783. */
  102784. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  102785. __extends(AnaglyphGamepadCamera, _super);
  102786. /**
  102787. * Creates a new AnaglyphGamepadCamera
  102788. * @param name defines camera name
  102789. * @param position defines initial position
  102790. * @param interaxialDistance defines distance between each color axis
  102791. * @param scene defines the hosting scene
  102792. */
  102793. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  102794. var _this = _super.call(this, name, position, scene) || this;
  102795. _this.interaxialDistance = interaxialDistance;
  102796. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102797. return _this;
  102798. }
  102799. /**
  102800. * Gets camera class name
  102801. * @returns AnaglyphGamepadCamera
  102802. */
  102803. AnaglyphGamepadCamera.prototype.getClassName = function () {
  102804. return "AnaglyphGamepadCamera";
  102805. };
  102806. return AnaglyphGamepadCamera;
  102807. }(BABYLON.GamepadCamera));
  102808. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  102809. })(BABYLON || (BABYLON = {}));
  102810. //# sourceMappingURL=babylon.anaglyphGamepadCamera.js.map
  102811. var BABYLON;
  102812. (function (BABYLON) {
  102813. BABYLON.Node.AddNodeConstructor("AnaglyphUniversalCamera", function (name, scene, options) {
  102814. return function () { return new AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, scene); };
  102815. });
  102816. /**
  102817. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  102818. * @see http://doc.babylonjs.com/features/cameras#anaglyph-cameras
  102819. */
  102820. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  102821. __extends(AnaglyphUniversalCamera, _super);
  102822. /**
  102823. * Creates a new AnaglyphUniversalCamera
  102824. * @param name defines camera name
  102825. * @param position defines initial position
  102826. * @param interaxialDistance defines distance between each color axis
  102827. * @param scene defines the hosting scene
  102828. */
  102829. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  102830. var _this = _super.call(this, name, position, scene) || this;
  102831. _this.interaxialDistance = interaxialDistance;
  102832. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  102833. return _this;
  102834. }
  102835. /**
  102836. * Gets camera class name
  102837. * @returns AnaglyphUniversalCamera
  102838. */
  102839. AnaglyphUniversalCamera.prototype.getClassName = function () {
  102840. return "AnaglyphUniversalCamera";
  102841. };
  102842. return AnaglyphUniversalCamera;
  102843. }(BABYLON.UniversalCamera));
  102844. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  102845. })(BABYLON || (BABYLON = {}));
  102846. //# sourceMappingURL=babylon.anaglyphUniversalCamera.js.map
  102847. var BABYLON;
  102848. (function (BABYLON) {
  102849. /**
  102850. * StereoscopicInterlacePostProcess used to render stereo views from a rigged camera
  102851. */
  102852. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  102853. __extends(StereoscopicInterlacePostProcess, _super);
  102854. /**
  102855. * Initializes a StereoscopicInterlacePostProcess
  102856. * @param name The name of the effect.
  102857. * @param rigCameras The rig cameras to be appled to the post process
  102858. * @param isStereoscopicHoriz If the rendered results are horizontal or verticle
  102859. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  102860. * @param engine The engine which the post process will be applied. (default: current engine)
  102861. * @param reusable If the post process can be reused on the same frame. (default: false)
  102862. */
  102863. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  102864. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  102865. _this._passedProcess = rigCameras[0]._rigPostProcess;
  102866. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  102867. _this.onSizeChangedObservable.add(function () {
  102868. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  102869. });
  102870. _this.onApplyObservable.add(function (effect) {
  102871. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  102872. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  102873. });
  102874. return _this;
  102875. }
  102876. return StereoscopicInterlacePostProcess;
  102877. }(BABYLON.PostProcess));
  102878. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  102879. })(BABYLON || (BABYLON = {}));
  102880. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  102881. var BABYLON;
  102882. (function (BABYLON) {
  102883. BABYLON.Node.AddNodeConstructor("StereoscopicArcRotateCamera", function (name, scene, options) {
  102884. return function () { return new StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102885. });
  102886. /**
  102887. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  102888. * @see http://doc.babylonjs.com/features/cameras
  102889. */
  102890. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  102891. __extends(StereoscopicArcRotateCamera, _super);
  102892. /**
  102893. * Creates a new StereoscopicArcRotateCamera
  102894. * @param name defines camera name
  102895. * @param alpha defines alpha angle (in radians)
  102896. * @param beta defines beta angle (in radians)
  102897. * @param radius defines radius
  102898. * @param target defines camera target
  102899. * @param interaxialDistance defines distance between each color axis
  102900. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102901. * @param scene defines the hosting scene
  102902. */
  102903. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  102904. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  102905. _this.interaxialDistance = interaxialDistance;
  102906. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102907. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102908. return _this;
  102909. }
  102910. /**
  102911. * Gets camera class name
  102912. * @returns StereoscopicArcRotateCamera
  102913. */
  102914. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  102915. return "StereoscopicArcRotateCamera";
  102916. };
  102917. return StereoscopicArcRotateCamera;
  102918. }(BABYLON.ArcRotateCamera));
  102919. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  102920. })(BABYLON || (BABYLON = {}));
  102921. //# sourceMappingURL=babylon.stereoscopicArcRotateCamera.js.map
  102922. var BABYLON;
  102923. (function (BABYLON) {
  102924. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  102925. return function () { return new StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102926. });
  102927. /**
  102928. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  102929. * @see http://doc.babylonjs.com/features/cameras
  102930. */
  102931. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  102932. __extends(StereoscopicFreeCamera, _super);
  102933. /**
  102934. * Creates a new StereoscopicFreeCamera
  102935. * @param name defines camera name
  102936. * @param position defines initial position
  102937. * @param interaxialDistance defines distance between each color axis
  102938. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102939. * @param scene defines the hosting scene
  102940. */
  102941. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102942. var _this = _super.call(this, name, position, scene) || this;
  102943. _this.interaxialDistance = interaxialDistance;
  102944. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102945. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102946. return _this;
  102947. }
  102948. /**
  102949. * Gets camera class name
  102950. * @returns StereoscopicFreeCamera
  102951. */
  102952. StereoscopicFreeCamera.prototype.getClassName = function () {
  102953. return "StereoscopicFreeCamera";
  102954. };
  102955. return StereoscopicFreeCamera;
  102956. }(BABYLON.FreeCamera));
  102957. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  102958. })(BABYLON || (BABYLON = {}));
  102959. //# sourceMappingURL=babylon.stereoscopicFreeCamera.js.map
  102960. var BABYLON;
  102961. (function (BABYLON) {
  102962. BABYLON.Node.AddNodeConstructor("StereoscopicGamepadCamera", function (name, scene, options) {
  102963. return function () { return new StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  102964. });
  102965. /**
  102966. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  102967. * @see http://doc.babylonjs.com/features/cameras
  102968. */
  102969. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  102970. __extends(StereoscopicGamepadCamera, _super);
  102971. /**
  102972. * Creates a new StereoscopicGamepadCamera
  102973. * @param name defines camera name
  102974. * @param position defines initial position
  102975. * @param interaxialDistance defines distance between each color axis
  102976. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  102977. * @param scene defines the hosting scene
  102978. */
  102979. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  102980. var _this = _super.call(this, name, position, scene) || this;
  102981. _this.interaxialDistance = interaxialDistance;
  102982. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  102983. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  102984. return _this;
  102985. }
  102986. /**
  102987. * Gets camera class name
  102988. * @returns StereoscopicGamepadCamera
  102989. */
  102990. StereoscopicGamepadCamera.prototype.getClassName = function () {
  102991. return "StereoscopicGamepadCamera";
  102992. };
  102993. return StereoscopicGamepadCamera;
  102994. }(BABYLON.GamepadCamera));
  102995. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  102996. })(BABYLON || (BABYLON = {}));
  102997. //# sourceMappingURL=babylon.stereoscopicGamepadCamera.js.map
  102998. var BABYLON;
  102999. (function (BABYLON) {
  103000. BABYLON.Node.AddNodeConstructor("StereoscopicFreeCamera", function (name, scene, options) {
  103001. return function () { return new StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), options.interaxial_distance, options.isStereoscopicSideBySide, scene); };
  103002. });
  103003. /**
  103004. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  103005. * @see http://doc.babylonjs.com/features/cameras
  103006. */
  103007. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  103008. __extends(StereoscopicUniversalCamera, _super);
  103009. /**
  103010. * Creates a new StereoscopicUniversalCamera
  103011. * @param name defines camera name
  103012. * @param position defines initial position
  103013. * @param interaxialDistance defines distance between each color axis
  103014. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  103015. * @param scene defines the hosting scene
  103016. */
  103017. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  103018. var _this = _super.call(this, name, position, scene) || this;
  103019. _this.interaxialDistance = interaxialDistance;
  103020. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  103021. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  103022. return _this;
  103023. }
  103024. /**
  103025. * Gets camera class name
  103026. * @returns StereoscopicUniversalCamera
  103027. */
  103028. StereoscopicUniversalCamera.prototype.getClassName = function () {
  103029. return "StereoscopicUniversalCamera";
  103030. };
  103031. return StereoscopicUniversalCamera;
  103032. }(BABYLON.UniversalCamera));
  103033. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  103034. })(BABYLON || (BABYLON = {}));
  103035. //# sourceMappingURL=babylon.stereoscopicUniversalCamera.js.map
  103036. var BABYLON;
  103037. (function (BABYLON) {
  103038. /**
  103039. * VRDistortionCorrectionPostProcess used for mobile VR
  103040. */
  103041. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  103042. __extends(VRDistortionCorrectionPostProcess, _super);
  103043. /**
  103044. * Initializes the VRDistortionCorrectionPostProcess
  103045. * @param name The name of the effect.
  103046. * @param camera The camera to apply the render pass to.
  103047. * @param isRightEye If this is for the right eye distortion
  103048. * @param vrMetrics All the required metrics for the VR camera
  103049. */
  103050. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  103051. var _this = _super.call(this, name, "vrDistortionCorrection", [
  103052. 'LensCenter',
  103053. 'Scale',
  103054. 'ScaleIn',
  103055. 'HmdWarpParam'
  103056. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  103057. _this._isRightEye = isRightEye;
  103058. _this._distortionFactors = vrMetrics.distortionK;
  103059. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  103060. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  103061. _this.adaptScaleToCurrentViewport = true;
  103062. _this.onSizeChangedObservable.add(function () {
  103063. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  103064. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  103065. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  103066. });
  103067. _this.onApplyObservable.add(function (effect) {
  103068. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  103069. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  103070. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  103071. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  103072. });
  103073. return _this;
  103074. }
  103075. return VRDistortionCorrectionPostProcess;
  103076. }(BABYLON.PostProcess));
  103077. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  103078. })(BABYLON || (BABYLON = {}));
  103079. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  103080. var BABYLON;
  103081. (function (BABYLON) {
  103082. /**
  103083. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  103084. * Screen rotation is taken into account.
  103085. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103086. */
  103087. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  103088. /**
  103089. * Instantiates a new input
  103090. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103091. */
  103092. function FreeCameraDeviceOrientationInput() {
  103093. var _this = this;
  103094. this._screenOrientationAngle = 0;
  103095. this._screenQuaternion = new BABYLON.Quaternion();
  103096. this._alpha = 0;
  103097. this._beta = 0;
  103098. this._gamma = 0;
  103099. this._orientationChanged = function () {
  103100. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  103101. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  103102. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  103103. };
  103104. this._deviceOrientation = function (evt) {
  103105. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  103106. _this._beta = evt.beta !== null ? evt.beta : 0;
  103107. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  103108. };
  103109. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  103110. this._orientationChanged();
  103111. }
  103112. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  103113. /**
  103114. * Define the camera controlled by the input.
  103115. */
  103116. get: function () {
  103117. return this._camera;
  103118. },
  103119. set: function (camera) {
  103120. this._camera = camera;
  103121. if (this._camera != null && !this._camera.rotationQuaternion) {
  103122. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  103123. }
  103124. },
  103125. enumerable: true,
  103126. configurable: true
  103127. });
  103128. /**
  103129. * Attach the input controls to a specific dom element to get the input from.
  103130. * @param element Defines the element the controls should be listened from
  103131. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103132. */
  103133. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103134. window.addEventListener("orientationchange", this._orientationChanged);
  103135. window.addEventListener("deviceorientation", this._deviceOrientation);
  103136. //In certain cases, the attach control is called AFTER orientation was changed,
  103137. //So this is needed.
  103138. this._orientationChanged();
  103139. };
  103140. /**
  103141. * Detach the current controls from the specified dom element.
  103142. * @param element Defines the element to stop listening the inputs from
  103143. */
  103144. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  103145. window.removeEventListener("orientationchange", this._orientationChanged);
  103146. window.removeEventListener("deviceorientation", this._deviceOrientation);
  103147. };
  103148. /**
  103149. * Update the current camera state depending on the inputs that have been used this frame.
  103150. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103151. */
  103152. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  103153. //if no device orientation provided, don't update the rotation.
  103154. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  103155. if (!this._alpha)
  103156. return;
  103157. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  103158. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  103159. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  103160. //Mirror on XY Plane
  103161. this._camera.rotationQuaternion.z *= -1;
  103162. this._camera.rotationQuaternion.w *= -1;
  103163. };
  103164. /**
  103165. * Gets the class name of the current intput.
  103166. * @returns the class name
  103167. */
  103168. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  103169. return "FreeCameraDeviceOrientationInput";
  103170. };
  103171. /**
  103172. * Get the friendly name associated with the input class.
  103173. * @returns the input friendly name
  103174. */
  103175. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  103176. return "deviceOrientation";
  103177. };
  103178. return FreeCameraDeviceOrientationInput;
  103179. }());
  103180. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  103181. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  103182. })(BABYLON || (BABYLON = {}));
  103183. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  103184. var BABYLON;
  103185. (function (BABYLON) {
  103186. /**
  103187. * Manage the device orientation inputs (gyroscope) to control an arc rotate camera.
  103188. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  103189. */
  103190. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  103191. /**
  103192. * Instantiate a new ArcRotateCameraVRDeviceOrientationInput.
  103193. */
  103194. function ArcRotateCameraVRDeviceOrientationInput() {
  103195. /**
  103196. * Defines a correction factor applied on the alpha value retrieved from the orientation events.
  103197. */
  103198. this.alphaCorrection = 1;
  103199. /**
  103200. * Defines a correction factor applied on the beta value retrieved from the orientation events.
  103201. */
  103202. this.betaCorrection = 1;
  103203. /**
  103204. * Defines a correction factor applied on the gamma value retrieved from the orientation events.
  103205. */
  103206. this.gammaCorrection = 1;
  103207. this._alpha = 0;
  103208. this._gamma = 0;
  103209. this._dirty = false;
  103210. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  103211. }
  103212. /**
  103213. * Attach the input controls to a specific dom element to get the input from.
  103214. * @param element Defines the element the controls should be listened from
  103215. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  103216. */
  103217. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  103218. this.camera.attachControl(element, noPreventDefault);
  103219. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  103220. };
  103221. /** @hidden */
  103222. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  103223. if (evt.alpha !== null) {
  103224. this._alpha = +evt.alpha | 0;
  103225. }
  103226. if (evt.gamma !== null) {
  103227. this._gamma = +evt.gamma | 0;
  103228. }
  103229. this._dirty = true;
  103230. };
  103231. /**
  103232. * Update the current camera state depending on the inputs that have been used this frame.
  103233. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  103234. */
  103235. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  103236. if (this._dirty) {
  103237. this._dirty = false;
  103238. if (this._gamma < 0) {
  103239. this._gamma = 180 + this._gamma;
  103240. }
  103241. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  103242. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  103243. }
  103244. };
  103245. /**
  103246. * Detach the current controls from the specified dom element.
  103247. * @param element Defines the element to stop listening the inputs from
  103248. */
  103249. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  103250. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  103251. };
  103252. /**
  103253. * Gets the class name of the current intput.
  103254. * @returns the class name
  103255. */
  103256. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  103257. return "ArcRotateCameraVRDeviceOrientationInput";
  103258. };
  103259. /**
  103260. * Get the friendly name associated with the input class.
  103261. * @returns the input friendly name
  103262. */
  103263. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  103264. return "VRDeviceOrientation";
  103265. };
  103266. return ArcRotateCameraVRDeviceOrientationInput;
  103267. }());
  103268. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  103269. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  103270. })(BABYLON || (BABYLON = {}));
  103271. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  103272. var BABYLON;
  103273. (function (BABYLON) {
  103274. /**
  103275. * This represents all the required metrics to create a VR camera.
  103276. * @see http://doc.babylonjs.com/babylon101/cameras#device-orientation-camera
  103277. */
  103278. var VRCameraMetrics = /** @class */ (function () {
  103279. function VRCameraMetrics() {
  103280. /**
  103281. * Define if the current vr camera should compensate the distortion of the lense or not.
  103282. */
  103283. this.compensateDistortion = true;
  103284. }
  103285. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  103286. /**
  103287. * Gets the rendering aspect ratio based on the provided resolutions.
  103288. */
  103289. get: function () {
  103290. return this.hResolution / (2 * this.vResolution);
  103291. },
  103292. enumerable: true,
  103293. configurable: true
  103294. });
  103295. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  103296. /**
  103297. * Gets the aspect ratio based on the FOV, scale factors, and real screen sizes.
  103298. */
  103299. get: function () {
  103300. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  103301. },
  103302. enumerable: true,
  103303. configurable: true
  103304. });
  103305. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  103306. /**
  103307. * @hidden
  103308. */
  103309. get: function () {
  103310. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103311. var h = (4 * meters) / this.hScreenSize;
  103312. return BABYLON.Matrix.Translation(h, 0, 0);
  103313. },
  103314. enumerable: true,
  103315. configurable: true
  103316. });
  103317. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  103318. /**
  103319. * @hidden
  103320. */
  103321. get: function () {
  103322. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  103323. var h = (4 * meters) / this.hScreenSize;
  103324. return BABYLON.Matrix.Translation(-h, 0, 0);
  103325. },
  103326. enumerable: true,
  103327. configurable: true
  103328. });
  103329. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  103330. /**
  103331. * @hidden
  103332. */
  103333. get: function () {
  103334. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  103335. },
  103336. enumerable: true,
  103337. configurable: true
  103338. });
  103339. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  103340. /**
  103341. * @hidden
  103342. */
  103343. get: function () {
  103344. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  103345. },
  103346. enumerable: true,
  103347. configurable: true
  103348. });
  103349. /**
  103350. * Get the default VRMetrics based on the most generic setup.
  103351. * @returns the default vr metrics
  103352. */
  103353. VRCameraMetrics.GetDefault = function () {
  103354. var result = new VRCameraMetrics();
  103355. result.hResolution = 1280;
  103356. result.vResolution = 800;
  103357. result.hScreenSize = 0.149759993;
  103358. result.vScreenSize = 0.0935999975;
  103359. result.vScreenCenter = 0.0467999987;
  103360. result.eyeToScreenDistance = 0.0410000011;
  103361. result.lensSeparationDistance = 0.0635000020;
  103362. result.interpupillaryDistance = 0.0640000030;
  103363. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  103364. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  103365. result.postProcessScaleFactor = 1.714605507808412;
  103366. result.lensCenterOffset = 0.151976421;
  103367. return result;
  103368. };
  103369. return VRCameraMetrics;
  103370. }());
  103371. BABYLON.VRCameraMetrics = VRCameraMetrics;
  103372. })(BABYLON || (BABYLON = {}));
  103373. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  103374. var BABYLON;
  103375. (function (BABYLON) {
  103376. BABYLON.Node.AddNodeConstructor("WebVRFreeCamera", function (name, scene) {
  103377. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103378. });
  103379. BABYLON.Node.AddNodeConstructor("WebVRGamepadCamera", function (name, scene) {
  103380. return function () { return new WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  103381. });
  103382. /**
  103383. * This represents a WebVR camera.
  103384. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  103385. * @example http://doc.babylonjs.com/how_to/webvr_camera
  103386. */
  103387. var WebVRFreeCamera = /** @class */ (function (_super) {
  103388. __extends(WebVRFreeCamera, _super);
  103389. /**
  103390. * Instantiates a WebVRFreeCamera.
  103391. * @param name The name of the WebVRFreeCamera
  103392. * @param position The starting anchor position for the camera
  103393. * @param scene The scene the camera belongs to
  103394. * @param webVROptions a set of customizable options for the webVRCamera
  103395. */
  103396. function WebVRFreeCamera(name, position, scene, webVROptions) {
  103397. if (webVROptions === void 0) { webVROptions = {}; }
  103398. var _this = _super.call(this, name, position, scene) || this;
  103399. _this.webVROptions = webVROptions;
  103400. /**
  103401. * @hidden
  103402. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  103403. */
  103404. _this._vrDevice = null;
  103405. /**
  103406. * The rawPose of the vrDevice.
  103407. */
  103408. _this.rawPose = null;
  103409. _this._specsVersion = "1.1";
  103410. _this._attached = false;
  103411. _this._descendants = [];
  103412. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  103413. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  103414. /** @hidden */
  103415. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  103416. _this._standingMatrix = null;
  103417. /**
  103418. * Represents device position in babylon space.
  103419. */
  103420. _this.devicePosition = BABYLON.Vector3.Zero();
  103421. /**
  103422. * Represents device rotation in babylon space.
  103423. */
  103424. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  103425. /**
  103426. * The scale of the device to be used when translating from device space to babylon space.
  103427. */
  103428. _this.deviceScaleFactor = 1;
  103429. _this._deviceToWorld = BABYLON.Matrix.Identity();
  103430. _this._worldToDevice = BABYLON.Matrix.Identity();
  103431. /**
  103432. * References to the webVR controllers for the vrDevice.
  103433. */
  103434. _this.controllers = [];
  103435. /**
  103436. * Emits an event when a controller is attached.
  103437. */
  103438. _this.onControllersAttachedObservable = new BABYLON.Observable();
  103439. /**
  103440. * Emits an event when a controller's mesh has been loaded;
  103441. */
  103442. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  103443. /**
  103444. * Emits an event when the HMD's pose has been updated.
  103445. */
  103446. _this.onPoseUpdatedFromDeviceObservable = new BABYLON.Observable();
  103447. _this._poseSet = false;
  103448. /**
  103449. * If the rig cameras be used as parent instead of this camera.
  103450. */
  103451. _this.rigParenting = true;
  103452. _this._defaultHeight = undefined;
  103453. _this._htmlElementAttached = null;
  103454. _this._detachIfAttached = function () {
  103455. var vrDisplay = _this.getEngine().getVRDevice();
  103456. if (vrDisplay && !vrDisplay.isPresenting && _this._htmlElementAttached) {
  103457. _this.detachControl(_this._htmlElementAttached);
  103458. }
  103459. };
  103460. _this._workingVector = BABYLON.Vector3.Zero();
  103461. _this._oneVector = BABYLON.Vector3.One();
  103462. _this._workingMatrix = BABYLON.Matrix.Identity();
  103463. _this._tmpMatrix = new BABYLON.Matrix();
  103464. _this._cache.position = BABYLON.Vector3.Zero();
  103465. if (webVROptions.defaultHeight) {
  103466. _this._defaultHeight = webVROptions.defaultHeight;
  103467. _this.position.y = _this._defaultHeight;
  103468. }
  103469. _this.minZ = 0.1;
  103470. //legacy support - the compensation boolean was removed.
  103471. if (arguments.length === 5) {
  103472. _this.webVROptions = arguments[4];
  103473. }
  103474. // default webVR options
  103475. if (_this.webVROptions.trackPosition == undefined) {
  103476. _this.webVROptions.trackPosition = true;
  103477. }
  103478. if (_this.webVROptions.controllerMeshes == undefined) {
  103479. _this.webVROptions.controllerMeshes = true;
  103480. }
  103481. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  103482. _this.webVROptions.defaultLightingOnControllers = true;
  103483. }
  103484. _this.rotationQuaternion = new BABYLON.Quaternion();
  103485. if (_this.webVROptions && _this.webVROptions.positionScale) {
  103486. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  103487. }
  103488. //enable VR
  103489. var engine = _this.getEngine();
  103490. _this._onVREnabled = function (success) { if (success) {
  103491. _this.initControllers();
  103492. } };
  103493. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  103494. engine.initWebVR().add(function (event) {
  103495. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  103496. return;
  103497. }
  103498. _this._vrDevice = event.vrDisplay;
  103499. //reset the rig parameters.
  103500. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  103501. if (_this._attached) {
  103502. _this.getEngine().enableVR();
  103503. }
  103504. });
  103505. if (typeof (VRFrameData) !== "undefined")
  103506. _this._frameData = new VRFrameData();
  103507. /**
  103508. * The idea behind the following lines:
  103509. * objects that have the camera as parent should actually have the rig cameras as a parent.
  103510. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  103511. * the second will not show it correctly.
  103512. *
  103513. * To solve this - each object that has the camera as parent will be added to a protected array.
  103514. * When the rig camera renders, it will take this array and set all of those to be its children.
  103515. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  103516. * Amazing!
  103517. */
  103518. scene.onBeforeCameraRenderObservable.add(function (camera) {
  103519. if (camera.parent === _this && _this.rigParenting) {
  103520. _this._descendants = _this.getDescendants(true, function (n) {
  103521. // don't take the cameras or the controllers!
  103522. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  103523. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  103524. return !isController && !isRigCamera;
  103525. });
  103526. _this._descendants.forEach(function (node) {
  103527. node.parent = camera;
  103528. });
  103529. }
  103530. });
  103531. scene.onAfterCameraRenderObservable.add(function (camera) {
  103532. if (camera.parent === _this && _this.rigParenting) {
  103533. _this._descendants.forEach(function (node) {
  103534. node.parent = _this;
  103535. });
  103536. }
  103537. });
  103538. return _this;
  103539. }
  103540. /**
  103541. * Gets the device distance from the ground in meters.
  103542. * @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.
  103543. */
  103544. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  103545. if (this._standingMatrix) {
  103546. // Add standing matrix offset to get real offset from ground in room
  103547. this._standingMatrix.getTranslationToRef(this._workingVector);
  103548. return this._deviceRoomPosition.y + this._workingVector.y;
  103549. }
  103550. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  103551. return this._defaultHeight || 0;
  103552. };
  103553. /**
  103554. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103555. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  103556. */
  103557. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  103558. var _this = this;
  103559. if (callback === void 0) { callback = function (bool) { }; }
  103560. // Use standing matrix if available
  103561. this.getEngine().initWebVRAsync().then(function (result) {
  103562. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform || !_this.webVROptions.trackPosition) {
  103563. callback(false);
  103564. }
  103565. else {
  103566. _this._standingMatrix = new BABYLON.Matrix();
  103567. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  103568. if (!_this.getScene().useRightHandedSystem) {
  103569. [2, 6, 8, 9, 14].forEach(function (num) {
  103570. if (_this._standingMatrix) {
  103571. _this._standingMatrix.m[num] *= -1;
  103572. }
  103573. });
  103574. }
  103575. callback(true);
  103576. }
  103577. });
  103578. };
  103579. /**
  103580. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  103581. * @returns A promise with a boolean set to if the standing matrix is supported.
  103582. */
  103583. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  103584. var _this = this;
  103585. return new Promise(function (res, rej) {
  103586. _this.useStandingMatrix(function (supported) {
  103587. res(supported);
  103588. });
  103589. });
  103590. };
  103591. /**
  103592. * Disposes the camera
  103593. */
  103594. WebVRFreeCamera.prototype.dispose = function () {
  103595. this._detachIfAttached();
  103596. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  103597. if (this._updateCacheWhenTrackingDisabledObserver) {
  103598. this._scene.onBeforeRenderObservable.remove(this._updateCacheWhenTrackingDisabledObserver);
  103599. }
  103600. _super.prototype.dispose.call(this);
  103601. };
  103602. /**
  103603. * Gets a vrController by name.
  103604. * @param name The name of the controller to retreive
  103605. * @returns the controller matching the name specified or null if not found
  103606. */
  103607. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  103608. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  103609. var gp = _a[_i];
  103610. if (gp.hand === name) {
  103611. return gp;
  103612. }
  103613. }
  103614. return null;
  103615. };
  103616. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  103617. /**
  103618. * The controller corrisponding to the users left hand.
  103619. */
  103620. get: function () {
  103621. if (!this._leftController) {
  103622. this._leftController = this.getControllerByName("left");
  103623. }
  103624. return this._leftController;
  103625. },
  103626. enumerable: true,
  103627. configurable: true
  103628. });
  103629. ;
  103630. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  103631. /**
  103632. * The controller corrisponding to the users right hand.
  103633. */
  103634. get: function () {
  103635. if (!this._rightController) {
  103636. this._rightController = this.getControllerByName("right");
  103637. }
  103638. return this._rightController;
  103639. },
  103640. enumerable: true,
  103641. configurable: true
  103642. });
  103643. ;
  103644. /**
  103645. * Casts a ray forward from the vrCamera's gaze.
  103646. * @param length Length of the ray (default: 100)
  103647. * @returns the ray corrisponding to the gaze
  103648. */
  103649. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  103650. if (length === void 0) { length = 100; }
  103651. if (this.leftCamera) {
  103652. // Use left eye to avoid computation to compute center on every call
  103653. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  103654. }
  103655. else {
  103656. return _super.prototype.getForwardRay.call(this, length);
  103657. }
  103658. };
  103659. /**
  103660. * @hidden
  103661. * Updates the camera based on device's frame data
  103662. */
  103663. WebVRFreeCamera.prototype._checkInputs = function () {
  103664. if (this._vrDevice && this._vrDevice.isPresenting) {
  103665. this._vrDevice.getFrameData(this._frameData);
  103666. this.updateFromDevice(this._frameData.pose);
  103667. }
  103668. _super.prototype._checkInputs.call(this);
  103669. };
  103670. /**
  103671. * Updates the poseControlled values based on the input device pose.
  103672. * @param poseData Pose coming from the device
  103673. */
  103674. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  103675. if (poseData && poseData.orientation) {
  103676. this.rawPose = poseData;
  103677. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  103678. if (this.getScene().useRightHandedSystem) {
  103679. this._deviceRoomRotationQuaternion.z *= -1;
  103680. this._deviceRoomRotationQuaternion.w *= -1;
  103681. }
  103682. if (this.webVROptions.trackPosition && this.rawPose.position) {
  103683. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  103684. if (this.getScene().useRightHandedSystem) {
  103685. this._deviceRoomPosition.z *= -1;
  103686. }
  103687. }
  103688. this._poseSet = true;
  103689. }
  103690. };
  103691. /**
  103692. * WebVR's attach control will start broadcasting frames to the device.
  103693. * Note that in certain browsers (chrome for example) this function must be called
  103694. * within a user-interaction callback. Example:
  103695. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  103696. *
  103697. * @param element html element to attach the vrDevice to
  103698. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  103699. */
  103700. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  103701. _super.prototype.attachControl.call(this, element, noPreventDefault);
  103702. this._attached = true;
  103703. this._htmlElementAttached = element;
  103704. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  103705. if (this._vrDevice) {
  103706. this.getEngine().enableVR();
  103707. }
  103708. window.addEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103709. };
  103710. /**
  103711. * Detaches the camera from the html element and disables VR
  103712. *
  103713. * @param element html element to detach from
  103714. */
  103715. WebVRFreeCamera.prototype.detachControl = function (element) {
  103716. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  103717. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  103718. _super.prototype.detachControl.call(this, element);
  103719. this._attached = false;
  103720. this.getEngine().disableVR();
  103721. window.removeEventListener('vrdisplaypresentchange', this._detachIfAttached);
  103722. };
  103723. /**
  103724. * @returns the name of this class
  103725. */
  103726. WebVRFreeCamera.prototype.getClassName = function () {
  103727. return "WebVRFreeCamera";
  103728. };
  103729. /**
  103730. * Calls resetPose on the vrDisplay
  103731. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  103732. */
  103733. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  103734. //uses the vrDisplay's "resetPose()".
  103735. //pitch and roll won't be affected.
  103736. this._vrDevice.resetPose();
  103737. };
  103738. /**
  103739. * @hidden
  103740. * Updates the rig cameras (left and right eye)
  103741. */
  103742. WebVRFreeCamera.prototype._updateRigCameras = function () {
  103743. var camLeft = this._rigCameras[0];
  103744. var camRight = this._rigCameras[1];
  103745. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  103746. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  103747. camLeft.position.copyFrom(this._deviceRoomPosition);
  103748. camRight.position.copyFrom(this._deviceRoomPosition);
  103749. };
  103750. // Remove translation from 6dof headset if trackposition is set to false
  103751. WebVRFreeCamera.prototype._correctPositionIfNotTrackPosition = function (matrix, isViewMatrix) {
  103752. if (isViewMatrix === void 0) { isViewMatrix = false; }
  103753. if (this.rawPose && this.rawPose.position && !this.webVROptions.trackPosition) {
  103754. BABYLON.Matrix.TranslationToRef(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2], this._tmpMatrix);
  103755. if (!isViewMatrix) {
  103756. this._tmpMatrix.invert();
  103757. }
  103758. this._tmpMatrix.multiplyToRef(matrix, matrix);
  103759. }
  103760. };
  103761. /**
  103762. * @hidden
  103763. * Updates the cached values of the camera
  103764. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  103765. */
  103766. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  103767. var _this = this;
  103768. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  103769. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  103770. if (!this.updateCacheCalled) {
  103771. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  103772. this.updateCacheCalled = true;
  103773. this.update();
  103774. }
  103775. // Set working vector to the device position in room space rotated by the new rotation
  103776. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  103777. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  103778. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  103779. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  103780. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  103781. // Add translation from anchor position
  103782. this._deviceToWorld.getTranslationToRef(this._workingVector);
  103783. this._workingVector.addInPlace(this.position);
  103784. this._workingVector.subtractInPlace(this._cache.position);
  103785. this._deviceToWorld.setTranslation(this._workingVector);
  103786. // Set an inverted matrix to be used when updating the camera
  103787. this._deviceToWorld.invertToRef(this._worldToDevice);
  103788. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  103789. this.controllers.forEach(function (controller) {
  103790. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  103791. _this._correctPositionIfNotTrackPosition(controller._deviceToWorld);
  103792. controller.update();
  103793. });
  103794. }
  103795. if (!ignoreParentClass) {
  103796. _super.prototype._updateCache.call(this);
  103797. }
  103798. this.updateCacheCalled = false;
  103799. };
  103800. /**
  103801. * @hidden
  103802. * Get current device position in babylon world
  103803. */
  103804. WebVRFreeCamera.prototype._computeDevicePosition = function () {
  103805. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  103806. };
  103807. /**
  103808. * Updates the current device position and rotation in the babylon world
  103809. */
  103810. WebVRFreeCamera.prototype.update = function () {
  103811. this._computeDevicePosition();
  103812. // Get current device rotation in babylon world
  103813. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  103814. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  103815. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  103816. if (this._poseSet) {
  103817. this.onPoseUpdatedFromDeviceObservable.notifyObservers(null);
  103818. }
  103819. _super.prototype.update.call(this);
  103820. };
  103821. /**
  103822. * @hidden
  103823. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  103824. * @returns an identity matrix
  103825. */
  103826. WebVRFreeCamera.prototype._getViewMatrix = function () {
  103827. return BABYLON.Matrix.Identity();
  103828. };
  103829. /**
  103830. * This function is called by the two RIG cameras.
  103831. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  103832. */
  103833. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  103834. var _this = this;
  103835. // Update the parent camera prior to using a child camera to avoid desynchronization
  103836. var parentCamera = this._cameraRigParams["parentCamera"];
  103837. parentCamera._updateCache();
  103838. //WebVR 1.1
  103839. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  103840. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  103841. if (!this.getScene().useRightHandedSystem) {
  103842. [2, 6, 8, 9, 14].forEach(function (num) {
  103843. _this._webvrViewMatrix.m[num] *= -1;
  103844. });
  103845. }
  103846. // update the camera rotation matrix
  103847. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  103848. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  103849. // Computing target and final matrix
  103850. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  103851. // should the view matrix be updated with scale and position offset?
  103852. if (parentCamera.deviceScaleFactor !== 1) {
  103853. this._webvrViewMatrix.invert();
  103854. // scale the position, if set
  103855. if (parentCamera.deviceScaleFactor) {
  103856. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  103857. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  103858. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  103859. }
  103860. this._webvrViewMatrix.invert();
  103861. }
  103862. // Remove translation from 6dof headset if trackposition is set to false
  103863. parentCamera._correctPositionIfNotTrackPosition(this._webvrViewMatrix, true);
  103864. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  103865. // Compute global position
  103866. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  103867. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  103868. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  103869. this._workingMatrix.getTranslationToRef(this._globalPosition);
  103870. this._markSyncedWithParent();
  103871. return this._webvrViewMatrix;
  103872. };
  103873. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  103874. var _this = this;
  103875. var parentCamera = this.parent;
  103876. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  103877. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  103878. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  103879. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  103880. //babylon compatible matrix
  103881. if (!this.getScene().useRightHandedSystem) {
  103882. [8, 9, 10, 11].forEach(function (num) {
  103883. _this._projectionMatrix.m[num] *= -1;
  103884. });
  103885. }
  103886. return this._projectionMatrix;
  103887. };
  103888. /**
  103889. * Initializes the controllers and their meshes
  103890. */
  103891. WebVRFreeCamera.prototype.initControllers = function () {
  103892. var _this = this;
  103893. this.controllers = [];
  103894. var manager = this.getScene().gamepadManager;
  103895. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  103896. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  103897. var webVrController = gamepad;
  103898. if (webVrController.defaultModel) {
  103899. webVrController.defaultModel.setEnabled(false);
  103900. }
  103901. if (webVrController.hand === "right") {
  103902. _this._rightController = null;
  103903. }
  103904. if (webVrController.hand === "left") {
  103905. _this._leftController = null;
  103906. }
  103907. var controllerIndex = _this.controllers.indexOf(webVrController);
  103908. if (controllerIndex !== -1) {
  103909. _this.controllers.splice(controllerIndex, 1);
  103910. }
  103911. }
  103912. });
  103913. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  103914. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  103915. var webVrController_1 = gamepad;
  103916. if (!_this.webVROptions.trackPosition) {
  103917. webVrController_1._disableTrackPosition(new BABYLON.Vector3(webVrController_1.hand == "left" ? -0.15 : 0.15, -0.5, 0.25));
  103918. // Cache must be updated before rendering controllers to avoid them being one frame behind
  103919. if (!_this._updateCacheWhenTrackingDisabledObserver) {
  103920. _this._updateCacheWhenTrackingDisabledObserver = _this._scene.onBeforeRenderObservable.add(function () {
  103921. _this._updateCache();
  103922. });
  103923. }
  103924. }
  103925. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  103926. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  103927. _this._correctPositionIfNotTrackPosition(webVrController_1._deviceToWorld);
  103928. if (_this.webVROptions.controllerMeshes) {
  103929. if (webVrController_1.defaultModel) {
  103930. webVrController_1.defaultModel.setEnabled(true);
  103931. }
  103932. else {
  103933. // Load the meshes
  103934. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  103935. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  103936. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  103937. if (_this.webVROptions.defaultLightingOnControllers) {
  103938. if (!_this._lightOnControllers) {
  103939. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  103940. }
  103941. var activateLightOnSubMeshes_1 = function (mesh, light) {
  103942. var children = mesh.getChildren();
  103943. if (children && children.length !== 0) {
  103944. children.forEach(function (mesh) {
  103945. light.includedOnlyMeshes.push(mesh);
  103946. activateLightOnSubMeshes_1(mesh, light);
  103947. });
  103948. }
  103949. };
  103950. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  103951. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  103952. }
  103953. });
  103954. }
  103955. }
  103956. webVrController_1.attachToPoseControlledCamera(_this);
  103957. // since this is async - sanity check. Is the controller already stored?
  103958. if (_this.controllers.indexOf(webVrController_1) === -1) {
  103959. //add to the controllers array
  103960. _this.controllers.push(webVrController_1);
  103961. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  103962. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  103963. // So we're overriding setting left & right manually to be sure
  103964. var firstViveWandDetected = false;
  103965. for (var i = 0; i < _this.controllers.length; i++) {
  103966. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  103967. if (!firstViveWandDetected) {
  103968. firstViveWandDetected = true;
  103969. _this.controllers[i].hand = "left";
  103970. }
  103971. else {
  103972. _this.controllers[i].hand = "right";
  103973. }
  103974. }
  103975. }
  103976. //did we find enough controllers? Great! let the developer know.
  103977. if (_this.controllers.length >= 2) {
  103978. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  103979. }
  103980. }
  103981. }
  103982. });
  103983. };
  103984. return WebVRFreeCamera;
  103985. }(BABYLON.FreeCamera));
  103986. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  103987. })(BABYLON || (BABYLON = {}));
  103988. //# sourceMappingURL=babylon.webVRCamera.js.map
  103989. var BABYLON;
  103990. (function (BABYLON) {
  103991. BABYLON.Node.AddNodeConstructor("DeviceOrientationCamera", function (name, scene) {
  103992. return function () { return new DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  103993. });
  103994. // We're mainly based on the logic defined into the FreeCamera code
  103995. /**
  103996. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  103997. * being tilted forward or back and left or right.
  103998. */
  103999. var DeviceOrientationCamera = /** @class */ (function (_super) {
  104000. __extends(DeviceOrientationCamera, _super);
  104001. /**
  104002. * Creates a new device orientation camera
  104003. * @param name The name of the camera
  104004. * @param position The start position camera
  104005. * @param scene The scene the camera belongs to
  104006. */
  104007. function DeviceOrientationCamera(name, position, scene) {
  104008. var _this = _super.call(this, name, position, scene) || this;
  104009. _this._quaternionCache = new BABYLON.Quaternion();
  104010. _this.inputs.addDeviceOrientation();
  104011. return _this;
  104012. }
  104013. /**
  104014. * Gets the current instance class name ("DeviceOrientationCamera").
  104015. * This helps avoiding instanceof at run time.
  104016. * @returns the class name
  104017. */
  104018. DeviceOrientationCamera.prototype.getClassName = function () {
  104019. return "DeviceOrientationCamera";
  104020. };
  104021. /**
  104022. * @hidden
  104023. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  104024. */
  104025. DeviceOrientationCamera.prototype._checkInputs = function () {
  104026. _super.prototype._checkInputs.call(this);
  104027. this._quaternionCache.copyFrom(this.rotationQuaternion);
  104028. if (this._initialQuaternion) {
  104029. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104030. }
  104031. };
  104032. /**
  104033. * Reset the camera to its default orientation on the specified axis only.
  104034. * @param axis The axis to reset
  104035. */
  104036. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  104037. var _this = this;
  104038. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  104039. //can only work if this camera has a rotation quaternion already.
  104040. if (!this.rotationQuaternion)
  104041. return;
  104042. if (!this._initialQuaternion) {
  104043. this._initialQuaternion = new BABYLON.Quaternion();
  104044. }
  104045. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  104046. ['x', 'y', 'z'].forEach(function (axisName) {
  104047. if (!axis[axisName]) {
  104048. _this._initialQuaternion[axisName] = 0;
  104049. }
  104050. else {
  104051. _this._initialQuaternion[axisName] *= -1;
  104052. }
  104053. });
  104054. this._initialQuaternion.normalize();
  104055. //force rotation update
  104056. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  104057. };
  104058. return DeviceOrientationCamera;
  104059. }(BABYLON.FreeCamera));
  104060. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  104061. })(BABYLON || (BABYLON = {}));
  104062. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  104063. var BABYLON;
  104064. (function (BABYLON) {
  104065. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104066. return function () { return new VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  104067. });
  104068. /**
  104069. * Camera used to simulate VR rendering (based on FreeCamera)
  104070. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104071. */
  104072. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  104073. __extends(VRDeviceOrientationFreeCamera, _super);
  104074. /**
  104075. * Creates a new VRDeviceOrientationFreeCamera
  104076. * @param name defines camera name
  104077. * @param position defines the start position of the camera
  104078. * @param scene defines the scene the camera belongs to
  104079. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104080. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104081. */
  104082. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104083. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104084. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104085. var _this = _super.call(this, name, position, scene) || this;
  104086. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104087. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104088. return _this;
  104089. }
  104090. /**
  104091. * Gets camera class name
  104092. * @returns VRDeviceOrientationFreeCamera
  104093. */
  104094. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  104095. return "VRDeviceOrientationFreeCamera";
  104096. };
  104097. return VRDeviceOrientationFreeCamera;
  104098. }(BABYLON.DeviceOrientationCamera));
  104099. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  104100. })(BABYLON || (BABYLON = {}));
  104101. //# sourceMappingURL=babylon.vrDeviceOrientationFreeCamera.js.map
  104102. var BABYLON;
  104103. (function (BABYLON) {
  104104. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationFreeCamera", function (name, scene) {
  104105. return function () { return new VRDeviceOrientationArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  104106. });
  104107. /**
  104108. * Camera used to simulate VR rendering (based on ArcRotateCamera)
  104109. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104110. */
  104111. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  104112. __extends(VRDeviceOrientationArcRotateCamera, _super);
  104113. /**
  104114. * Creates a new VRDeviceOrientationArcRotateCamera
  104115. * @param name defines camera name
  104116. * @param alpha defines the camera rotation along the logitudinal axis
  104117. * @param beta defines the camera rotation along the latitudinal axis
  104118. * @param radius defines the camera distance from its target
  104119. * @param target defines the camera target
  104120. * @param scene defines the scene the camera belongs to
  104121. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104122. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104123. */
  104124. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  104125. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104126. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104127. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  104128. vrCameraMetrics.compensateDistortion = compensateDistortion;
  104129. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  104130. _this.inputs.addVRDeviceOrientation();
  104131. return _this;
  104132. }
  104133. /**
  104134. * Gets camera class name
  104135. * @returns VRDeviceOrientationArcRotateCamera
  104136. */
  104137. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  104138. return "VRDeviceOrientationArcRotateCamera";
  104139. };
  104140. return VRDeviceOrientationArcRotateCamera;
  104141. }(BABYLON.ArcRotateCamera));
  104142. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  104143. })(BABYLON || (BABYLON = {}));
  104144. //# sourceMappingURL=babylon.vrDeviceOrientationArcRotateCamera.js.map
  104145. var BABYLON;
  104146. (function (BABYLON) {
  104147. BABYLON.Node.AddNodeConstructor("VRDeviceOrientationGamepadCamera", function (name, scene) {
  104148. return function () { return new VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  104149. });
  104150. /**
  104151. * Camera used to simulate VR rendering (based on VRDeviceOrientationFreeCamera)
  104152. * @see http://doc.babylonjs.com/babylon101/cameras#vr-device-orientation-cameras
  104153. */
  104154. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  104155. __extends(VRDeviceOrientationGamepadCamera, _super);
  104156. /**
  104157. * Creates a new VRDeviceOrientationGamepadCamera
  104158. * @param name defines camera name
  104159. * @param position defines the start position of the camera
  104160. * @param scene defines the scene the camera belongs to
  104161. * @param compensateDistortion defines if the camera needs to compensate the lens distorsion
  104162. * @param vrCameraMetrics defines the vr metrics associated to the camera
  104163. */
  104164. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  104165. if (compensateDistortion === void 0) { compensateDistortion = true; }
  104166. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  104167. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  104168. _this.inputs.addGamepad();
  104169. return _this;
  104170. }
  104171. /**
  104172. * Gets camera class name
  104173. * @returns VRDeviceOrientationGamepadCamera
  104174. */
  104175. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  104176. return "VRDeviceOrientationGamepadCamera";
  104177. };
  104178. return VRDeviceOrientationGamepadCamera;
  104179. }(BABYLON.VRDeviceOrientationFreeCamera));
  104180. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  104181. })(BABYLON || (BABYLON = {}));
  104182. //# sourceMappingURL=babylon.vrDeviceOrientationGamepadCamera.js.map
  104183. var BABYLON;
  104184. (function (BABYLON) {
  104185. var VRExperienceHelperGazer = /** @class */ (function () {
  104186. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  104187. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  104188. this.scene = scene;
  104189. /** @hidden */
  104190. this._pointerDownOnMeshAsked = false;
  104191. /** @hidden */
  104192. this._isActionableMesh = false;
  104193. /** @hidden */
  104194. this._teleportationRequestInitiated = false;
  104195. /** @hidden */
  104196. this._teleportationBackRequestInitiated = false;
  104197. /** @hidden */
  104198. this._rotationRightAsked = false;
  104199. /** @hidden */
  104200. this._rotationLeftAsked = false;
  104201. /** @hidden */
  104202. this._dpadPressed = true;
  104203. /** @hidden */
  104204. this._activePointer = false;
  104205. this._id = VRExperienceHelperGazer._idCounter++;
  104206. // Gaze tracker
  104207. if (!gazeTrackerToClone) {
  104208. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  104209. this._gazeTracker.bakeCurrentTransformIntoVertices();
  104210. this._gazeTracker.isPickable = false;
  104211. this._gazeTracker.isVisible = false;
  104212. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  104213. targetMat.specularColor = BABYLON.Color3.Black();
  104214. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104215. targetMat.backFaceCulling = false;
  104216. this._gazeTracker.material = targetMat;
  104217. }
  104218. else {
  104219. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  104220. }
  104221. }
  104222. /** @hidden */
  104223. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  104224. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  104225. };
  104226. /** @hidden */
  104227. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  104228. this._pointerDownOnMeshAsked = true;
  104229. if (this._currentHit) {
  104230. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  104231. }
  104232. };
  104233. /** @hidden */
  104234. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  104235. if (this._currentHit) {
  104236. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  104237. }
  104238. this._pointerDownOnMeshAsked = false;
  104239. };
  104240. /** @hidden */
  104241. VRExperienceHelperGazer.prototype._activatePointer = function () {
  104242. this._activePointer = true;
  104243. };
  104244. /** @hidden */
  104245. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  104246. this._activePointer = false;
  104247. };
  104248. /** @hidden */
  104249. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  104250. if (distance === void 0) { distance = 100; }
  104251. };
  104252. VRExperienceHelperGazer.prototype.dispose = function () {
  104253. this._interactionsEnabled = false;
  104254. this._teleportationEnabled = false;
  104255. if (this._gazeTracker) {
  104256. this._gazeTracker.dispose();
  104257. }
  104258. };
  104259. VRExperienceHelperGazer._idCounter = 0;
  104260. return VRExperienceHelperGazer;
  104261. }());
  104262. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  104263. __extends(VRExperienceHelperControllerGazer, _super);
  104264. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  104265. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  104266. _this.webVRController = webVRController;
  104267. // Laser pointer
  104268. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  104269. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  104270. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  104271. laserPointerMaterial.alpha = 0.6;
  104272. _this._laserPointer.material = laserPointerMaterial;
  104273. _this._laserPointer.rotation.x = Math.PI / 2;
  104274. _this._laserPointer.position.z = -0.5;
  104275. _this._laserPointer.isVisible = false;
  104276. _this._laserPointer.isPickable = false;
  104277. if (!webVRController.mesh) {
  104278. // Create an empty mesh that is used prior to loading the high quality model
  104279. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  104280. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  104281. preloadPointerPose.rotation.x = -0.7;
  104282. preloadMesh.addChild(preloadPointerPose);
  104283. webVRController.attachToMesh(preloadMesh);
  104284. }
  104285. _this._setLaserPointerParent(webVRController.mesh);
  104286. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  104287. _this._setLaserPointerParent(mesh);
  104288. });
  104289. return _this;
  104290. }
  104291. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  104292. return this.webVRController.getForwardRay(length);
  104293. };
  104294. /** @hidden */
  104295. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  104296. _super.prototype._activatePointer.call(this);
  104297. this._laserPointer.isVisible = true;
  104298. };
  104299. /** @hidden */
  104300. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  104301. _super.prototype._deactivatePointer.call(this);
  104302. this._laserPointer.isVisible = false;
  104303. };
  104304. /** @hidden */
  104305. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  104306. this._laserPointer.material.emissiveColor = color;
  104307. };
  104308. /** @hidden */
  104309. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  104310. var makeNotPick = function (root) {
  104311. root.isPickable = false;
  104312. root.getChildMeshes().forEach(function (c) {
  104313. makeNotPick(c);
  104314. });
  104315. };
  104316. makeNotPick(mesh);
  104317. var childMeshes = mesh.getChildMeshes();
  104318. this.webVRController._pointingPoseNode = null;
  104319. for (var i = 0; i < childMeshes.length; i++) {
  104320. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  104321. mesh = childMeshes[i];
  104322. this.webVRController._pointingPoseNode = mesh;
  104323. break;
  104324. }
  104325. }
  104326. this._laserPointer.parent = mesh;
  104327. };
  104328. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  104329. if (distance === void 0) { distance = 100; }
  104330. this._laserPointer.scaling.y = distance;
  104331. this._laserPointer.position.z = -distance / 2;
  104332. };
  104333. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  104334. _super.prototype.dispose.call(this);
  104335. this._laserPointer.dispose();
  104336. if (this._meshAttachedObserver) {
  104337. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  104338. }
  104339. };
  104340. return VRExperienceHelperControllerGazer;
  104341. }(VRExperienceHelperGazer));
  104342. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  104343. __extends(VRExperienceHelperCameraGazer, _super);
  104344. function VRExperienceHelperCameraGazer(getCamera, scene) {
  104345. var _this = _super.call(this, scene) || this;
  104346. _this.getCamera = getCamera;
  104347. return _this;
  104348. }
  104349. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  104350. var camera = this.getCamera();
  104351. if (camera) {
  104352. return camera.getForwardRay(length);
  104353. }
  104354. else {
  104355. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  104356. }
  104357. };
  104358. return VRExperienceHelperCameraGazer;
  104359. }(VRExperienceHelperGazer));
  104360. /**
  104361. * Helps to quickly add VR support to an existing scene.
  104362. * See http://doc.babylonjs.com/how_to/webvr_helper
  104363. */
  104364. var VRExperienceHelper = /** @class */ (function () {
  104365. /**
  104366. * Instantiates a VRExperienceHelper.
  104367. * Helps to quickly add VR support to an existing scene.
  104368. * @param scene The scene the VRExperienceHelper belongs to.
  104369. * @param webVROptions Options to modify the vr experience helper's behavior.
  104370. */
  104371. function VRExperienceHelper(scene,
  104372. /** Options to modify the vr experience helper's behavior. */
  104373. webVROptions) {
  104374. if (webVROptions === void 0) { webVROptions = {}; }
  104375. var _this = this;
  104376. this.webVROptions = webVROptions;
  104377. // Can the system support WebVR, even if a headset isn't plugged in?
  104378. this._webVRsupported = false;
  104379. // If WebVR is supported, is a headset plugged in and are we ready to present?
  104380. this._webVRready = false;
  104381. // Are we waiting for the requestPresent callback to complete?
  104382. this._webVRrequesting = false;
  104383. // Are we presenting to the headset right now? (this is the vrDevice state)
  104384. this._webVRpresenting = false;
  104385. // Are we presenting in the fullscreen fallback?
  104386. this._fullscreenVRpresenting = false;
  104387. /**
  104388. * Observable raised when entering VR.
  104389. */
  104390. this.onEnteringVRObservable = new BABYLON.Observable();
  104391. /**
  104392. * Observable raised when exiting VR.
  104393. */
  104394. this.onExitingVRObservable = new BABYLON.Observable();
  104395. /**
  104396. * Observable raised when controller mesh is loaded.
  104397. */
  104398. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  104399. this._useCustomVRButton = false;
  104400. this._teleportationRequested = false;
  104401. this._teleportActive = false;
  104402. this._floorMeshesCollection = [];
  104403. this._rotationAllowed = true;
  104404. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  104405. this._isDefaultTeleportationTarget = true;
  104406. this._teleportationFillColor = "#444444";
  104407. this._teleportationBorderColor = "#FFFFFF";
  104408. this._rotationAngle = 0;
  104409. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  104410. this._padSensibilityUp = 0.65;
  104411. this._padSensibilityDown = 0.35;
  104412. this._leftController = null;
  104413. this._rightController = null;
  104414. /**
  104415. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  104416. */
  104417. this.onNewMeshSelected = new BABYLON.Observable();
  104418. /**
  104419. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  104420. */
  104421. this.onNewMeshPicked = new BABYLON.Observable();
  104422. /**
  104423. * Observable raised before camera teleportation
  104424. */
  104425. this.onBeforeCameraTeleport = new BABYLON.Observable();
  104426. /**
  104427. * Observable raised after camera teleportation
  104428. */
  104429. this.onAfterCameraTeleport = new BABYLON.Observable();
  104430. /**
  104431. * Observable raised when current selected mesh gets unselected
  104432. */
  104433. this.onSelectedMeshUnselected = new BABYLON.Observable();
  104434. /**
  104435. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  104436. */
  104437. this.teleportationEnabled = true;
  104438. this._teleportationInitialized = false;
  104439. this._interactionsEnabled = false;
  104440. this._interactionsRequested = false;
  104441. this._displayGaze = true;
  104442. this._displayLaserPointer = true;
  104443. /**
  104444. * If the gaze trackers scale should be updated to be constant size when pointing at near/far meshes
  104445. */
  104446. this.updateGazeTrackerScale = true;
  104447. this._onResize = function () {
  104448. _this.moveButtonToBottomRight();
  104449. if (_this._fullscreenVRpresenting && _this._webVRready) {
  104450. _this.exitVR();
  104451. }
  104452. };
  104453. this._onFullscreenChange = function () {
  104454. if (document.fullscreen !== undefined) {
  104455. _this._fullscreenVRpresenting = document.fullscreen;
  104456. }
  104457. else if (document.mozFullScreen !== undefined) {
  104458. _this._fullscreenVRpresenting = document.mozFullScreen;
  104459. }
  104460. else if (document.webkitIsFullScreen !== undefined) {
  104461. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  104462. }
  104463. else if (document.msIsFullScreen !== undefined) {
  104464. _this._fullscreenVRpresenting = document.msIsFullScreen;
  104465. }
  104466. else if (document.msFullscreenElement !== undefined) {
  104467. _this._fullscreenVRpresenting = document.msFullscreenElement;
  104468. }
  104469. if (!_this._fullscreenVRpresenting && _this._canvas) {
  104470. _this.exitVR();
  104471. if (!_this._useCustomVRButton) {
  104472. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  104473. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  104474. }
  104475. }
  104476. };
  104477. this.beforeRender = function () {
  104478. if (_this._leftController && _this._leftController._activePointer) {
  104479. _this._castRayAndSelectObject(_this._leftController);
  104480. }
  104481. if (_this._rightController && _this._rightController._activePointer) {
  104482. _this._castRayAndSelectObject(_this._rightController);
  104483. }
  104484. if (_this._noControllerIsActive) {
  104485. _this._castRayAndSelectObject(_this._cameraGazer);
  104486. }
  104487. else {
  104488. _this._cameraGazer._gazeTracker.isVisible = false;
  104489. }
  104490. };
  104491. this._onNewGamepadConnected = function (gamepad) {
  104492. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  104493. if (gamepad.leftStick) {
  104494. gamepad.onleftstickchanged(function (stickValues) {
  104495. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  104496. // Listening to classic/xbox gamepad only if no VR controller is active
  104497. if ((!_this._leftController && !_this._rightController) ||
  104498. ((_this._leftController && !_this._leftController._activePointer) &&
  104499. (_this._rightController && !_this._rightController._activePointer))) {
  104500. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  104501. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  104502. }
  104503. }
  104504. });
  104505. }
  104506. if (gamepad.rightStick) {
  104507. gamepad.onrightstickchanged(function (stickValues) {
  104508. if (_this._teleportationInitialized) {
  104509. _this._checkRotate(stickValues, _this._cameraGazer);
  104510. }
  104511. });
  104512. }
  104513. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  104514. gamepad.onbuttondown(function (buttonPressed) {
  104515. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104516. _this._cameraGazer._selectionPointerDown();
  104517. }
  104518. });
  104519. gamepad.onbuttonup(function (buttonPressed) {
  104520. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  104521. _this._cameraGazer._selectionPointerUp();
  104522. }
  104523. });
  104524. }
  104525. }
  104526. else {
  104527. var webVRController = gamepad;
  104528. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  104529. if (webVRController.hand === "right" || (_this._leftController && _this._leftController.webVRController != webVRController)) {
  104530. _this._rightController = controller;
  104531. }
  104532. else {
  104533. _this._leftController = controller;
  104534. }
  104535. _this._tryEnableInteractionOnController(controller);
  104536. }
  104537. };
  104538. // 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
  104539. this._tryEnableInteractionOnController = function (controller) {
  104540. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  104541. _this._enableInteractionOnController(controller);
  104542. }
  104543. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  104544. _this._enableTeleportationOnController(controller);
  104545. }
  104546. };
  104547. this._onNewGamepadDisconnected = function (gamepad) {
  104548. if (gamepad instanceof BABYLON.WebVRController) {
  104549. if (gamepad.hand === "left" && _this._leftController != null) {
  104550. _this._leftController.dispose();
  104551. _this._leftController = null;
  104552. }
  104553. if (gamepad.hand === "right" && _this._rightController != null) {
  104554. _this._rightController.dispose();
  104555. _this._rightController = null;
  104556. }
  104557. }
  104558. };
  104559. this._workingVector = BABYLON.Vector3.Zero();
  104560. this._workingQuaternion = BABYLON.Quaternion.Identity();
  104561. this._workingMatrix = BABYLON.Matrix.Identity();
  104562. this._scene = scene;
  104563. this._canvas = scene.getEngine().getRenderingCanvas();
  104564. // Parse options
  104565. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  104566. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  104567. }
  104568. if (webVROptions.createDeviceOrientationCamera === undefined) {
  104569. webVROptions.createDeviceOrientationCamera = true;
  104570. }
  104571. if (webVROptions.laserToggle === undefined) {
  104572. webVROptions.laserToggle = true;
  104573. }
  104574. if (webVROptions.defaultHeight === undefined) {
  104575. webVROptions.defaultHeight = 1.7;
  104576. }
  104577. if (webVROptions.useCustomVRButton) {
  104578. this._useCustomVRButton = true;
  104579. if (webVROptions.customVRButton) {
  104580. this._btnVR = webVROptions.customVRButton;
  104581. }
  104582. }
  104583. if (webVROptions.rayLength) {
  104584. this._rayLength = webVROptions.rayLength;
  104585. }
  104586. this._defaultHeight = webVROptions.defaultHeight;
  104587. if (webVROptions.positionScale) {
  104588. this._rayLength *= webVROptions.positionScale;
  104589. this._defaultHeight *= webVROptions.positionScale;
  104590. }
  104591. this._hasEnteredVR = false;
  104592. // Set position
  104593. if (this._scene.activeCamera) {
  104594. this._position = this._scene.activeCamera.position.clone();
  104595. }
  104596. else {
  104597. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  104598. }
  104599. // Set non-vr camera
  104600. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  104601. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  104602. // Copy data from existing camera
  104603. if (this._scene.activeCamera) {
  104604. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  104605. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  104606. // Set rotation from previous camera
  104607. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  104608. var targetCamera = this._scene.activeCamera;
  104609. if (targetCamera.rotationQuaternion) {
  104610. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  104611. }
  104612. else {
  104613. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  104614. }
  104615. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  104616. }
  104617. }
  104618. this._scene.activeCamera = this._deviceOrientationCamera;
  104619. if (this._canvas) {
  104620. this._scene.activeCamera.attachControl(this._canvas);
  104621. }
  104622. }
  104623. else {
  104624. this._existingCamera = this._scene.activeCamera;
  104625. }
  104626. // Create VR cameras
  104627. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104628. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  104629. }
  104630. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  104631. this._webVRCamera.useStandingMatrix();
  104632. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  104633. // Create default button
  104634. if (!this._useCustomVRButton) {
  104635. this._btnVR = document.createElement("BUTTON");
  104636. this._btnVR.className = "babylonVRicon";
  104637. this._btnVR.id = "babylonVRiconbtn";
  104638. this._btnVR.title = "Click to switch to VR";
  104639. 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) }";
  104640. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  104641. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  104642. // css += ".babylonVRicon.vrdisplaysupported { }";
  104643. // css += ".babylonVRicon.vrdisplayready { }";
  104644. // css += ".babylonVRicon.vrdisplayrequesting { }";
  104645. var style = document.createElement('style');
  104646. style.appendChild(document.createTextNode(css));
  104647. document.getElementsByTagName('head')[0].appendChild(style);
  104648. this.moveButtonToBottomRight();
  104649. }
  104650. // VR button click event
  104651. if (this._btnVR) {
  104652. this._btnVR.addEventListener("click", function () {
  104653. if (!_this.isInVRMode) {
  104654. _this.enterVR();
  104655. }
  104656. else {
  104657. _this.exitVR();
  104658. }
  104659. });
  104660. }
  104661. // Window events
  104662. window.addEventListener("resize", this._onResize);
  104663. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  104664. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  104665. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  104666. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  104667. document.onmsfullscreenchange = this._onFullscreenChange;
  104668. // Display vr button when headset is connected
  104669. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  104670. this.displayVRButton();
  104671. }
  104672. else {
  104673. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  104674. if (e.vrDisplay) {
  104675. _this.displayVRButton();
  104676. }
  104677. });
  104678. }
  104679. // Exiting VR mode using 'ESC' key on desktop
  104680. this._onKeyDown = function (event) {
  104681. if (event.keyCode === 27 && _this.isInVRMode) {
  104682. _this.exitVR();
  104683. }
  104684. };
  104685. document.addEventListener("keydown", this._onKeyDown);
  104686. // Exiting VR mode double tapping the touch screen
  104687. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  104688. if (_this.isInVRMode) {
  104689. _this.exitVR();
  104690. if (_this._fullscreenVRpresenting) {
  104691. _this._scene.getEngine().switchFullscreen(true);
  104692. }
  104693. }
  104694. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  104695. // Listen for WebVR display changes
  104696. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  104697. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  104698. this._onVRRequestPresentStart = function () {
  104699. _this._webVRrequesting = true;
  104700. _this.updateButtonVisibility();
  104701. };
  104702. this._onVRRequestPresentComplete = function (success) {
  104703. _this._webVRrequesting = false;
  104704. _this.updateButtonVisibility();
  104705. };
  104706. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  104707. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  104708. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  104709. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  104710. scene.onDisposeObservable.add(function () {
  104711. _this.dispose();
  104712. });
  104713. // Gamepad connection events
  104714. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  104715. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  104716. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  104717. this.updateButtonVisibility();
  104718. //create easing functions
  104719. this._circleEase = new BABYLON.CircleEase();
  104720. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  104721. if (this.webVROptions.floorMeshes) {
  104722. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  104723. }
  104724. }
  104725. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  104726. /** Return this.onEnteringVRObservable
  104727. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  104728. */
  104729. get: function () {
  104730. return this.onEnteringVRObservable;
  104731. },
  104732. enumerable: true,
  104733. configurable: true
  104734. });
  104735. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  104736. /** Return this.onExitingVRObservable
  104737. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  104738. */
  104739. get: function () {
  104740. return this.onExitingVRObservable;
  104741. },
  104742. enumerable: true,
  104743. configurable: true
  104744. });
  104745. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  104746. /** Return this.onControllerMeshLoadedObservable
  104747. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  104748. */
  104749. get: function () {
  104750. return this.onControllerMeshLoadedObservable;
  104751. },
  104752. enumerable: true,
  104753. configurable: true
  104754. });
  104755. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  104756. /**
  104757. * The mesh used to display where the user is going to teleport.
  104758. */
  104759. get: function () {
  104760. return this._teleportationTarget;
  104761. },
  104762. /**
  104763. * Sets the mesh to be used to display where the user is going to teleport.
  104764. */
  104765. set: function (value) {
  104766. if (value) {
  104767. value.name = "teleportationTarget";
  104768. this._isDefaultTeleportationTarget = false;
  104769. this._teleportationTarget = value;
  104770. }
  104771. },
  104772. enumerable: true,
  104773. configurable: true
  104774. });
  104775. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  104776. /**
  104777. * 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
  104778. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  104779. * See http://doc.babylonjs.com/resources/baking_transformations
  104780. */
  104781. get: function () {
  104782. return this._cameraGazer._gazeTracker;
  104783. },
  104784. set: function (value) {
  104785. if (value) {
  104786. // Dispose of existing meshes
  104787. if (this._cameraGazer._gazeTracker) {
  104788. this._cameraGazer._gazeTracker.dispose();
  104789. }
  104790. if (this._leftController && this._leftController._gazeTracker) {
  104791. this._leftController._gazeTracker.dispose();
  104792. }
  104793. if (this._rightController && this._rightController._gazeTracker) {
  104794. this._rightController._gazeTracker.dispose();
  104795. }
  104796. // Set and create gaze trackers on head and controllers
  104797. this._cameraGazer._gazeTracker = value;
  104798. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  104799. this._cameraGazer._gazeTracker.isPickable = false;
  104800. this._cameraGazer._gazeTracker.isVisible = false;
  104801. this._cameraGazer._gazeTracker.name = "gazeTracker";
  104802. if (this._leftController) {
  104803. this._leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  104804. }
  104805. if (this._rightController) {
  104806. this._rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  104807. }
  104808. }
  104809. },
  104810. enumerable: true,
  104811. configurable: true
  104812. });
  104813. Object.defineProperty(VRExperienceHelper.prototype, "leftControllerGazeTrackerMesh", {
  104814. /**
  104815. * The gaze tracking mesh corresponding to the left controller
  104816. */
  104817. get: function () {
  104818. if (this._leftController) {
  104819. return this._leftController._gazeTracker;
  104820. }
  104821. return null;
  104822. },
  104823. enumerable: true,
  104824. configurable: true
  104825. });
  104826. Object.defineProperty(VRExperienceHelper.prototype, "rightControllerGazeTrackerMesh", {
  104827. /**
  104828. * The gaze tracking mesh corresponding to the right controller
  104829. */
  104830. get: function () {
  104831. if (this._rightController) {
  104832. return this._rightController._gazeTracker;
  104833. }
  104834. return null;
  104835. },
  104836. enumerable: true,
  104837. configurable: true
  104838. });
  104839. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  104840. /**
  104841. * If the ray of the gaze should be displayed.
  104842. */
  104843. get: function () {
  104844. return this._displayGaze;
  104845. },
  104846. /**
  104847. * Sets if the ray of the gaze should be displayed.
  104848. */
  104849. set: function (value) {
  104850. this._displayGaze = value;
  104851. if (!value) {
  104852. this._cameraGazer._gazeTracker.isVisible = false;
  104853. if (this._leftController) {
  104854. this._leftController._gazeTracker.isVisible = false;
  104855. }
  104856. if (this._rightController) {
  104857. this._rightController._gazeTracker.isVisible = false;
  104858. }
  104859. }
  104860. },
  104861. enumerable: true,
  104862. configurable: true
  104863. });
  104864. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  104865. /**
  104866. * If the ray of the LaserPointer should be displayed.
  104867. */
  104868. get: function () {
  104869. return this._displayLaserPointer;
  104870. },
  104871. /**
  104872. * Sets if the ray of the LaserPointer should be displayed.
  104873. */
  104874. set: function (value) {
  104875. this._displayLaserPointer = value;
  104876. if (!value) {
  104877. if (this._rightController) {
  104878. this._rightController._deactivatePointer();
  104879. this._rightController._gazeTracker.isVisible = false;
  104880. }
  104881. if (this._leftController) {
  104882. this._leftController._deactivatePointer();
  104883. this._leftController._gazeTracker.isVisible = false;
  104884. }
  104885. }
  104886. else {
  104887. if (this._rightController) {
  104888. this._rightController._activatePointer();
  104889. }
  104890. if (this._leftController) {
  104891. this._leftController._activatePointer();
  104892. }
  104893. }
  104894. },
  104895. enumerable: true,
  104896. configurable: true
  104897. });
  104898. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  104899. /**
  104900. * The deviceOrientationCamera used as the camera when not in VR.
  104901. */
  104902. get: function () {
  104903. return this._deviceOrientationCamera;
  104904. },
  104905. enumerable: true,
  104906. configurable: true
  104907. });
  104908. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  104909. /**
  104910. * Based on the current WebVR support, returns the current VR camera used.
  104911. */
  104912. get: function () {
  104913. if (this._webVRready) {
  104914. return this._webVRCamera;
  104915. }
  104916. else {
  104917. return this._scene.activeCamera;
  104918. }
  104919. },
  104920. enumerable: true,
  104921. configurable: true
  104922. });
  104923. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  104924. /**
  104925. * The webVRCamera which is used when in VR.
  104926. */
  104927. get: function () {
  104928. return this._webVRCamera;
  104929. },
  104930. enumerable: true,
  104931. configurable: true
  104932. });
  104933. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  104934. /**
  104935. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  104936. */
  104937. get: function () {
  104938. return this._vrDeviceOrientationCamera;
  104939. },
  104940. enumerable: true,
  104941. configurable: true
  104942. });
  104943. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  104944. get: function () {
  104945. var result = this._cameraGazer._teleportationRequestInitiated
  104946. || (this._leftController !== null && this._leftController._teleportationRequestInitiated)
  104947. || (this._rightController !== null && this._rightController._teleportationRequestInitiated);
  104948. return result;
  104949. },
  104950. enumerable: true,
  104951. configurable: true
  104952. });
  104953. // Raised when one of the controller has loaded successfully its associated default mesh
  104954. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  104955. if (this._leftController && this._leftController.webVRController == webVRController) {
  104956. if (webVRController.mesh) {
  104957. this._leftController._setLaserPointerParent(webVRController.mesh);
  104958. }
  104959. }
  104960. if (this._rightController && this._rightController.webVRController == webVRController) {
  104961. if (webVRController.mesh) {
  104962. this._rightController._setLaserPointerParent(webVRController.mesh);
  104963. }
  104964. }
  104965. try {
  104966. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  104967. }
  104968. catch (err) {
  104969. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  104970. }
  104971. };
  104972. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  104973. /**
  104974. * Gets a value indicating if we are currently in VR mode.
  104975. */
  104976. get: function () {
  104977. return this._webVRpresenting || this._fullscreenVRpresenting;
  104978. },
  104979. enumerable: true,
  104980. configurable: true
  104981. });
  104982. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  104983. var vrDisplay = this._scene.getEngine().getVRDevice();
  104984. if (vrDisplay) {
  104985. var wasPresenting = this._webVRpresenting;
  104986. this._webVRpresenting = vrDisplay.isPresenting;
  104987. if (wasPresenting && !this._webVRpresenting)
  104988. this.exitVR();
  104989. }
  104990. else {
  104991. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  104992. }
  104993. this.updateButtonVisibility();
  104994. };
  104995. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  104996. this._webVRsupported = eventArgs.vrSupported;
  104997. this._webVRready = !!eventArgs.vrDisplay;
  104998. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  104999. this.updateButtonVisibility();
  105000. };
  105001. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  105002. if (this._canvas && !this._useCustomVRButton) {
  105003. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  105004. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  105005. }
  105006. };
  105007. VRExperienceHelper.prototype.displayVRButton = function () {
  105008. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  105009. document.body.appendChild(this._btnVR);
  105010. this._btnVRDisplayed = true;
  105011. }
  105012. };
  105013. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  105014. if (!this._btnVR || this._useCustomVRButton) {
  105015. return;
  105016. }
  105017. this._btnVR.className = "babylonVRicon";
  105018. if (this.isInVRMode) {
  105019. this._btnVR.className += " vrdisplaypresenting";
  105020. }
  105021. else {
  105022. if (this._webVRready)
  105023. this._btnVR.className += " vrdisplayready";
  105024. if (this._webVRsupported)
  105025. this._btnVR.className += " vrdisplaysupported";
  105026. if (this._webVRrequesting)
  105027. this._btnVR.className += " vrdisplayrequesting";
  105028. }
  105029. };
  105030. /**
  105031. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  105032. * Otherwise, will use the fullscreen API.
  105033. */
  105034. VRExperienceHelper.prototype.enterVR = function () {
  105035. if (this.onEnteringVRObservable) {
  105036. try {
  105037. this.onEnteringVRObservable.notifyObservers(this);
  105038. }
  105039. catch (err) {
  105040. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  105041. }
  105042. }
  105043. if (this._scene.activeCamera) {
  105044. this._position = this._scene.activeCamera.position.clone();
  105045. // make sure that we return to the last active camera
  105046. this._existingCamera = this._scene.activeCamera;
  105047. }
  105048. if (this._webVRrequesting)
  105049. return;
  105050. // If WebVR is supported and a headset is connected
  105051. if (this._webVRready) {
  105052. if (!this._webVRpresenting) {
  105053. this._webVRCamera.position = this._position;
  105054. this._scene.activeCamera = this._webVRCamera;
  105055. }
  105056. }
  105057. else if (this._vrDeviceOrientationCamera) {
  105058. this._vrDeviceOrientationCamera.position = this._position;
  105059. if (this._scene.activeCamera) {
  105060. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  105061. }
  105062. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  105063. this._scene.getEngine().switchFullscreen(true);
  105064. this.updateButtonVisibility();
  105065. }
  105066. if (this._scene.activeCamera && this._canvas) {
  105067. this._scene.activeCamera.attachControl(this._canvas);
  105068. }
  105069. if (this._interactionsEnabled) {
  105070. this._scene.registerBeforeRender(this.beforeRender);
  105071. }
  105072. this._hasEnteredVR = true;
  105073. };
  105074. /**
  105075. * Attempt to exit VR, or fullscreen.
  105076. */
  105077. VRExperienceHelper.prototype.exitVR = function () {
  105078. if (this._hasEnteredVR) {
  105079. if (this.onExitingVRObservable) {
  105080. try {
  105081. this.onExitingVRObservable.notifyObservers(this);
  105082. }
  105083. catch (err) {
  105084. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  105085. }
  105086. }
  105087. if (this._webVRpresenting) {
  105088. this._scene.getEngine().disableVR();
  105089. }
  105090. if (this._scene.activeCamera) {
  105091. this._position = this._scene.activeCamera.position.clone();
  105092. }
  105093. if (this._deviceOrientationCamera) {
  105094. this._deviceOrientationCamera.position = this._position;
  105095. this._scene.activeCamera = this._deviceOrientationCamera;
  105096. if (this._canvas) {
  105097. this._scene.activeCamera.attachControl(this._canvas);
  105098. }
  105099. }
  105100. else if (this._existingCamera) {
  105101. this._existingCamera.position = this._position;
  105102. this._scene.activeCamera = this._existingCamera;
  105103. }
  105104. this.updateButtonVisibility();
  105105. if (this._interactionsEnabled) {
  105106. this._scene.unregisterBeforeRender(this.beforeRender);
  105107. this._cameraGazer._gazeTracker.isVisible = false;
  105108. if (this._leftController) {
  105109. this._leftController._gazeTracker.isVisible = false;
  105110. }
  105111. if (this._rightController) {
  105112. this._rightController._gazeTracker.isVisible = false;
  105113. }
  105114. }
  105115. // resize to update width and height when exiting vr exits fullscreen
  105116. this._scene.getEngine().resize();
  105117. this._hasEnteredVR = false;
  105118. }
  105119. };
  105120. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  105121. /**
  105122. * The position of the vr experience helper.
  105123. */
  105124. get: function () {
  105125. return this._position;
  105126. },
  105127. /**
  105128. * Sets the position of the vr experience helper.
  105129. */
  105130. set: function (value) {
  105131. this._position = value;
  105132. if (this._scene.activeCamera) {
  105133. this._scene.activeCamera.position = value;
  105134. }
  105135. },
  105136. enumerable: true,
  105137. configurable: true
  105138. });
  105139. /**
  105140. * Enables controllers and user interactions such as selecting and object or clicking on an object.
  105141. */
  105142. VRExperienceHelper.prototype.enableInteractions = function () {
  105143. var _this = this;
  105144. if (!this._interactionsEnabled) {
  105145. this._interactionsRequested = true;
  105146. if (this._leftController) {
  105147. this._enableInteractionOnController(this._leftController);
  105148. }
  105149. if (this._rightController) {
  105150. this._enableInteractionOnController(this._rightController);
  105151. }
  105152. this.raySelectionPredicate = function (mesh) {
  105153. return mesh.isVisible && (mesh.isPickable || mesh.name === _this._floorMeshName);
  105154. };
  105155. this.meshSelectionPredicate = function (mesh) {
  105156. return true;
  105157. };
  105158. this._raySelectionPredicate = function (mesh) {
  105159. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  105160. && mesh.name.indexOf("teleportationTarget") === -1
  105161. && mesh.name.indexOf("torusTeleportation") === -1)) {
  105162. return _this.raySelectionPredicate(mesh);
  105163. }
  105164. return false;
  105165. };
  105166. this._interactionsEnabled = true;
  105167. }
  105168. };
  105169. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  105170. get: function () {
  105171. return !(this._leftController && this._leftController._activePointer) && !(this._rightController && this._rightController._activePointer);
  105172. },
  105173. enumerable: true,
  105174. configurable: true
  105175. });
  105176. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  105177. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  105178. if (this._floorMeshesCollection[i].id === mesh.id) {
  105179. return true;
  105180. }
  105181. }
  105182. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  105183. return true;
  105184. }
  105185. return false;
  105186. };
  105187. /**
  105188. * Adds a floor mesh to be used for teleportation.
  105189. * @param floorMesh the mesh to be used for teleportation.
  105190. */
  105191. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  105192. if (!this._floorMeshesCollection) {
  105193. return;
  105194. }
  105195. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  105196. return;
  105197. }
  105198. this._floorMeshesCollection.push(floorMesh);
  105199. };
  105200. /**
  105201. * Removes a floor mesh from being used for teleportation.
  105202. * @param floorMesh the mesh to be removed.
  105203. */
  105204. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  105205. if (!this._floorMeshesCollection) {
  105206. return;
  105207. }
  105208. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  105209. if (meshIndex !== -1) {
  105210. this._floorMeshesCollection.splice(meshIndex, 1);
  105211. }
  105212. };
  105213. /**
  105214. * Enables interactions and teleportation using the VR controllers and gaze.
  105215. * @param vrTeleportationOptions options to modify teleportation behavior.
  105216. */
  105217. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  105218. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  105219. if (!this._teleportationInitialized) {
  105220. this._teleportationRequested = true;
  105221. this.enableInteractions();
  105222. if (vrTeleportationOptions.floorMeshName) {
  105223. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  105224. }
  105225. if (vrTeleportationOptions.floorMeshes) {
  105226. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  105227. }
  105228. if (this._leftController != null) {
  105229. this._enableTeleportationOnController(this._leftController);
  105230. }
  105231. if (this._rightController != null) {
  105232. this._enableTeleportationOnController(this._rightController);
  105233. }
  105234. // Creates an image processing post process for the vignette not relying
  105235. // on the main scene configuration for image processing to reduce setup and spaces
  105236. // (gamma/linear) conflicts.
  105237. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  105238. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  105239. imageProcessingConfiguration.vignetteEnabled = true;
  105240. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  105241. this._webVRCamera.detachPostProcess(this._postProcessMove);
  105242. this._teleportationInitialized = true;
  105243. if (this._isDefaultTeleportationTarget) {
  105244. this._createTeleportationCircles();
  105245. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  105246. }
  105247. }
  105248. };
  105249. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  105250. var _this = this;
  105251. var controllerMesh = controller.webVRController.mesh;
  105252. if (controllerMesh) {
  105253. controller._interactionsEnabled = true;
  105254. controller._activatePointer();
  105255. if (this.webVROptions.laserToggle) {
  105256. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  105257. // Enabling / disabling laserPointer
  105258. if (_this._displayLaserPointer && stateObject.value === 1) {
  105259. if (controller._activePointer) {
  105260. controller._deactivatePointer();
  105261. }
  105262. else {
  105263. controller._activatePointer();
  105264. }
  105265. if (_this.displayGaze) {
  105266. controller._gazeTracker.isVisible = controller._activePointer;
  105267. }
  105268. }
  105269. });
  105270. }
  105271. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  105272. var gazer = controller;
  105273. if (_this._noControllerIsActive) {
  105274. gazer = _this._cameraGazer;
  105275. }
  105276. if (!gazer._pointerDownOnMeshAsked) {
  105277. if (stateObject.value > _this._padSensibilityUp) {
  105278. gazer._selectionPointerDown();
  105279. }
  105280. }
  105281. else if (stateObject.value < _this._padSensibilityDown) {
  105282. gazer._selectionPointerUp();
  105283. }
  105284. });
  105285. }
  105286. };
  105287. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  105288. // Dont teleport if another gaze already requested teleportation
  105289. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  105290. return;
  105291. }
  105292. if (!gazer._teleportationRequestInitiated) {
  105293. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  105294. gazer._activatePointer();
  105295. gazer._teleportationRequestInitiated = true;
  105296. }
  105297. }
  105298. else {
  105299. // Listening to the proper controller values changes to confirm teleportation
  105300. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  105301. if (this._teleportActive) {
  105302. this.teleportCamera(this._haloCenter);
  105303. }
  105304. gazer._teleportationRequestInitiated = false;
  105305. }
  105306. }
  105307. };
  105308. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  105309. // Only rotate when user is not currently selecting a teleportation location
  105310. if (gazer._teleportationRequestInitiated) {
  105311. return;
  105312. }
  105313. if (!gazer._rotationLeftAsked) {
  105314. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  105315. gazer._rotationLeftAsked = true;
  105316. if (this._rotationAllowed) {
  105317. this._rotateCamera(false);
  105318. }
  105319. }
  105320. }
  105321. else {
  105322. if (stateObject.x > -this._padSensibilityDown) {
  105323. gazer._rotationLeftAsked = false;
  105324. }
  105325. }
  105326. if (!gazer._rotationRightAsked) {
  105327. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  105328. gazer._rotationRightAsked = true;
  105329. if (this._rotationAllowed) {
  105330. this._rotateCamera(true);
  105331. }
  105332. }
  105333. }
  105334. else {
  105335. if (stateObject.x < this._padSensibilityDown) {
  105336. gazer._rotationRightAsked = false;
  105337. }
  105338. }
  105339. };
  105340. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  105341. // Only teleport backwards when user is not currently selecting a teleportation location
  105342. if (gazer._teleportationRequestInitiated) {
  105343. return;
  105344. }
  105345. // Teleport backwards
  105346. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  105347. if (!gazer._teleportationBackRequestInitiated) {
  105348. if (!this.currentVRCamera) {
  105349. return;
  105350. }
  105351. // Get rotation and position of the current camera
  105352. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  105353. var position = this.currentVRCamera.position;
  105354. // If the camera has device position, use that instead
  105355. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  105356. rotation = this.currentVRCamera.deviceRotationQuaternion;
  105357. position = this.currentVRCamera.devicePosition;
  105358. }
  105359. // Get matrix with only the y rotation of the device rotation
  105360. rotation.toEulerAnglesToRef(this._workingVector);
  105361. this._workingVector.z = 0;
  105362. this._workingVector.x = 0;
  105363. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  105364. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  105365. // Rotate backwards ray by device rotation to cast at the ground behind the user
  105366. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  105367. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  105368. var ray = new BABYLON.Ray(position, this._workingVector);
  105369. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105370. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  105371. this.teleportCamera(hit.pickedPoint);
  105372. }
  105373. gazer._teleportationBackRequestInitiated = true;
  105374. }
  105375. }
  105376. else {
  105377. gazer._teleportationBackRequestInitiated = false;
  105378. }
  105379. };
  105380. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  105381. var _this = this;
  105382. var controllerMesh = controller.webVRController.mesh;
  105383. if (controllerMesh) {
  105384. if (!controller._interactionsEnabled) {
  105385. this._enableInteractionOnController(controller);
  105386. }
  105387. controller._interactionsEnabled = true;
  105388. controller._teleportationEnabled = true;
  105389. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  105390. controller._dpadPressed = false;
  105391. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  105392. controller._dpadPressed = stateObject.pressed;
  105393. if (!controller._dpadPressed) {
  105394. controller._rotationLeftAsked = false;
  105395. controller._rotationRightAsked = false;
  105396. controller._teleportationBackRequestInitiated = false;
  105397. }
  105398. });
  105399. }
  105400. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  105401. if (_this.teleportationEnabled) {
  105402. _this._checkTeleportBackwards(stateObject, controller);
  105403. _this._checkTeleportWithRay(stateObject, controller);
  105404. }
  105405. _this._checkRotate(stateObject, controller);
  105406. });
  105407. }
  105408. };
  105409. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  105410. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  105411. this._teleportationTarget.isPickable = false;
  105412. var length = 512;
  105413. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  105414. dynamicTexture.hasAlpha = true;
  105415. var context = dynamicTexture.getContext();
  105416. var centerX = length / 2;
  105417. var centerY = length / 2;
  105418. var radius = 200;
  105419. context.beginPath();
  105420. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  105421. context.fillStyle = this._teleportationFillColor;
  105422. context.fill();
  105423. context.lineWidth = 10;
  105424. context.strokeStyle = this._teleportationBorderColor;
  105425. context.stroke();
  105426. context.closePath();
  105427. dynamicTexture.update();
  105428. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  105429. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  105430. this._teleportationTarget.material = teleportationCircleMaterial;
  105431. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  105432. torus.isPickable = false;
  105433. torus.parent = this._teleportationTarget;
  105434. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  105435. var keys = [];
  105436. keys.push({
  105437. frame: 0,
  105438. value: 0
  105439. });
  105440. keys.push({
  105441. frame: 30,
  105442. value: 0.4
  105443. });
  105444. keys.push({
  105445. frame: 60,
  105446. value: 0
  105447. });
  105448. animationInnerCircle.setKeys(keys);
  105449. var easingFunction = new BABYLON.SineEase();
  105450. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  105451. animationInnerCircle.setEasingFunction(easingFunction);
  105452. torus.animations = [];
  105453. torus.animations.push(animationInnerCircle);
  105454. this._scene.beginAnimation(torus, 0, 60, true);
  105455. this._hideTeleportationTarget();
  105456. };
  105457. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  105458. this._teleportActive = true;
  105459. if (this._teleportationInitialized) {
  105460. this._teleportationTarget.isVisible = true;
  105461. if (this._isDefaultTeleportationTarget) {
  105462. this._teleportationTarget.getChildren()[0].isVisible = true;
  105463. }
  105464. }
  105465. };
  105466. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  105467. this._teleportActive = false;
  105468. if (this._teleportationInitialized) {
  105469. this._teleportationTarget.isVisible = false;
  105470. if (this._isDefaultTeleportationTarget) {
  105471. this._teleportationTarget.getChildren()[0].isVisible = false;
  105472. }
  105473. }
  105474. };
  105475. VRExperienceHelper.prototype._rotateCamera = function (right) {
  105476. var _this = this;
  105477. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105478. return;
  105479. }
  105480. if (right) {
  105481. this._rotationAngle++;
  105482. }
  105483. else {
  105484. this._rotationAngle--;
  105485. }
  105486. this.currentVRCamera.animations = [];
  105487. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  105488. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105489. var animationRotationKeys = [];
  105490. animationRotationKeys.push({
  105491. frame: 0,
  105492. value: this.currentVRCamera.rotationQuaternion
  105493. });
  105494. animationRotationKeys.push({
  105495. frame: 6,
  105496. value: target
  105497. });
  105498. animationRotation.setKeys(animationRotationKeys);
  105499. animationRotation.setEasingFunction(this._circleEase);
  105500. this.currentVRCamera.animations.push(animationRotation);
  105501. this._postProcessMove.animations = [];
  105502. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105503. var vignetteWeightKeys = [];
  105504. vignetteWeightKeys.push({
  105505. frame: 0,
  105506. value: 0
  105507. });
  105508. vignetteWeightKeys.push({
  105509. frame: 3,
  105510. value: 4
  105511. });
  105512. vignetteWeightKeys.push({
  105513. frame: 6,
  105514. value: 0
  105515. });
  105516. animationPP.setKeys(vignetteWeightKeys);
  105517. animationPP.setEasingFunction(this._circleEase);
  105518. this._postProcessMove.animations.push(animationPP);
  105519. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105520. var vignetteStretchKeys = [];
  105521. vignetteStretchKeys.push({
  105522. frame: 0,
  105523. value: 0
  105524. });
  105525. vignetteStretchKeys.push({
  105526. frame: 3,
  105527. value: 10
  105528. });
  105529. vignetteStretchKeys.push({
  105530. frame: 6,
  105531. value: 0
  105532. });
  105533. animationPP2.setKeys(vignetteStretchKeys);
  105534. animationPP2.setEasingFunction(this._circleEase);
  105535. this._postProcessMove.animations.push(animationPP2);
  105536. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105537. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105538. this._postProcessMove.samples = 4;
  105539. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105540. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  105541. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105542. });
  105543. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  105544. };
  105545. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  105546. if (hit.pickedPoint) {
  105547. if (gazer._teleportationRequestInitiated) {
  105548. this._displayTeleportationTarget();
  105549. this._haloCenter.copyFrom(hit.pickedPoint);
  105550. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  105551. }
  105552. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  105553. if (pickNormal) {
  105554. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105555. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105556. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  105557. }
  105558. this._teleportationTarget.position.y += 0.1;
  105559. }
  105560. };
  105561. /**
  105562. * Teleports the users feet to the desired location
  105563. * @param location The location where the user's feet should be placed
  105564. */
  105565. VRExperienceHelper.prototype.teleportCamera = function (location) {
  105566. var _this = this;
  105567. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105568. return;
  105569. }
  105570. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  105571. // offset of the headset from the anchor.
  105572. if (this.webVRCamera.leftCamera) {
  105573. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  105574. this._workingVector.subtractInPlace(this.webVRCamera.position);
  105575. location.subtractToRef(this._workingVector, this._workingVector);
  105576. }
  105577. else {
  105578. this._workingVector.copyFrom(location);
  105579. }
  105580. // Add height to account for user's height offset
  105581. if (this.isInVRMode) {
  105582. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  105583. }
  105584. else {
  105585. this._workingVector.y += this._defaultHeight;
  105586. }
  105587. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  105588. // Create animation from the camera's position to the new location
  105589. this.currentVRCamera.animations = [];
  105590. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105591. var animationCameraTeleportationKeys = [{
  105592. frame: 0,
  105593. value: this.currentVRCamera.position
  105594. },
  105595. {
  105596. frame: 11,
  105597. value: this._workingVector
  105598. }
  105599. ];
  105600. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  105601. animationCameraTeleportation.setEasingFunction(this._circleEase);
  105602. this.currentVRCamera.animations.push(animationCameraTeleportation);
  105603. this._postProcessMove.animations = [];
  105604. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105605. var vignetteWeightKeys = [];
  105606. vignetteWeightKeys.push({
  105607. frame: 0,
  105608. value: 0
  105609. });
  105610. vignetteWeightKeys.push({
  105611. frame: 5,
  105612. value: 8
  105613. });
  105614. vignetteWeightKeys.push({
  105615. frame: 11,
  105616. value: 0
  105617. });
  105618. animationPP.setKeys(vignetteWeightKeys);
  105619. this._postProcessMove.animations.push(animationPP);
  105620. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  105621. var vignetteStretchKeys = [];
  105622. vignetteStretchKeys.push({
  105623. frame: 0,
  105624. value: 0
  105625. });
  105626. vignetteStretchKeys.push({
  105627. frame: 5,
  105628. value: 10
  105629. });
  105630. vignetteStretchKeys.push({
  105631. frame: 11,
  105632. value: 0
  105633. });
  105634. animationPP2.setKeys(vignetteStretchKeys);
  105635. this._postProcessMove.animations.push(animationPP2);
  105636. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  105637. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  105638. this._webVRCamera.attachPostProcess(this._postProcessMove);
  105639. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  105640. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  105641. });
  105642. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  105643. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  105644. });
  105645. this._hideTeleportationTarget();
  105646. };
  105647. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  105648. if (normal) {
  105649. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  105650. if (angle < Math.PI / 2) {
  105651. normal.scaleInPlace(-1);
  105652. }
  105653. }
  105654. return normal;
  105655. };
  105656. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  105657. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  105658. return;
  105659. }
  105660. var ray = gazer._getForwardRay(this._rayLength);
  105661. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  105662. if (hit) {
  105663. // Populate the contrllers mesh that can be used for drag/drop
  105664. if (gazer._laserPointer) {
  105665. hit.originMesh = gazer._laserPointer.parent;
  105666. }
  105667. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  105668. }
  105669. gazer._currentHit = hit;
  105670. // Moving the gazeTracker on the mesh face targetted
  105671. if (hit && hit.pickedPoint) {
  105672. if (this._displayGaze) {
  105673. var multiplier = 1;
  105674. gazer._gazeTracker.isVisible = true;
  105675. if (gazer._isActionableMesh) {
  105676. multiplier = 3;
  105677. }
  105678. if (this.updateGazeTrackerScale) {
  105679. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  105680. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  105681. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  105682. }
  105683. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  105684. // To avoid z-fighting
  105685. var deltaFighting = 0.002;
  105686. if (pickNormal) {
  105687. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  105688. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  105689. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  105690. }
  105691. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  105692. if (gazer._gazeTracker.position.x < 0) {
  105693. gazer._gazeTracker.position.x += deltaFighting;
  105694. }
  105695. else {
  105696. gazer._gazeTracker.position.x -= deltaFighting;
  105697. }
  105698. if (gazer._gazeTracker.position.y < 0) {
  105699. gazer._gazeTracker.position.y += deltaFighting;
  105700. }
  105701. else {
  105702. gazer._gazeTracker.position.y -= deltaFighting;
  105703. }
  105704. if (gazer._gazeTracker.position.z < 0) {
  105705. gazer._gazeTracker.position.z += deltaFighting;
  105706. }
  105707. else {
  105708. gazer._gazeTracker.position.z -= deltaFighting;
  105709. }
  105710. }
  105711. // Changing the size of the laser pointer based on the distance from the targetted point
  105712. gazer._updatePointerDistance(hit.distance);
  105713. }
  105714. else {
  105715. gazer._updatePointerDistance();
  105716. gazer._gazeTracker.isVisible = false;
  105717. }
  105718. if (hit && hit.pickedMesh) {
  105719. // The object selected is the floor, we're in a teleportation scenario
  105720. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  105721. // Moving the teleportation area to this targetted point
  105722. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  105723. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  105724. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105725. }
  105726. gazer._currentMeshSelected = null;
  105727. if (gazer._teleportationRequestInitiated) {
  105728. this._moveTeleportationSelectorTo(hit, gazer, ray);
  105729. }
  105730. return;
  105731. }
  105732. // If not, we're in a selection scenario
  105733. //this._teleportationAllowed = false;
  105734. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  105735. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  105736. this.onNewMeshPicked.notifyObservers(hit);
  105737. gazer._currentMeshSelected = hit.pickedMesh;
  105738. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  105739. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  105740. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  105741. gazer._isActionableMesh = true;
  105742. }
  105743. else {
  105744. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105745. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105746. gazer._isActionableMesh = false;
  105747. }
  105748. try {
  105749. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  105750. }
  105751. catch (err) {
  105752. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  105753. }
  105754. }
  105755. else {
  105756. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105757. gazer._currentMeshSelected = null;
  105758. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105759. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105760. }
  105761. }
  105762. }
  105763. else {
  105764. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  105765. gazer._currentMeshSelected = null;
  105766. //this._teleportationAllowed = false;
  105767. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105768. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  105769. }
  105770. };
  105771. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  105772. if (mesh) {
  105773. this.onSelectedMeshUnselected.notifyObservers(mesh);
  105774. }
  105775. };
  105776. /**
  105777. * Sets the color of the laser ray from the vr controllers.
  105778. * @param color new color for the ray.
  105779. */
  105780. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  105781. if (this._leftController) {
  105782. this._leftController._setLaserPointerColor(color);
  105783. }
  105784. if (this._rightController) {
  105785. this._rightController._setLaserPointerColor(color);
  105786. }
  105787. };
  105788. /**
  105789. * Sets the color of the ray from the vr headsets gaze.
  105790. * @param color new color for the ray.
  105791. */
  105792. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  105793. if (!this._cameraGazer._gazeTracker.material) {
  105794. return;
  105795. }
  105796. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  105797. if (this._leftController) {
  105798. this._leftController._gazeTracker.material.emissiveColor = color;
  105799. }
  105800. if (this._rightController) {
  105801. this._rightController._gazeTracker.material.emissiveColor = color;
  105802. }
  105803. };
  105804. /**
  105805. * Exits VR and disposes of the vr experience helper
  105806. */
  105807. VRExperienceHelper.prototype.dispose = function () {
  105808. if (this.isInVRMode) {
  105809. this.exitVR();
  105810. }
  105811. if (this._postProcessMove) {
  105812. this._postProcessMove.dispose();
  105813. }
  105814. if (this._webVRCamera) {
  105815. this._webVRCamera.dispose();
  105816. }
  105817. if (this._vrDeviceOrientationCamera) {
  105818. this._vrDeviceOrientationCamera.dispose();
  105819. }
  105820. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  105821. document.body.removeChild(this._btnVR);
  105822. }
  105823. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  105824. this._deviceOrientationCamera.dispose();
  105825. }
  105826. if (this._cameraGazer) {
  105827. this._cameraGazer.dispose();
  105828. }
  105829. if (this._leftController) {
  105830. this._leftController.dispose();
  105831. }
  105832. if (this._rightController) {
  105833. this._rightController.dispose();
  105834. }
  105835. if (this._teleportationTarget) {
  105836. this._teleportationTarget.dispose();
  105837. }
  105838. this._floorMeshesCollection = [];
  105839. document.removeEventListener("keydown", this._onKeyDown);
  105840. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105841. window.removeEventListener("resize", this._onResize);
  105842. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  105843. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  105844. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  105845. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  105846. document.onmsfullscreenchange = null;
  105847. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  105848. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  105849. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  105850. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  105851. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  105852. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  105853. this._scene.unregisterBeforeRender(this.beforeRender);
  105854. };
  105855. /**
  105856. * Gets the name of the VRExperienceHelper class
  105857. * @returns "VRExperienceHelper"
  105858. */
  105859. VRExperienceHelper.prototype.getClassName = function () {
  105860. return "VRExperienceHelper";
  105861. };
  105862. return VRExperienceHelper;
  105863. }());
  105864. BABYLON.VRExperienceHelper = VRExperienceHelper;
  105865. })(BABYLON || (BABYLON = {}));
  105866. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  105867. // Mainly based on these 2 articles :
  105868. // 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
  105869. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  105870. var BABYLON;
  105871. (function (BABYLON) {
  105872. /**
  105873. * Defines the potential axis of a Joystick
  105874. */
  105875. var JoystickAxis;
  105876. (function (JoystickAxis) {
  105877. /** X axis */
  105878. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  105879. /** Y axis */
  105880. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  105881. /** Z axis */
  105882. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  105883. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  105884. /**
  105885. * Class used to define virtual joystick (used in touch mode)
  105886. */
  105887. var VirtualJoystick = /** @class */ (function () {
  105888. /**
  105889. * Creates a new virtual joystick
  105890. * @param leftJoystick defines that the joystick is for left hand (false by default)
  105891. */
  105892. function VirtualJoystick(leftJoystick) {
  105893. var _this = this;
  105894. if (leftJoystick) {
  105895. this._leftJoystick = true;
  105896. }
  105897. else {
  105898. this._leftJoystick = false;
  105899. }
  105900. VirtualJoystick._globalJoystickIndex++;
  105901. // By default left & right arrow keys are moving the X
  105902. // and up & down keys are moving the Y
  105903. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  105904. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  105905. this.reverseLeftRight = false;
  105906. this.reverseUpDown = false;
  105907. // collections of pointers
  105908. this._touches = new BABYLON.StringDictionary();
  105909. this.deltaPosition = BABYLON.Vector3.Zero();
  105910. this._joystickSensibility = 25;
  105911. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  105912. this._onResize = function (evt) {
  105913. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  105914. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  105915. if (VirtualJoystick.vjCanvas) {
  105916. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  105917. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  105918. }
  105919. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  105920. };
  105921. // injecting a canvas element on top of the canvas 3D game
  105922. if (!VirtualJoystick.vjCanvas) {
  105923. window.addEventListener("resize", this._onResize, false);
  105924. VirtualJoystick.vjCanvas = document.createElement("canvas");
  105925. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  105926. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  105927. VirtualJoystick.vjCanvas.width = window.innerWidth;
  105928. VirtualJoystick.vjCanvas.height = window.innerHeight;
  105929. VirtualJoystick.vjCanvas.style.width = "100%";
  105930. VirtualJoystick.vjCanvas.style.height = "100%";
  105931. VirtualJoystick.vjCanvas.style.position = "absolute";
  105932. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  105933. VirtualJoystick.vjCanvas.style.top = "0px";
  105934. VirtualJoystick.vjCanvas.style.left = "0px";
  105935. VirtualJoystick.vjCanvas.style.zIndex = "5";
  105936. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  105937. // Support for jQuery PEP polyfill
  105938. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  105939. var context = VirtualJoystick.vjCanvas.getContext('2d');
  105940. if (!context) {
  105941. throw new Error("Unable to create canvas for virtual joystick");
  105942. }
  105943. VirtualJoystick.vjCanvasContext = context;
  105944. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  105945. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  105946. document.body.appendChild(VirtualJoystick.vjCanvas);
  105947. }
  105948. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  105949. this.pressed = false;
  105950. // default joystick color
  105951. this._joystickColor = "cyan";
  105952. this._joystickPointerID = -1;
  105953. // current joystick position
  105954. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  105955. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  105956. // origin joystick position
  105957. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  105958. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  105959. this._onPointerDownHandlerRef = function (evt) {
  105960. _this._onPointerDown(evt);
  105961. };
  105962. this._onPointerMoveHandlerRef = function (evt) {
  105963. _this._onPointerMove(evt);
  105964. };
  105965. this._onPointerUpHandlerRef = function (evt) {
  105966. _this._onPointerUp(evt);
  105967. };
  105968. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  105969. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  105970. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  105971. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  105972. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  105973. evt.preventDefault(); // Disables system menu
  105974. }, false);
  105975. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  105976. }
  105977. /**
  105978. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  105979. * @param newJoystickSensibility defines the new sensibility
  105980. */
  105981. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  105982. this._joystickSensibility = newJoystickSensibility;
  105983. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  105984. };
  105985. VirtualJoystick.prototype._onPointerDown = function (e) {
  105986. var positionOnScreenCondition;
  105987. e.preventDefault();
  105988. if (this._leftJoystick === true) {
  105989. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  105990. }
  105991. else {
  105992. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  105993. }
  105994. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  105995. // First contact will be dedicated to the virtual joystick
  105996. this._joystickPointerID = e.pointerId;
  105997. this._joystickPointerStartPos.x = e.clientX;
  105998. this._joystickPointerStartPos.y = e.clientY;
  105999. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  106000. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  106001. this._deltaJoystickVector.x = 0;
  106002. this._deltaJoystickVector.y = 0;
  106003. this.pressed = true;
  106004. this._touches.add(e.pointerId.toString(), e);
  106005. }
  106006. else {
  106007. // You can only trigger the action buttons with a joystick declared
  106008. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  106009. this._action();
  106010. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  106011. }
  106012. }
  106013. };
  106014. VirtualJoystick.prototype._onPointerMove = function (e) {
  106015. // If the current pointer is the one associated to the joystick (first touch contact)
  106016. if (this._joystickPointerID == e.pointerId) {
  106017. this._joystickPointerPos.x = e.clientX;
  106018. this._joystickPointerPos.y = e.clientY;
  106019. this._deltaJoystickVector = this._joystickPointerPos.clone();
  106020. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  106021. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  106022. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  106023. switch (this._axisTargetedByLeftAndRight) {
  106024. case JoystickAxis.X:
  106025. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  106026. break;
  106027. case JoystickAxis.Y:
  106028. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  106029. break;
  106030. case JoystickAxis.Z:
  106031. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  106032. break;
  106033. }
  106034. var directionUpDown = this.reverseUpDown ? 1 : -1;
  106035. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  106036. switch (this._axisTargetedByUpAndDown) {
  106037. case JoystickAxis.X:
  106038. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  106039. break;
  106040. case JoystickAxis.Y:
  106041. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  106042. break;
  106043. case JoystickAxis.Z:
  106044. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  106045. break;
  106046. }
  106047. }
  106048. else {
  106049. var data = this._touches.get(e.pointerId.toString());
  106050. if (data) {
  106051. data.x = e.clientX;
  106052. data.y = e.clientY;
  106053. }
  106054. }
  106055. };
  106056. VirtualJoystick.prototype._onPointerUp = function (e) {
  106057. if (this._joystickPointerID == e.pointerId) {
  106058. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  106059. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  106060. this._joystickPointerID = -1;
  106061. this.pressed = false;
  106062. }
  106063. else {
  106064. var touch = this._touches.get(e.pointerId.toString());
  106065. if (touch) {
  106066. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106067. }
  106068. }
  106069. this._deltaJoystickVector.x = 0;
  106070. this._deltaJoystickVector.y = 0;
  106071. this._touches.remove(e.pointerId.toString());
  106072. };
  106073. /**
  106074. * Change the color of the virtual joystick
  106075. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  106076. */
  106077. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  106078. this._joystickColor = newColor;
  106079. };
  106080. /**
  106081. * Defines a callback to call when the joystick is touched
  106082. * @param action defines the callback
  106083. */
  106084. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  106085. this._action = action;
  106086. };
  106087. /**
  106088. * Defines which axis you'd like to control for left & right
  106089. * @param axis defines the axis to use
  106090. */
  106091. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  106092. switch (axis) {
  106093. case JoystickAxis.X:
  106094. case JoystickAxis.Y:
  106095. case JoystickAxis.Z:
  106096. this._axisTargetedByLeftAndRight = axis;
  106097. break;
  106098. default:
  106099. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  106100. break;
  106101. }
  106102. };
  106103. /**
  106104. * Defines which axis you'd like to control for up & down
  106105. * @param axis defines the axis to use
  106106. */
  106107. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  106108. switch (axis) {
  106109. case JoystickAxis.X:
  106110. case JoystickAxis.Y:
  106111. case JoystickAxis.Z:
  106112. this._axisTargetedByUpAndDown = axis;
  106113. break;
  106114. default:
  106115. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  106116. break;
  106117. }
  106118. };
  106119. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  106120. var _this = this;
  106121. if (this.pressed) {
  106122. this._touches.forEach(function (key, touch) {
  106123. if (touch.pointerId === _this._joystickPointerID) {
  106124. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  106125. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  106126. VirtualJoystick.vjCanvasContext.beginPath();
  106127. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106128. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106129. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  106130. VirtualJoystick.vjCanvasContext.stroke();
  106131. VirtualJoystick.vjCanvasContext.closePath();
  106132. VirtualJoystick.vjCanvasContext.beginPath();
  106133. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106134. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  106135. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  106136. VirtualJoystick.vjCanvasContext.stroke();
  106137. VirtualJoystick.vjCanvasContext.closePath();
  106138. VirtualJoystick.vjCanvasContext.beginPath();
  106139. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  106140. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  106141. VirtualJoystick.vjCanvasContext.stroke();
  106142. VirtualJoystick.vjCanvasContext.closePath();
  106143. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  106144. }
  106145. else {
  106146. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  106147. VirtualJoystick.vjCanvasContext.beginPath();
  106148. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  106149. VirtualJoystick.vjCanvasContext.beginPath();
  106150. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  106151. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  106152. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  106153. VirtualJoystick.vjCanvasContext.stroke();
  106154. VirtualJoystick.vjCanvasContext.closePath();
  106155. touch.prevX = touch.x;
  106156. touch.prevY = touch.y;
  106157. }
  106158. ;
  106159. });
  106160. }
  106161. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  106162. };
  106163. /**
  106164. * Release internal HTML canvas
  106165. */
  106166. VirtualJoystick.prototype.releaseCanvas = function () {
  106167. if (VirtualJoystick.vjCanvas) {
  106168. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  106169. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  106170. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  106171. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  106172. window.removeEventListener("resize", this._onResize);
  106173. document.body.removeChild(VirtualJoystick.vjCanvas);
  106174. VirtualJoystick.vjCanvas = null;
  106175. }
  106176. };
  106177. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  106178. VirtualJoystick._globalJoystickIndex = 0;
  106179. return VirtualJoystick;
  106180. }());
  106181. BABYLON.VirtualJoystick = VirtualJoystick;
  106182. })(BABYLON || (BABYLON = {}));
  106183. //# sourceMappingURL=babylon.virtualJoystick.js.map
  106184. var BABYLON;
  106185. (function (BABYLON) {
  106186. BABYLON.Node.AddNodeConstructor("VirtualJoysticksCamera", function (name, scene) {
  106187. return function () { return new VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  106188. });
  106189. /**
  106190. * This represents a free type of camera. It can be usefull in First Person Shooter game for instance.
  106191. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106192. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106193. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106194. */
  106195. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  106196. __extends(VirtualJoysticksCamera, _super);
  106197. /**
  106198. * Intantiates a VirtualJoysticksCamera. It can be usefull in First Person Shooter game for instance.
  106199. * It is identical to the Free Camera and simply adds by default a virtual joystick.
  106200. * Virtual Joysticks are on-screen 2D graphics that are used to control the camera or other scene items.
  106201. * @see http://doc.babylonjs.com/features/cameras#virtual-joysticks-camera
  106202. * @param name Define the name of the camera in the scene
  106203. * @param position Define the start position of the camera in the scene
  106204. * @param scene Define the scene the camera belongs to
  106205. */
  106206. function VirtualJoysticksCamera(name, position, scene) {
  106207. var _this = _super.call(this, name, position, scene) || this;
  106208. _this.inputs.addVirtualJoystick();
  106209. return _this;
  106210. }
  106211. /**
  106212. * Gets the current object class name.
  106213. * @return the class name
  106214. */
  106215. VirtualJoysticksCamera.prototype.getClassName = function () {
  106216. return "VirtualJoysticksCamera";
  106217. };
  106218. return VirtualJoysticksCamera;
  106219. }(BABYLON.FreeCamera));
  106220. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  106221. })(BABYLON || (BABYLON = {}));
  106222. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  106223. var BABYLON;
  106224. (function (BABYLON) {
  106225. /**
  106226. * Manage the Virtual Joystick inputs to control the movement of a free camera.
  106227. * @see http://doc.babylonjs.com/how_to/customizing_camera_inputs
  106228. */
  106229. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  106230. function FreeCameraVirtualJoystickInput() {
  106231. }
  106232. /**
  106233. * Gets the left stick of the virtual joystick.
  106234. * @returns The virtual Joystick
  106235. */
  106236. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  106237. return this._leftjoystick;
  106238. };
  106239. /**
  106240. * Gets the right stick of the virtual joystick.
  106241. * @returns The virtual Joystick
  106242. */
  106243. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  106244. return this._rightjoystick;
  106245. };
  106246. /**
  106247. * Update the current camera state depending on the inputs that have been used this frame.
  106248. * This is a dynamically created lambda to avoid the performance penalty of looping for inputs in the render loop.
  106249. */
  106250. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  106251. if (this._leftjoystick) {
  106252. var camera = this.camera;
  106253. var speed = camera._computeLocalCameraSpeed() * 50;
  106254. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  106255. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  106256. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  106257. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  106258. if (!this._leftjoystick.pressed) {
  106259. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  106260. }
  106261. if (!this._rightjoystick.pressed) {
  106262. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  106263. }
  106264. }
  106265. };
  106266. /**
  106267. * Attach the input controls to a specific dom element to get the input from.
  106268. * @param element Defines the element the controls should be listened from
  106269. * @param noPreventDefault Defines whether event caught by the controls should call preventdefault() (https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault)
  106270. */
  106271. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  106272. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  106273. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  106274. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  106275. this._leftjoystick.setJoystickSensibility(0.15);
  106276. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  106277. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  106278. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  106279. this._rightjoystick.reverseUpDown = true;
  106280. this._rightjoystick.setJoystickSensibility(0.05);
  106281. this._rightjoystick.setJoystickColor("yellow");
  106282. };
  106283. /**
  106284. * Detach the current controls from the specified dom element.
  106285. * @param element Defines the element to stop listening the inputs from
  106286. */
  106287. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  106288. this._leftjoystick.releaseCanvas();
  106289. this._rightjoystick.releaseCanvas();
  106290. };
  106291. /**
  106292. * Gets the class name of the current intput.
  106293. * @returns the class name
  106294. */
  106295. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  106296. return "FreeCameraVirtualJoystickInput";
  106297. };
  106298. /**
  106299. * Get the friendly name associated with the input class.
  106300. * @returns the input friendly name
  106301. */
  106302. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  106303. return "virtualJoystick";
  106304. };
  106305. return FreeCameraVirtualJoystickInput;
  106306. }());
  106307. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  106308. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  106309. })(BABYLON || (BABYLON = {}));
  106310. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  106311. var BABYLON;
  106312. (function (BABYLON) {
  106313. /**
  106314. * Class used to specify simplification options
  106315. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106316. */
  106317. var SimplificationSettings = /** @class */ (function () {
  106318. /**
  106319. * Creates a SimplificationSettings
  106320. * @param quality expected quality
  106321. * @param distance distance when this optimized version should be used
  106322. * @param optimizeMesh already optimized mesh
  106323. */
  106324. function SimplificationSettings(
  106325. /** expected quality */
  106326. quality,
  106327. /** distance when this optimized version should be used */
  106328. distance,
  106329. /** already optimized mesh */
  106330. optimizeMesh) {
  106331. this.quality = quality;
  106332. this.distance = distance;
  106333. this.optimizeMesh = optimizeMesh;
  106334. }
  106335. return SimplificationSettings;
  106336. }());
  106337. BABYLON.SimplificationSettings = SimplificationSettings;
  106338. /**
  106339. * Queue used to order the simplification tasks
  106340. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106341. */
  106342. var SimplificationQueue = /** @class */ (function () {
  106343. /**
  106344. * Creates a new queue
  106345. */
  106346. function SimplificationQueue() {
  106347. this.running = false;
  106348. this._simplificationArray = [];
  106349. }
  106350. /**
  106351. * Adds a new simplification task
  106352. * @param task defines a task to add
  106353. */
  106354. SimplificationQueue.prototype.addTask = function (task) {
  106355. this._simplificationArray.push(task);
  106356. };
  106357. /**
  106358. * Execute next task
  106359. */
  106360. SimplificationQueue.prototype.executeNext = function () {
  106361. var task = this._simplificationArray.pop();
  106362. if (task) {
  106363. this.running = true;
  106364. this.runSimplification(task);
  106365. }
  106366. else {
  106367. this.running = false;
  106368. }
  106369. };
  106370. /**
  106371. * Execute a simplification task
  106372. * @param task defines the task to run
  106373. */
  106374. SimplificationQueue.prototype.runSimplification = function (task) {
  106375. var _this = this;
  106376. if (task.parallelProcessing) {
  106377. //parallel simplifier
  106378. task.settings.forEach(function (setting) {
  106379. var simplifier = _this.getSimplifier(task);
  106380. simplifier.simplify(setting, function (newMesh) {
  106381. task.mesh.addLODLevel(setting.distance, newMesh);
  106382. newMesh.isVisible = true;
  106383. //check if it is the last
  106384. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  106385. //all done, run the success callback.
  106386. task.successCallback();
  106387. }
  106388. _this.executeNext();
  106389. });
  106390. });
  106391. }
  106392. else {
  106393. //single simplifier.
  106394. var simplifier = this.getSimplifier(task);
  106395. var runDecimation = function (setting, callback) {
  106396. simplifier.simplify(setting, function (newMesh) {
  106397. task.mesh.addLODLevel(setting.distance, newMesh);
  106398. newMesh.isVisible = true;
  106399. //run the next quality level
  106400. callback();
  106401. });
  106402. };
  106403. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  106404. runDecimation(task.settings[loop.index], function () {
  106405. loop.executeNext();
  106406. });
  106407. }, function () {
  106408. //execution ended, run the success callback.
  106409. if (task.successCallback) {
  106410. task.successCallback();
  106411. }
  106412. _this.executeNext();
  106413. });
  106414. }
  106415. };
  106416. SimplificationQueue.prototype.getSimplifier = function (task) {
  106417. switch (task.simplificationType) {
  106418. case SimplificationType.QUADRATIC:
  106419. default:
  106420. return new QuadraticErrorSimplification(task.mesh);
  106421. }
  106422. };
  106423. return SimplificationQueue;
  106424. }());
  106425. BABYLON.SimplificationQueue = SimplificationQueue;
  106426. /**
  106427. * The implemented types of simplification
  106428. * At the moment only Quadratic Error Decimation is implemented
  106429. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106430. */
  106431. var SimplificationType;
  106432. (function (SimplificationType) {
  106433. /** Quadratic error decimation */
  106434. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  106435. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  106436. var DecimationTriangle = /** @class */ (function () {
  106437. function DecimationTriangle(vertices) {
  106438. this.vertices = vertices;
  106439. this.error = new Array(4);
  106440. this.deleted = false;
  106441. this.isDirty = false;
  106442. this.deletePending = false;
  106443. this.borderFactor = 0;
  106444. }
  106445. return DecimationTriangle;
  106446. }());
  106447. var DecimationVertex = /** @class */ (function () {
  106448. function DecimationVertex(position, id) {
  106449. this.position = position;
  106450. this.id = id;
  106451. this.isBorder = true;
  106452. this.q = new QuadraticMatrix();
  106453. this.triangleCount = 0;
  106454. this.triangleStart = 0;
  106455. this.originalOffsets = [];
  106456. }
  106457. DecimationVertex.prototype.updatePosition = function (newPosition) {
  106458. this.position.copyFrom(newPosition);
  106459. };
  106460. return DecimationVertex;
  106461. }());
  106462. var QuadraticMatrix = /** @class */ (function () {
  106463. function QuadraticMatrix(data) {
  106464. this.data = new Array(10);
  106465. for (var i = 0; i < 10; ++i) {
  106466. if (data && data[i]) {
  106467. this.data[i] = data[i];
  106468. }
  106469. else {
  106470. this.data[i] = 0;
  106471. }
  106472. }
  106473. }
  106474. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  106475. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  106476. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  106477. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  106478. return det;
  106479. };
  106480. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  106481. for (var i = 0; i < 10; ++i) {
  106482. this.data[i] += matrix.data[i];
  106483. }
  106484. };
  106485. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  106486. for (var i = 0; i < 10; ++i) {
  106487. this.data[i] += data[i];
  106488. }
  106489. };
  106490. QuadraticMatrix.prototype.add = function (matrix) {
  106491. var m = new QuadraticMatrix();
  106492. for (var i = 0; i < 10; ++i) {
  106493. m.data[i] = this.data[i] + matrix.data[i];
  106494. }
  106495. return m;
  106496. };
  106497. QuadraticMatrix.FromData = function (a, b, c, d) {
  106498. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  106499. };
  106500. //returning an array to avoid garbage collection
  106501. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  106502. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  106503. };
  106504. return QuadraticMatrix;
  106505. }());
  106506. var Reference = /** @class */ (function () {
  106507. function Reference(vertexId, triangleId) {
  106508. this.vertexId = vertexId;
  106509. this.triangleId = triangleId;
  106510. }
  106511. return Reference;
  106512. }());
  106513. /**
  106514. * An implementation of the Quadratic Error simplification algorithm.
  106515. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  106516. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  106517. * @author RaananW
  106518. * @see http://doc.babylonjs.com/how_to/in-browser_mesh_simplification
  106519. */
  106520. var QuadraticErrorSimplification = /** @class */ (function () {
  106521. function QuadraticErrorSimplification(_mesh) {
  106522. this._mesh = _mesh;
  106523. this.syncIterations = 5000;
  106524. this.aggressiveness = 7;
  106525. this.decimationIterations = 100;
  106526. this.boundingBoxEpsilon = BABYLON.Epsilon;
  106527. }
  106528. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  106529. var _this = this;
  106530. this.initDecimatedMesh();
  106531. //iterating through the submeshes array, one after the other.
  106532. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  106533. _this.initWithMesh(loop.index, function () {
  106534. _this.runDecimation(settings, loop.index, function () {
  106535. loop.executeNext();
  106536. });
  106537. }, settings.optimizeMesh);
  106538. }, function () {
  106539. setTimeout(function () {
  106540. successCallback(_this._reconstructedMesh);
  106541. }, 0);
  106542. });
  106543. };
  106544. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  106545. var _this = this;
  106546. var targetCount = ~~(this.triangles.length * settings.quality);
  106547. var deletedTriangles = 0;
  106548. var triangleCount = this.triangles.length;
  106549. var iterationFunction = function (iteration, callback) {
  106550. setTimeout(function () {
  106551. if (iteration % 5 === 0) {
  106552. _this.updateMesh(iteration === 0);
  106553. }
  106554. for (var i = 0; i < _this.triangles.length; ++i) {
  106555. _this.triangles[i].isDirty = false;
  106556. }
  106557. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  106558. var trianglesIterator = function (i) {
  106559. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  106560. var t = _this.triangles[tIdx];
  106561. if (!t)
  106562. return;
  106563. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  106564. return;
  106565. }
  106566. for (var j = 0; j < 3; ++j) {
  106567. if (t.error[j] < threshold) {
  106568. var deleted0 = [];
  106569. var deleted1 = [];
  106570. var v0 = t.vertices[j];
  106571. var v1 = t.vertices[(j + 1) % 3];
  106572. if (v0.isBorder || v1.isBorder)
  106573. continue;
  106574. var p = BABYLON.Vector3.Zero();
  106575. var n = BABYLON.Vector3.Zero();
  106576. var uv = BABYLON.Vector2.Zero();
  106577. var color = new BABYLON.Color4(0, 0, 0, 1);
  106578. _this.calculateError(v0, v1, p, n, uv, color);
  106579. var delTr = new Array();
  106580. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  106581. continue;
  106582. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  106583. continue;
  106584. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  106585. continue;
  106586. var uniqueArray = new Array();
  106587. delTr.forEach(function (deletedT) {
  106588. if (uniqueArray.indexOf(deletedT) === -1) {
  106589. deletedT.deletePending = true;
  106590. uniqueArray.push(deletedT);
  106591. }
  106592. });
  106593. if (uniqueArray.length % 2 !== 0) {
  106594. continue;
  106595. }
  106596. v0.q = v1.q.add(v0.q);
  106597. v0.updatePosition(p);
  106598. var tStart = _this.references.length;
  106599. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  106600. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  106601. var tCount = _this.references.length - tStart;
  106602. if (tCount <= v0.triangleCount) {
  106603. if (tCount) {
  106604. for (var c = 0; c < tCount; c++) {
  106605. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  106606. }
  106607. }
  106608. }
  106609. else {
  106610. v0.triangleStart = tStart;
  106611. }
  106612. v0.triangleCount = tCount;
  106613. break;
  106614. }
  106615. }
  106616. };
  106617. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  106618. }, 0);
  106619. };
  106620. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  106621. if (triangleCount - deletedTriangles <= targetCount)
  106622. loop.breakLoop();
  106623. else {
  106624. iterationFunction(loop.index, function () {
  106625. loop.executeNext();
  106626. });
  106627. }
  106628. }, function () {
  106629. setTimeout(function () {
  106630. //reconstruct this part of the mesh
  106631. _this.reconstructMesh(submeshIndex);
  106632. successCallback();
  106633. }, 0);
  106634. });
  106635. };
  106636. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  106637. var _this = this;
  106638. this.vertices = [];
  106639. this.triangles = [];
  106640. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  106641. var indices = this._mesh.getIndices();
  106642. var submesh = this._mesh.subMeshes[submeshIndex];
  106643. var findInVertices = function (positionToSearch) {
  106644. if (optimizeMesh) {
  106645. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  106646. if (_this.vertices[ii].position.equals(positionToSearch)) {
  106647. return _this.vertices[ii];
  106648. }
  106649. }
  106650. }
  106651. return null;
  106652. };
  106653. var vertexReferences = [];
  106654. var vertexInit = function (i) {
  106655. if (!positionData) {
  106656. return;
  106657. }
  106658. var offset = i + submesh.verticesStart;
  106659. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  106660. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  106661. vertex.originalOffsets.push(offset);
  106662. if (vertex.id === _this.vertices.length) {
  106663. _this.vertices.push(vertex);
  106664. }
  106665. vertexReferences.push(vertex.id);
  106666. };
  106667. //var totalVertices = mesh.getTotalVertices();
  106668. var totalVertices = submesh.verticesCount;
  106669. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  106670. var indicesInit = function (i) {
  106671. if (!indices) {
  106672. return;
  106673. }
  106674. var offset = (submesh.indexStart / 3) + i;
  106675. var pos = (offset * 3);
  106676. var i0 = indices[pos + 0];
  106677. var i1 = indices[pos + 1];
  106678. var i2 = indices[pos + 2];
  106679. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  106680. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  106681. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  106682. var triangle = new DecimationTriangle([v0, v1, v2]);
  106683. triangle.originalOffset = pos;
  106684. _this.triangles.push(triangle);
  106685. };
  106686. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  106687. _this.init(callback);
  106688. });
  106689. });
  106690. };
  106691. QuadraticErrorSimplification.prototype.init = function (callback) {
  106692. var _this = this;
  106693. var triangleInit1 = function (i) {
  106694. var t = _this.triangles[i];
  106695. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  106696. for (var j = 0; j < 3; j++) {
  106697. 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))));
  106698. }
  106699. };
  106700. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  106701. var triangleInit2 = function (i) {
  106702. var t = _this.triangles[i];
  106703. for (var j = 0; j < 3; ++j) {
  106704. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  106705. }
  106706. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106707. };
  106708. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  106709. callback();
  106710. });
  106711. });
  106712. };
  106713. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  106714. var newTriangles = [];
  106715. var i;
  106716. for (i = 0; i < this.vertices.length; ++i) {
  106717. this.vertices[i].triangleCount = 0;
  106718. }
  106719. var t;
  106720. var j;
  106721. for (i = 0; i < this.triangles.length; ++i) {
  106722. if (!this.triangles[i].deleted) {
  106723. t = this.triangles[i];
  106724. for (j = 0; j < 3; ++j) {
  106725. t.vertices[j].triangleCount = 1;
  106726. }
  106727. newTriangles.push(t);
  106728. }
  106729. }
  106730. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  106731. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  106732. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  106733. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  106734. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  106735. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  106736. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  106737. var vertexCount = 0;
  106738. for (i = 0; i < this.vertices.length; ++i) {
  106739. var vertex = this.vertices[i];
  106740. vertex.id = vertexCount;
  106741. if (vertex.triangleCount) {
  106742. vertex.originalOffsets.forEach(function (originalOffset) {
  106743. if (!normalData) {
  106744. return;
  106745. }
  106746. newPositionData.push(vertex.position.x);
  106747. newPositionData.push(vertex.position.y);
  106748. newPositionData.push(vertex.position.z);
  106749. newNormalData.push(normalData[originalOffset * 3]);
  106750. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  106751. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  106752. if (uvs && uvs.length) {
  106753. newUVsData.push(uvs[(originalOffset * 2)]);
  106754. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  106755. }
  106756. else if (colorsData && colorsData.length) {
  106757. newColorsData.push(colorsData[(originalOffset * 4)]);
  106758. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  106759. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  106760. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  106761. }
  106762. ++vertexCount;
  106763. });
  106764. }
  106765. }
  106766. var startingIndex = this._reconstructedMesh.getTotalIndices();
  106767. var startingVertex = this._reconstructedMesh.getTotalVertices();
  106768. var submeshesArray = this._reconstructedMesh.subMeshes;
  106769. this._reconstructedMesh.subMeshes = [];
  106770. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  106771. var originalIndices = this._mesh.getIndices();
  106772. for (i = 0; i < newTriangles.length; ++i) {
  106773. t = newTriangles[i]; //now get the new referencing point for each vertex
  106774. [0, 1, 2].forEach(function (idx) {
  106775. var id = originalIndices[t.originalOffset + idx];
  106776. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  106777. if (offset < 0)
  106778. offset = 0;
  106779. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  106780. });
  106781. }
  106782. //overwriting the old vertex buffers and indices.
  106783. this._reconstructedMesh.setIndices(newIndicesArray);
  106784. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  106785. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  106786. if (newUVsData.length > 0)
  106787. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  106788. if (newColorsData.length > 0)
  106789. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  106790. //create submesh
  106791. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  106792. if (submeshIndex > 0) {
  106793. this._reconstructedMesh.subMeshes = [];
  106794. submeshesArray.forEach(function (submesh) {
  106795. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  106796. });
  106797. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  106798. }
  106799. };
  106800. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  106801. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  106802. this._reconstructedMesh.material = this._mesh.material;
  106803. this._reconstructedMesh.parent = this._mesh.parent;
  106804. this._reconstructedMesh.isVisible = false;
  106805. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  106806. };
  106807. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  106808. for (var i = 0; i < vertex1.triangleCount; ++i) {
  106809. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  106810. if (t.deleted)
  106811. continue;
  106812. var s = this.references[vertex1.triangleStart + i].vertexId;
  106813. var v1 = t.vertices[(s + 1) % 3];
  106814. var v2 = t.vertices[(s + 2) % 3];
  106815. if ((v1 === vertex2 || v2 === vertex2)) {
  106816. deletedArray[i] = true;
  106817. delTr.push(t);
  106818. continue;
  106819. }
  106820. var d1 = v1.position.subtract(point);
  106821. d1 = d1.normalize();
  106822. var d2 = v2.position.subtract(point);
  106823. d2 = d2.normalize();
  106824. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  106825. return true;
  106826. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  106827. deletedArray[i] = false;
  106828. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  106829. return true;
  106830. }
  106831. return false;
  106832. };
  106833. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  106834. var newDeleted = deletedTriangles;
  106835. for (var i = 0; i < vertex.triangleCount; ++i) {
  106836. var ref = this.references[vertex.triangleStart + i];
  106837. var t = this.triangles[ref.triangleId];
  106838. if (t.deleted)
  106839. continue;
  106840. if (deletedArray[i] && t.deletePending) {
  106841. t.deleted = true;
  106842. newDeleted++;
  106843. continue;
  106844. }
  106845. t.vertices[ref.vertexId] = origVertex;
  106846. t.isDirty = true;
  106847. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  106848. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  106849. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  106850. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  106851. this.references.push(ref);
  106852. }
  106853. return newDeleted;
  106854. };
  106855. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  106856. for (var i = 0; i < this.vertices.length; ++i) {
  106857. var vCount = [];
  106858. var vId = [];
  106859. var v = this.vertices[i];
  106860. var j;
  106861. for (j = 0; j < v.triangleCount; ++j) {
  106862. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  106863. for (var ii = 0; ii < 3; ii++) {
  106864. var ofs = 0;
  106865. var vv = triangle.vertices[ii];
  106866. while (ofs < vCount.length) {
  106867. if (vId[ofs] === vv.id)
  106868. break;
  106869. ++ofs;
  106870. }
  106871. if (ofs === vCount.length) {
  106872. vCount.push(1);
  106873. vId.push(vv.id);
  106874. }
  106875. else {
  106876. vCount[ofs]++;
  106877. }
  106878. }
  106879. }
  106880. for (j = 0; j < vCount.length; ++j) {
  106881. if (vCount[j] === 1) {
  106882. this.vertices[vId[j]].isBorder = true;
  106883. }
  106884. else {
  106885. this.vertices[vId[j]].isBorder = false;
  106886. }
  106887. }
  106888. }
  106889. };
  106890. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  106891. if (identifyBorders === void 0) { identifyBorders = false; }
  106892. var i;
  106893. if (!identifyBorders) {
  106894. var newTrianglesVector = [];
  106895. for (i = 0; i < this.triangles.length; ++i) {
  106896. if (!this.triangles[i].deleted) {
  106897. newTrianglesVector.push(this.triangles[i]);
  106898. }
  106899. }
  106900. this.triangles = newTrianglesVector;
  106901. }
  106902. for (i = 0; i < this.vertices.length; ++i) {
  106903. this.vertices[i].triangleCount = 0;
  106904. this.vertices[i].triangleStart = 0;
  106905. }
  106906. var t;
  106907. var j;
  106908. var v;
  106909. for (i = 0; i < this.triangles.length; ++i) {
  106910. t = this.triangles[i];
  106911. for (j = 0; j < 3; ++j) {
  106912. v = t.vertices[j];
  106913. v.triangleCount++;
  106914. }
  106915. }
  106916. var tStart = 0;
  106917. for (i = 0; i < this.vertices.length; ++i) {
  106918. this.vertices[i].triangleStart = tStart;
  106919. tStart += this.vertices[i].triangleCount;
  106920. this.vertices[i].triangleCount = 0;
  106921. }
  106922. var newReferences = new Array(this.triangles.length * 3);
  106923. for (i = 0; i < this.triangles.length; ++i) {
  106924. t = this.triangles[i];
  106925. for (j = 0; j < 3; ++j) {
  106926. v = t.vertices[j];
  106927. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  106928. v.triangleCount++;
  106929. }
  106930. }
  106931. this.references = newReferences;
  106932. if (identifyBorders) {
  106933. this.identifyBorder();
  106934. }
  106935. };
  106936. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  106937. var x = point.x;
  106938. var y = point.y;
  106939. var z = point.z;
  106940. 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
  106941. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  106942. };
  106943. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  106944. var q = vertex1.q.add(vertex2.q);
  106945. var border = vertex1.isBorder && vertex2.isBorder;
  106946. var error = 0;
  106947. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  106948. if (qDet !== 0 && !border) {
  106949. if (!pointResult) {
  106950. pointResult = BABYLON.Vector3.Zero();
  106951. }
  106952. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  106953. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  106954. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  106955. error = this.vertexError(q, pointResult);
  106956. }
  106957. else {
  106958. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  106959. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  106960. var error1 = this.vertexError(q, vertex1.position);
  106961. var error2 = this.vertexError(q, vertex2.position);
  106962. var error3 = this.vertexError(q, p3);
  106963. error = Math.min(error1, error2, error3);
  106964. if (error === error1) {
  106965. if (pointResult) {
  106966. pointResult.copyFrom(vertex1.position);
  106967. }
  106968. }
  106969. else if (error === error2) {
  106970. if (pointResult) {
  106971. pointResult.copyFrom(vertex2.position);
  106972. }
  106973. }
  106974. else {
  106975. if (pointResult) {
  106976. pointResult.copyFrom(p3);
  106977. }
  106978. }
  106979. }
  106980. return error;
  106981. };
  106982. return QuadraticErrorSimplification;
  106983. }());
  106984. })(BABYLON || (BABYLON = {}));
  106985. //# sourceMappingURL=babylon.meshSimplification.js.map
  106986. var BABYLON;
  106987. (function (BABYLON) {
  106988. Object.defineProperty(BABYLON.Scene.prototype, "simplificationQueue", {
  106989. get: function () {
  106990. if (!this._simplificationQueue) {
  106991. this._simplificationQueue = new BABYLON.SimplificationQueue();
  106992. var component = this._getComponent(BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE);
  106993. if (!component) {
  106994. component = new SimplicationQueueSceneComponent(this);
  106995. this._addComponent(component);
  106996. }
  106997. }
  106998. return this._simplificationQueue;
  106999. },
  107000. set: function (value) {
  107001. this._simplificationQueue = value;
  107002. },
  107003. enumerable: true,
  107004. configurable: true
  107005. });
  107006. BABYLON.Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  107007. if (parallelProcessing === void 0) { parallelProcessing = true; }
  107008. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  107009. this.getScene().simplificationQueue.addTask({
  107010. settings: settings,
  107011. parallelProcessing: parallelProcessing,
  107012. mesh: this,
  107013. simplificationType: simplificationType,
  107014. successCallback: successCallback
  107015. });
  107016. return this;
  107017. };
  107018. /**
  107019. * Defines the simplification queue scene component responsible to help scheduling the various simplification task
  107020. * created in a scene
  107021. */
  107022. var SimplicationQueueSceneComponent = /** @class */ (function () {
  107023. /**
  107024. * Creates a new instance of the component for the given scene
  107025. * @param scene Defines the scene to register the component in
  107026. */
  107027. function SimplicationQueueSceneComponent(scene) {
  107028. /**
  107029. * The component name helpfull to identify the component in the list of scene components.
  107030. */
  107031. this.name = BABYLON.SceneComponentConstants.NAME_SIMPLIFICATIONQUEUE;
  107032. this.scene = scene;
  107033. }
  107034. /**
  107035. * Registers the component in a given scene
  107036. */
  107037. SimplicationQueueSceneComponent.prototype.register = function () {
  107038. this.scene._beforeCameraUpdateStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERAUPDATE_SIMPLIFICATIONQUEUE, this, this._beforeCameraUpdate);
  107039. };
  107040. /**
  107041. * Rebuilds the elements related to this component in case of
  107042. * context lost for instance.
  107043. */
  107044. SimplicationQueueSceneComponent.prototype.rebuild = function () {
  107045. // Nothing to do for this component
  107046. };
  107047. /**
  107048. * Disposes the component and the associated ressources
  107049. */
  107050. SimplicationQueueSceneComponent.prototype.dispose = function () {
  107051. // Nothing to do for this component
  107052. };
  107053. SimplicationQueueSceneComponent.prototype._beforeCameraUpdate = function () {
  107054. if (this.scene._simplificationQueue && !this.scene._simplificationQueue.running) {
  107055. this.scene._simplificationQueue.executeNext();
  107056. }
  107057. };
  107058. return SimplicationQueueSceneComponent;
  107059. }());
  107060. BABYLON.SimplicationQueueSceneComponent = SimplicationQueueSceneComponent;
  107061. })(BABYLON || (BABYLON = {}));
  107062. //# sourceMappingURL=babylon.meshSimplificationSceneComponent.js.map
  107063. var BABYLON;
  107064. (function (BABYLON) {
  107065. /**
  107066. * Class used to represent a specific level of detail of a mesh
  107067. * @see http://doc.babylonjs.com/how_to/how_to_use_lod
  107068. */
  107069. var MeshLODLevel = /** @class */ (function () {
  107070. /**
  107071. * Creates a new LOD level
  107072. * @param distance defines the distance where this level should star being displayed
  107073. * @param mesh defines the mesh to use to render this level
  107074. */
  107075. function MeshLODLevel(
  107076. /** Defines the distance where this level should star being displayed */
  107077. distance,
  107078. /** Defines the mesh to use to render this level */
  107079. mesh) {
  107080. this.distance = distance;
  107081. this.mesh = mesh;
  107082. }
  107083. return MeshLODLevel;
  107084. }());
  107085. BABYLON.MeshLODLevel = MeshLODLevel;
  107086. })(BABYLON || (BABYLON = {}));
  107087. //# sourceMappingURL=babylon.meshLODLevel.js.map
  107088. var BABYLON;
  107089. (function (BABYLON) {
  107090. /**
  107091. * Defines the root class used to create scene optimization to use with SceneOptimizer
  107092. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107093. */
  107094. var SceneOptimization = /** @class */ (function () {
  107095. /**
  107096. * Creates the SceneOptimization object
  107097. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107098. * @param desc defines the description associated with the optimization
  107099. */
  107100. function SceneOptimization(
  107101. /**
  107102. * Defines the priority of this optimization (0 by default which means first in the list)
  107103. */
  107104. priority) {
  107105. if (priority === void 0) { priority = 0; }
  107106. this.priority = priority;
  107107. }
  107108. /**
  107109. * Gets a string describing the action executed by the current optimization
  107110. * @returns description string
  107111. */
  107112. SceneOptimization.prototype.getDescription = function () {
  107113. return "";
  107114. };
  107115. /**
  107116. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107117. * @param scene defines the current scene where to apply this optimization
  107118. * @param optimizer defines the current optimizer
  107119. * @returns true if everything that can be done was applied
  107120. */
  107121. SceneOptimization.prototype.apply = function (scene, optimizer) {
  107122. return true;
  107123. };
  107124. ;
  107125. return SceneOptimization;
  107126. }());
  107127. BABYLON.SceneOptimization = SceneOptimization;
  107128. /**
  107129. * Defines an optimization used to reduce the size of render target textures
  107130. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107131. */
  107132. var TextureOptimization = /** @class */ (function (_super) {
  107133. __extends(TextureOptimization, _super);
  107134. /**
  107135. * Creates the TextureOptimization object
  107136. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107137. * @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
  107138. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107139. */
  107140. function TextureOptimization(
  107141. /**
  107142. * Defines the priority of this optimization (0 by default which means first in the list)
  107143. */
  107144. priority,
  107145. /**
  107146. * 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
  107147. */
  107148. maximumSize,
  107149. /**
  107150. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  107151. */
  107152. step) {
  107153. if (priority === void 0) { priority = 0; }
  107154. if (maximumSize === void 0) { maximumSize = 1024; }
  107155. if (step === void 0) { step = 0.5; }
  107156. var _this = _super.call(this, priority) || this;
  107157. _this.priority = priority;
  107158. _this.maximumSize = maximumSize;
  107159. _this.step = step;
  107160. return _this;
  107161. }
  107162. /**
  107163. * Gets a string describing the action executed by the current optimization
  107164. * @returns description string
  107165. */
  107166. TextureOptimization.prototype.getDescription = function () {
  107167. return "Reducing render target texture size to " + this.maximumSize;
  107168. };
  107169. /**
  107170. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107171. * @param scene defines the current scene where to apply this optimization
  107172. * @param optimizer defines the current optimizer
  107173. * @returns true if everything that can be done was applied
  107174. */
  107175. TextureOptimization.prototype.apply = function (scene, optimizer) {
  107176. var allDone = true;
  107177. for (var index = 0; index < scene.textures.length; index++) {
  107178. var texture = scene.textures[index];
  107179. if (!texture.canRescale || texture.getContext) {
  107180. continue;
  107181. }
  107182. var currentSize = texture.getSize();
  107183. var maxDimension = Math.max(currentSize.width, currentSize.height);
  107184. if (maxDimension > this.maximumSize) {
  107185. texture.scale(this.step);
  107186. allDone = false;
  107187. }
  107188. }
  107189. return allDone;
  107190. };
  107191. return TextureOptimization;
  107192. }(SceneOptimization));
  107193. BABYLON.TextureOptimization = TextureOptimization;
  107194. /**
  107195. * Defines an optimization used to increase or decrease the rendering resolution
  107196. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107197. */
  107198. var HardwareScalingOptimization = /** @class */ (function (_super) {
  107199. __extends(HardwareScalingOptimization, _super);
  107200. /**
  107201. * Creates the HardwareScalingOptimization object
  107202. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107203. * @param maximumScale defines the maximum scale to use (2 by default)
  107204. * @param step defines the step to use between two passes (0.5 by default)
  107205. */
  107206. function HardwareScalingOptimization(
  107207. /**
  107208. * Defines the priority of this optimization (0 by default which means first in the list)
  107209. */
  107210. priority,
  107211. /**
  107212. * Defines the maximum scale to use (2 by default)
  107213. */
  107214. maximumScale,
  107215. /**
  107216. * Defines the step to use between two passes (0.5 by default)
  107217. */
  107218. step) {
  107219. if (priority === void 0) { priority = 0; }
  107220. if (maximumScale === void 0) { maximumScale = 2; }
  107221. if (step === void 0) { step = 0.25; }
  107222. var _this = _super.call(this, priority) || this;
  107223. _this.priority = priority;
  107224. _this.maximumScale = maximumScale;
  107225. _this.step = step;
  107226. _this._currentScale = -1;
  107227. _this._directionOffset = 1;
  107228. return _this;
  107229. }
  107230. /**
  107231. * Gets a string describing the action executed by the current optimization
  107232. * @return description string
  107233. */
  107234. HardwareScalingOptimization.prototype.getDescription = function () {
  107235. return "Setting hardware scaling level to " + this._currentScale;
  107236. };
  107237. /**
  107238. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107239. * @param scene defines the current scene where to apply this optimization
  107240. * @param optimizer defines the current optimizer
  107241. * @returns true if everything that can be done was applied
  107242. */
  107243. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  107244. if (this._currentScale === -1) {
  107245. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  107246. if (this._currentScale > this.maximumScale) {
  107247. this._directionOffset = -1;
  107248. }
  107249. }
  107250. this._currentScale += this._directionOffset * this.step;
  107251. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  107252. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  107253. };
  107254. ;
  107255. return HardwareScalingOptimization;
  107256. }(SceneOptimization));
  107257. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  107258. /**
  107259. * Defines an optimization used to remove shadows
  107260. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107261. */
  107262. var ShadowsOptimization = /** @class */ (function (_super) {
  107263. __extends(ShadowsOptimization, _super);
  107264. function ShadowsOptimization() {
  107265. return _super !== null && _super.apply(this, arguments) || this;
  107266. }
  107267. /**
  107268. * Gets a string describing the action executed by the current optimization
  107269. * @return description string
  107270. */
  107271. ShadowsOptimization.prototype.getDescription = function () {
  107272. return "Turning shadows on/off";
  107273. };
  107274. /**
  107275. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107276. * @param scene defines the current scene where to apply this optimization
  107277. * @param optimizer defines the current optimizer
  107278. * @returns true if everything that can be done was applied
  107279. */
  107280. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  107281. scene.shadowsEnabled = optimizer.isInImprovementMode;
  107282. return true;
  107283. };
  107284. ;
  107285. return ShadowsOptimization;
  107286. }(SceneOptimization));
  107287. BABYLON.ShadowsOptimization = ShadowsOptimization;
  107288. /**
  107289. * Defines an optimization used to turn post-processes off
  107290. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107291. */
  107292. var PostProcessesOptimization = /** @class */ (function (_super) {
  107293. __extends(PostProcessesOptimization, _super);
  107294. function PostProcessesOptimization() {
  107295. return _super !== null && _super.apply(this, arguments) || this;
  107296. }
  107297. /**
  107298. * Gets a string describing the action executed by the current optimization
  107299. * @return description string
  107300. */
  107301. PostProcessesOptimization.prototype.getDescription = function () {
  107302. return "Turning post-processes on/off";
  107303. };
  107304. /**
  107305. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107306. * @param scene defines the current scene where to apply this optimization
  107307. * @param optimizer defines the current optimizer
  107308. * @returns true if everything that can be done was applied
  107309. */
  107310. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  107311. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  107312. return true;
  107313. };
  107314. ;
  107315. return PostProcessesOptimization;
  107316. }(SceneOptimization));
  107317. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  107318. /**
  107319. * Defines an optimization used to turn lens flares off
  107320. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107321. */
  107322. var LensFlaresOptimization = /** @class */ (function (_super) {
  107323. __extends(LensFlaresOptimization, _super);
  107324. function LensFlaresOptimization() {
  107325. return _super !== null && _super.apply(this, arguments) || this;
  107326. }
  107327. /**
  107328. * Gets a string describing the action executed by the current optimization
  107329. * @return description string
  107330. */
  107331. LensFlaresOptimization.prototype.getDescription = function () {
  107332. return "Turning lens flares on/off";
  107333. };
  107334. /**
  107335. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107336. * @param scene defines the current scene where to apply this optimization
  107337. * @param optimizer defines the current optimizer
  107338. * @returns true if everything that can be done was applied
  107339. */
  107340. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  107341. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  107342. return true;
  107343. };
  107344. ;
  107345. return LensFlaresOptimization;
  107346. }(SceneOptimization));
  107347. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  107348. /**
  107349. * Defines an optimization based on user defined callback.
  107350. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107351. */
  107352. var CustomOptimization = /** @class */ (function (_super) {
  107353. __extends(CustomOptimization, _super);
  107354. function CustomOptimization() {
  107355. return _super !== null && _super.apply(this, arguments) || this;
  107356. }
  107357. /**
  107358. * Gets a string describing the action executed by the current optimization
  107359. * @returns description string
  107360. */
  107361. CustomOptimization.prototype.getDescription = function () {
  107362. if (this.onGetDescription) {
  107363. return this.onGetDescription();
  107364. }
  107365. return "Running user defined callback";
  107366. };
  107367. /**
  107368. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107369. * @param scene defines the current scene where to apply this optimization
  107370. * @param optimizer defines the current optimizer
  107371. * @returns true if everything that can be done was applied
  107372. */
  107373. CustomOptimization.prototype.apply = function (scene, optimizer) {
  107374. if (this.onApply) {
  107375. return this.onApply(scene, optimizer);
  107376. }
  107377. return true;
  107378. };
  107379. ;
  107380. return CustomOptimization;
  107381. }(SceneOptimization));
  107382. BABYLON.CustomOptimization = CustomOptimization;
  107383. /**
  107384. * Defines an optimization used to turn particles off
  107385. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107386. */
  107387. var ParticlesOptimization = /** @class */ (function (_super) {
  107388. __extends(ParticlesOptimization, _super);
  107389. function ParticlesOptimization() {
  107390. return _super !== null && _super.apply(this, arguments) || this;
  107391. }
  107392. /**
  107393. * Gets a string describing the action executed by the current optimization
  107394. * @return description string
  107395. */
  107396. ParticlesOptimization.prototype.getDescription = function () {
  107397. return "Turning particles on/off";
  107398. };
  107399. /**
  107400. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107401. * @param scene defines the current scene where to apply this optimization
  107402. * @param optimizer defines the current optimizer
  107403. * @returns true if everything that can be done was applied
  107404. */
  107405. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  107406. scene.particlesEnabled = optimizer.isInImprovementMode;
  107407. return true;
  107408. };
  107409. ;
  107410. return ParticlesOptimization;
  107411. }(SceneOptimization));
  107412. BABYLON.ParticlesOptimization = ParticlesOptimization;
  107413. /**
  107414. * Defines an optimization used to turn render targets off
  107415. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107416. */
  107417. var RenderTargetsOptimization = /** @class */ (function (_super) {
  107418. __extends(RenderTargetsOptimization, _super);
  107419. function RenderTargetsOptimization() {
  107420. return _super !== null && _super.apply(this, arguments) || this;
  107421. }
  107422. /**
  107423. * Gets a string describing the action executed by the current optimization
  107424. * @return description string
  107425. */
  107426. RenderTargetsOptimization.prototype.getDescription = function () {
  107427. return "Turning render targets off";
  107428. };
  107429. /**
  107430. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107431. * @param scene defines the current scene where to apply this optimization
  107432. * @param optimizer defines the current optimizer
  107433. * @returns true if everything that can be done was applied
  107434. */
  107435. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  107436. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  107437. return true;
  107438. };
  107439. ;
  107440. return RenderTargetsOptimization;
  107441. }(SceneOptimization));
  107442. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  107443. /**
  107444. * Defines an optimization used to merge meshes with compatible materials
  107445. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107446. */
  107447. var MergeMeshesOptimization = /** @class */ (function (_super) {
  107448. __extends(MergeMeshesOptimization, _super);
  107449. function MergeMeshesOptimization() {
  107450. var _this = _super !== null && _super.apply(this, arguments) || this;
  107451. _this._canBeMerged = function (abstractMesh) {
  107452. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  107453. return false;
  107454. }
  107455. var mesh = abstractMesh;
  107456. if (mesh.isDisposed()) {
  107457. return false;
  107458. }
  107459. if (!mesh.isVisible || !mesh.isEnabled()) {
  107460. return false;
  107461. }
  107462. if (mesh.instances.length > 0) {
  107463. return false;
  107464. }
  107465. if (mesh.skeleton || mesh.hasLODLevels) {
  107466. return false;
  107467. }
  107468. return true;
  107469. };
  107470. return _this;
  107471. }
  107472. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  107473. /**
  107474. * Gets or sets a boolean which defines if optimization octree has to be updated
  107475. */
  107476. get: function () {
  107477. return MergeMeshesOptimization._UpdateSelectionTree;
  107478. },
  107479. /**
  107480. * Gets or sets a boolean which defines if optimization octree has to be updated
  107481. */
  107482. set: function (value) {
  107483. MergeMeshesOptimization._UpdateSelectionTree = value;
  107484. },
  107485. enumerable: true,
  107486. configurable: true
  107487. });
  107488. /**
  107489. * Gets a string describing the action executed by the current optimization
  107490. * @return description string
  107491. */
  107492. MergeMeshesOptimization.prototype.getDescription = function () {
  107493. return "Merging similar meshes together";
  107494. };
  107495. /**
  107496. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  107497. * @param scene defines the current scene where to apply this optimization
  107498. * @param optimizer defines the current optimizer
  107499. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  107500. * @returns true if everything that can be done was applied
  107501. */
  107502. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  107503. var globalPool = scene.meshes.slice(0);
  107504. var globalLength = globalPool.length;
  107505. for (var index = 0; index < globalLength; index++) {
  107506. var currentPool = new Array();
  107507. var current = globalPool[index];
  107508. // Checks
  107509. if (!this._canBeMerged(current)) {
  107510. continue;
  107511. }
  107512. currentPool.push(current);
  107513. // Find compatible meshes
  107514. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  107515. var otherMesh = globalPool[subIndex];
  107516. if (!this._canBeMerged(otherMesh)) {
  107517. continue;
  107518. }
  107519. if (otherMesh.material !== current.material) {
  107520. continue;
  107521. }
  107522. if (otherMesh.checkCollisions !== current.checkCollisions) {
  107523. continue;
  107524. }
  107525. currentPool.push(otherMesh);
  107526. globalLength--;
  107527. globalPool.splice(subIndex, 1);
  107528. subIndex--;
  107529. }
  107530. if (currentPool.length < 2) {
  107531. continue;
  107532. }
  107533. // Merge meshes
  107534. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  107535. }
  107536. // Call the octree system optimization if it is defined.
  107537. var sceneAsAny = scene;
  107538. if (sceneAsAny.createOrUpdateSelectionOctree) {
  107539. if (updateSelectionTree != undefined) {
  107540. if (updateSelectionTree) {
  107541. sceneAsAny.createOrUpdateSelectionOctree();
  107542. }
  107543. }
  107544. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  107545. sceneAsAny.createOrUpdateSelectionOctree();
  107546. }
  107547. }
  107548. return true;
  107549. };
  107550. ;
  107551. MergeMeshesOptimization._UpdateSelectionTree = false;
  107552. return MergeMeshesOptimization;
  107553. }(SceneOptimization));
  107554. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  107555. /**
  107556. * Defines a list of options used by SceneOptimizer
  107557. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107558. */
  107559. var SceneOptimizerOptions = /** @class */ (function () {
  107560. /**
  107561. * Creates a new list of options used by SceneOptimizer
  107562. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  107563. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  107564. */
  107565. function SceneOptimizerOptions(
  107566. /**
  107567. * Defines the target frame rate to reach (60 by default)
  107568. */
  107569. targetFrameRate,
  107570. /**
  107571. * Defines the interval between two checkes (2000ms by default)
  107572. */
  107573. trackerDuration) {
  107574. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  107575. if (trackerDuration === void 0) { trackerDuration = 2000; }
  107576. this.targetFrameRate = targetFrameRate;
  107577. this.trackerDuration = trackerDuration;
  107578. /**
  107579. * Gets the list of optimizations to apply
  107580. */
  107581. this.optimizations = new Array();
  107582. }
  107583. /**
  107584. * Add a new optimization
  107585. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  107586. * @returns the current SceneOptimizerOptions
  107587. */
  107588. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  107589. this.optimizations.push(optimization);
  107590. return this;
  107591. };
  107592. /**
  107593. * Add a new custom optimization
  107594. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  107595. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  107596. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  107597. * @returns the current SceneOptimizerOptions
  107598. */
  107599. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  107600. if (priority === void 0) { priority = 0; }
  107601. var optimization = new CustomOptimization(priority);
  107602. optimization.onApply = onApply;
  107603. optimization.onGetDescription = onGetDescription;
  107604. this.optimizations.push(optimization);
  107605. return this;
  107606. };
  107607. /**
  107608. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  107609. * @param targetFrameRate defines the target frame rate (60 by default)
  107610. * @returns a SceneOptimizerOptions object
  107611. */
  107612. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  107613. var result = new SceneOptimizerOptions(targetFrameRate);
  107614. var priority = 0;
  107615. result.addOptimization(new MergeMeshesOptimization(priority));
  107616. result.addOptimization(new ShadowsOptimization(priority));
  107617. result.addOptimization(new LensFlaresOptimization(priority));
  107618. // Next priority
  107619. priority++;
  107620. result.addOptimization(new PostProcessesOptimization(priority));
  107621. result.addOptimization(new ParticlesOptimization(priority));
  107622. // Next priority
  107623. priority++;
  107624. result.addOptimization(new TextureOptimization(priority, 1024));
  107625. return result;
  107626. };
  107627. /**
  107628. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  107629. * @param targetFrameRate defines the target frame rate (60 by default)
  107630. * @returns a SceneOptimizerOptions object
  107631. */
  107632. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  107633. var result = new SceneOptimizerOptions(targetFrameRate);
  107634. var priority = 0;
  107635. result.addOptimization(new MergeMeshesOptimization(priority));
  107636. result.addOptimization(new ShadowsOptimization(priority));
  107637. result.addOptimization(new LensFlaresOptimization(priority));
  107638. // Next priority
  107639. priority++;
  107640. result.addOptimization(new PostProcessesOptimization(priority));
  107641. result.addOptimization(new ParticlesOptimization(priority));
  107642. // Next priority
  107643. priority++;
  107644. result.addOptimization(new TextureOptimization(priority, 512));
  107645. // Next priority
  107646. priority++;
  107647. result.addOptimization(new RenderTargetsOptimization(priority));
  107648. // Next priority
  107649. priority++;
  107650. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  107651. return result;
  107652. };
  107653. /**
  107654. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  107655. * @param targetFrameRate defines the target frame rate (60 by default)
  107656. * @returns a SceneOptimizerOptions object
  107657. */
  107658. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  107659. var result = new SceneOptimizerOptions(targetFrameRate);
  107660. var priority = 0;
  107661. result.addOptimization(new MergeMeshesOptimization(priority));
  107662. result.addOptimization(new ShadowsOptimization(priority));
  107663. result.addOptimization(new LensFlaresOptimization(priority));
  107664. // Next priority
  107665. priority++;
  107666. result.addOptimization(new PostProcessesOptimization(priority));
  107667. result.addOptimization(new ParticlesOptimization(priority));
  107668. // Next priority
  107669. priority++;
  107670. result.addOptimization(new TextureOptimization(priority, 256));
  107671. // Next priority
  107672. priority++;
  107673. result.addOptimization(new RenderTargetsOptimization(priority));
  107674. // Next priority
  107675. priority++;
  107676. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  107677. return result;
  107678. };
  107679. return SceneOptimizerOptions;
  107680. }());
  107681. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  107682. /**
  107683. * Class used to run optimizations in order to reach a target frame rate
  107684. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  107685. */
  107686. var SceneOptimizer = /** @class */ (function () {
  107687. /**
  107688. * Creates a new SceneOptimizer
  107689. * @param scene defines the scene to work on
  107690. * @param options defines the options to use with the SceneOptimizer
  107691. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  107692. * @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)
  107693. */
  107694. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  107695. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  107696. if (improvementMode === void 0) { improvementMode = false; }
  107697. var _this = this;
  107698. this._isRunning = false;
  107699. this._currentPriorityLevel = 0;
  107700. this._targetFrameRate = 60;
  107701. this._trackerDuration = 2000;
  107702. this._currentFrameRate = 0;
  107703. this._improvementMode = false;
  107704. /**
  107705. * Defines an observable called when the optimizer reaches the target frame rate
  107706. */
  107707. this.onSuccessObservable = new BABYLON.Observable();
  107708. /**
  107709. * Defines an observable called when the optimizer enables an optimization
  107710. */
  107711. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  107712. /**
  107713. * Defines an observable called when the optimizer is not able to reach the target frame rate
  107714. */
  107715. this.onFailureObservable = new BABYLON.Observable();
  107716. if (!options) {
  107717. this._options = new SceneOptimizerOptions();
  107718. }
  107719. else {
  107720. this._options = options;
  107721. }
  107722. if (this._options.targetFrameRate) {
  107723. this._targetFrameRate = this._options.targetFrameRate;
  107724. }
  107725. if (this._options.trackerDuration) {
  107726. this._trackerDuration = this._options.trackerDuration;
  107727. }
  107728. if (autoGeneratePriorities) {
  107729. var priority = 0;
  107730. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  107731. var optim = _a[_i];
  107732. optim.priority = priority++;
  107733. }
  107734. }
  107735. this._improvementMode = improvementMode;
  107736. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  107737. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  107738. _this._sceneDisposeObserver = null;
  107739. _this.dispose();
  107740. });
  107741. }
  107742. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  107743. /**
  107744. * Gets a boolean indicating if the optimizer is in improvement mode
  107745. */
  107746. get: function () {
  107747. return this._improvementMode;
  107748. },
  107749. enumerable: true,
  107750. configurable: true
  107751. });
  107752. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  107753. /**
  107754. * Gets the current priority level (0 at start)
  107755. */
  107756. get: function () {
  107757. return this._currentPriorityLevel;
  107758. },
  107759. enumerable: true,
  107760. configurable: true
  107761. });
  107762. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  107763. /**
  107764. * Gets the current frame rate checked by the SceneOptimizer
  107765. */
  107766. get: function () {
  107767. return this._currentFrameRate;
  107768. },
  107769. enumerable: true,
  107770. configurable: true
  107771. });
  107772. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  107773. /**
  107774. * Gets or sets the current target frame rate (60 by default)
  107775. */
  107776. get: function () {
  107777. return this._targetFrameRate;
  107778. },
  107779. /**
  107780. * Gets or sets the current target frame rate (60 by default)
  107781. */
  107782. set: function (value) {
  107783. this._targetFrameRate = value;
  107784. },
  107785. enumerable: true,
  107786. configurable: true
  107787. });
  107788. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  107789. /**
  107790. * Gets or sets the current interval between two checks (every 2000ms by default)
  107791. */
  107792. get: function () {
  107793. return this._trackerDuration;
  107794. },
  107795. /**
  107796. * Gets or sets the current interval between two checks (every 2000ms by default)
  107797. */
  107798. set: function (value) {
  107799. this._trackerDuration = value;
  107800. },
  107801. enumerable: true,
  107802. configurable: true
  107803. });
  107804. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  107805. /**
  107806. * Gets the list of active optimizations
  107807. */
  107808. get: function () {
  107809. return this._options.optimizations;
  107810. },
  107811. enumerable: true,
  107812. configurable: true
  107813. });
  107814. /**
  107815. * Stops the current optimizer
  107816. */
  107817. SceneOptimizer.prototype.stop = function () {
  107818. this._isRunning = false;
  107819. };
  107820. /**
  107821. * Reset the optimizer to initial step (current priority level = 0)
  107822. */
  107823. SceneOptimizer.prototype.reset = function () {
  107824. this._currentPriorityLevel = 0;
  107825. };
  107826. /**
  107827. * Start the optimizer. By default it will try to reach a specific framerate
  107828. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  107829. */
  107830. SceneOptimizer.prototype.start = function () {
  107831. var _this = this;
  107832. if (this._isRunning) {
  107833. return;
  107834. }
  107835. this._isRunning = true;
  107836. // Let's wait for the scene to be ready before running our check
  107837. this._scene.executeWhenReady(function () {
  107838. setTimeout(function () {
  107839. _this._checkCurrentState();
  107840. }, _this._trackerDuration);
  107841. });
  107842. };
  107843. SceneOptimizer.prototype._checkCurrentState = function () {
  107844. var _this = this;
  107845. if (!this._isRunning) {
  107846. return;
  107847. }
  107848. var scene = this._scene;
  107849. var options = this._options;
  107850. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  107851. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  107852. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  107853. this._isRunning = false;
  107854. this.onSuccessObservable.notifyObservers(this);
  107855. return;
  107856. }
  107857. // Apply current level of optimizations
  107858. var allDone = true;
  107859. var noOptimizationApplied = true;
  107860. for (var index = 0; index < options.optimizations.length; index++) {
  107861. var optimization = options.optimizations[index];
  107862. if (optimization.priority === this._currentPriorityLevel) {
  107863. noOptimizationApplied = false;
  107864. allDone = allDone && optimization.apply(scene, this);
  107865. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  107866. }
  107867. }
  107868. // If no optimization was applied, this is a failure :(
  107869. if (noOptimizationApplied) {
  107870. this._isRunning = false;
  107871. this.onFailureObservable.notifyObservers(this);
  107872. return;
  107873. }
  107874. // If all optimizations were done, move to next level
  107875. if (allDone) {
  107876. this._currentPriorityLevel++;
  107877. }
  107878. // Let's the system running for a specific amount of time before checking FPS
  107879. scene.executeWhenReady(function () {
  107880. setTimeout(function () {
  107881. _this._checkCurrentState();
  107882. }, _this._trackerDuration);
  107883. });
  107884. };
  107885. /**
  107886. * Release all resources
  107887. */
  107888. SceneOptimizer.prototype.dispose = function () {
  107889. this.stop();
  107890. this.onSuccessObservable.clear();
  107891. this.onFailureObservable.clear();
  107892. this.onNewOptimizationAppliedObservable.clear();
  107893. if (this._sceneDisposeObserver) {
  107894. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  107895. }
  107896. };
  107897. /**
  107898. * Helper function to create a SceneOptimizer with one single line of code
  107899. * @param scene defines the scene to work on
  107900. * @param options defines the options to use with the SceneOptimizer
  107901. * @param onSuccess defines a callback to call on success
  107902. * @param onFailure defines a callback to call on failure
  107903. * @returns the new SceneOptimizer object
  107904. */
  107905. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  107906. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  107907. if (onSuccess) {
  107908. optimizer.onSuccessObservable.add(function () {
  107909. onSuccess();
  107910. });
  107911. }
  107912. if (onFailure) {
  107913. optimizer.onFailureObservable.add(function () {
  107914. onFailure();
  107915. });
  107916. }
  107917. optimizer.start();
  107918. return optimizer;
  107919. };
  107920. return SceneOptimizer;
  107921. }());
  107922. BABYLON.SceneOptimizer = SceneOptimizer;
  107923. })(BABYLON || (BABYLON = {}));
  107924. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  107925. var BABYLON;
  107926. (function (BABYLON) {
  107927. /**
  107928. * Gets the outline renderer associated with the scene
  107929. * @returns a OutlineRenderer
  107930. */
  107931. BABYLON.Scene.prototype.getOutlineRenderer = function () {
  107932. if (!this._outlineRenderer) {
  107933. this._outlineRenderer = new OutlineRenderer(this);
  107934. }
  107935. return this._outlineRenderer;
  107936. };
  107937. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOutline", {
  107938. get: function () {
  107939. return this._renderOutline;
  107940. },
  107941. set: function (value) {
  107942. if (value) {
  107943. // Lazy Load the component.
  107944. this.getScene().getOutlineRenderer();
  107945. }
  107946. this._renderOutline = value;
  107947. },
  107948. enumerable: true,
  107949. configurable: true
  107950. });
  107951. Object.defineProperty(BABYLON.AbstractMesh.prototype, "renderOverlay", {
  107952. get: function () {
  107953. return this._renderOverlay;
  107954. },
  107955. set: function (value) {
  107956. if (value) {
  107957. // Lazy Load the component.
  107958. this.getScene().getOutlineRenderer();
  107959. }
  107960. this._renderOverlay = value;
  107961. },
  107962. enumerable: true,
  107963. configurable: true
  107964. });
  107965. /**
  107966. * This class is responsible to draw bothe outline/overlay of meshes.
  107967. * It should not be used directly but through the available method on mesh.
  107968. */
  107969. var OutlineRenderer = /** @class */ (function () {
  107970. /**
  107971. * Instantiates a new outline renderer. (There could be only one per scene).
  107972. * @param scene Defines the scene it belongs to
  107973. */
  107974. function OutlineRenderer(scene) {
  107975. /**
  107976. * The name of the component. Each component must have a unique name.
  107977. */
  107978. this.name = BABYLON.SceneComponentConstants.NAME_OUTLINERENDERER;
  107979. /**
  107980. * Defines a zOffset to prevent zFighting between the overlay and the mesh.
  107981. */
  107982. this.zOffset = 1;
  107983. this.scene = scene;
  107984. this._engine = scene.getEngine();
  107985. this.scene._addComponent(this);
  107986. }
  107987. /**
  107988. * Register the component to one instance of a scene.
  107989. */
  107990. OutlineRenderer.prototype.register = function () {
  107991. this.scene._beforeRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORERENDERINGMESH_OUTLINE, this, this._beforeRenderingMesh);
  107992. this.scene._afterRenderingMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGMESH_OUTLINE, this, this._afterRenderingMesh);
  107993. };
  107994. /**
  107995. * Rebuilds the elements related to this component in case of
  107996. * context lost for instance.
  107997. */
  107998. OutlineRenderer.prototype.rebuild = function () {
  107999. // Nothing to do here.
  108000. };
  108001. /**
  108002. * Disposes the component and the associated ressources.
  108003. */
  108004. OutlineRenderer.prototype.dispose = function () {
  108005. // Nothing to do here.
  108006. };
  108007. /**
  108008. * Renders the outline in the canvas.
  108009. * @param subMesh Defines the sumesh to render
  108010. * @param batch Defines the batch of meshes in case of instances
  108011. * @param useOverlay Defines if the rendering is for the overlay or the outline
  108012. */
  108013. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  108014. var _this = this;
  108015. if (useOverlay === void 0) { useOverlay = false; }
  108016. var scene = this.scene;
  108017. var engine = scene.getEngine();
  108018. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  108019. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  108020. return;
  108021. }
  108022. var mesh = subMesh.getRenderingMesh();
  108023. var material = subMesh.getMaterial();
  108024. if (!material || !scene.activeCamera) {
  108025. return;
  108026. }
  108027. engine.enableEffect(this._effect);
  108028. // Logarithmic depth
  108029. if (material.useLogarithmicDepth) {
  108030. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  108031. }
  108032. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  108033. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  108034. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  108035. // Bones
  108036. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  108037. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  108038. }
  108039. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  108040. // Alpha test
  108041. if (material && material.needAlphaTesting()) {
  108042. var alphaTexture = material.getAlphaTestTexture();
  108043. if (alphaTexture) {
  108044. this._effect.setTexture("diffuseSampler", alphaTexture);
  108045. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  108046. }
  108047. }
  108048. engine.setZOffset(-this.zOffset);
  108049. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  108050. engine.setZOffset(0);
  108051. };
  108052. /**
  108053. * Returns whether or not the outline renderer is ready for a given submesh.
  108054. * All the dependencies e.g. submeshes, texture, effect... mus be ready
  108055. * @param subMesh Defines the submesh to check readyness for
  108056. * @param useInstances Defines wheter wee are trying to render instances or not
  108057. * @returns true if ready otherwise false
  108058. */
  108059. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  108060. var defines = [];
  108061. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  108062. var mesh = subMesh.getMesh();
  108063. var material = subMesh.getMaterial();
  108064. if (material) {
  108065. // Alpha test
  108066. if (material.needAlphaTesting()) {
  108067. defines.push("#define ALPHATEST");
  108068. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  108069. attribs.push(BABYLON.VertexBuffer.UVKind);
  108070. defines.push("#define UV1");
  108071. }
  108072. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  108073. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  108074. defines.push("#define UV2");
  108075. }
  108076. }
  108077. //Logarithmic depth
  108078. if (material.useLogarithmicDepth) {
  108079. defines.push("#define LOGARITHMICDEPTH");
  108080. }
  108081. }
  108082. // Bones
  108083. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  108084. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  108085. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  108086. if (mesh.numBoneInfluencers > 4) {
  108087. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  108088. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  108089. }
  108090. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  108091. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  108092. }
  108093. else {
  108094. defines.push("#define NUM_BONE_INFLUENCERS 0");
  108095. }
  108096. // Instances
  108097. if (useInstances) {
  108098. defines.push("#define INSTANCES");
  108099. attribs.push("world0");
  108100. attribs.push("world1");
  108101. attribs.push("world2");
  108102. attribs.push("world3");
  108103. }
  108104. // Get correct effect
  108105. var join = defines.join("\n");
  108106. if (this._cachedDefines !== join) {
  108107. this._cachedDefines = join;
  108108. this._effect = this.scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  108109. }
  108110. return this._effect.isReady();
  108111. };
  108112. OutlineRenderer.prototype._beforeRenderingMesh = function (mesh, subMesh, batch) {
  108113. // Outline - step 1
  108114. this._savedDepthWrite = this._engine.getDepthWrite();
  108115. if (mesh.renderOutline) {
  108116. this._engine.setDepthWrite(false);
  108117. this.render(subMesh, batch);
  108118. this._engine.setDepthWrite(this._savedDepthWrite);
  108119. }
  108120. };
  108121. OutlineRenderer.prototype._afterRenderingMesh = function (mesh, subMesh, batch) {
  108122. // Outline - step 2
  108123. if (mesh.renderOutline && this._savedDepthWrite) {
  108124. this._engine.setDepthWrite(true);
  108125. this._engine.setColorWrite(false);
  108126. this.render(subMesh, batch);
  108127. this._engine.setColorWrite(true);
  108128. }
  108129. // Overlay
  108130. if (mesh.renderOverlay) {
  108131. var currentMode = this._engine.getAlphaMode();
  108132. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108133. this.render(subMesh, batch, true);
  108134. this._engine.setAlphaMode(currentMode);
  108135. }
  108136. };
  108137. return OutlineRenderer;
  108138. }());
  108139. BABYLON.OutlineRenderer = OutlineRenderer;
  108140. })(BABYLON || (BABYLON = {}));
  108141. //# sourceMappingURL=babylon.outlineRenderer.js.map
  108142. var BABYLON;
  108143. (function (BABYLON) {
  108144. BABYLON.AbstractMesh.prototype.disableEdgesRendering = function () {
  108145. if (this._edgesRenderer) {
  108146. this._edgesRenderer.dispose();
  108147. this._edgesRenderer = null;
  108148. }
  108149. return this;
  108150. };
  108151. BABYLON.AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108152. if (epsilon === void 0) { epsilon = 0.95; }
  108153. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108154. this.disableEdgesRendering();
  108155. this._edgesRenderer = new EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108156. return this;
  108157. };
  108158. Object.defineProperty(BABYLON.AbstractMesh.prototype, "edgesRenderer", {
  108159. get: function () {
  108160. return this._edgesRenderer;
  108161. },
  108162. enumerable: true,
  108163. configurable: true
  108164. });
  108165. BABYLON.LinesMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  108166. if (epsilon === void 0) { epsilon = 0.95; }
  108167. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108168. this.disableEdgesRendering();
  108169. this._edgesRenderer = new BABYLON.LineEdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  108170. return this;
  108171. };
  108172. /**
  108173. * FaceAdjacencies Helper class to generate edges
  108174. */
  108175. var FaceAdjacencies = /** @class */ (function () {
  108176. function FaceAdjacencies() {
  108177. this.edges = new Array();
  108178. this.edgesConnectedCount = 0;
  108179. }
  108180. return FaceAdjacencies;
  108181. }());
  108182. /**
  108183. * This class is used to generate edges of the mesh that could then easily be rendered in a scene.
  108184. */
  108185. var EdgesRenderer = /** @class */ (function () {
  108186. /**
  108187. * Creates an instance of the EdgesRenderer. It is primarily use to display edges of a mesh.
  108188. * Beware when you use this class with complex objects as the adjacencies computation can be really long
  108189. * @param source Mesh used to create edges
  108190. * @param epsilon sum of angles in adjacency to check for edge
  108191. * @param checkVerticesInsteadOfIndices
  108192. * @param generateEdgesLines - should generate Lines or only prepare resources.
  108193. */
  108194. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices, generateEdgesLines) {
  108195. if (epsilon === void 0) { epsilon = 0.95; }
  108196. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108197. if (generateEdgesLines === void 0) { generateEdgesLines = true; }
  108198. var _this = this;
  108199. /**
  108200. * Define the size of the edges with an orthographic camera
  108201. */
  108202. this.edgesWidthScalerForOrthographic = 1000.0;
  108203. /**
  108204. * Define the size of the edges with a perspective camera
  108205. */
  108206. this.edgesWidthScalerForPerspective = 50.0;
  108207. this._linesPositions = new Array();
  108208. this._linesNormals = new Array();
  108209. this._linesIndices = new Array();
  108210. this._buffers = {};
  108211. this._checkVerticesInsteadOfIndices = false;
  108212. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  108213. this.isEnabled = true;
  108214. this._source = source;
  108215. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  108216. this._epsilon = epsilon;
  108217. this._prepareRessources();
  108218. if (generateEdgesLines) {
  108219. this._generateEdgesLines();
  108220. }
  108221. this._meshRebuildObserver = this._source.onRebuildObservable.add(function () {
  108222. _this._rebuild();
  108223. });
  108224. this._meshDisposeObserver = this._source.onDisposeObservable.add(function () {
  108225. _this.dispose();
  108226. });
  108227. }
  108228. EdgesRenderer.prototype._prepareRessources = function () {
  108229. if (this._lineShader) {
  108230. return;
  108231. }
  108232. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  108233. attributes: ["position", "normal"],
  108234. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  108235. });
  108236. this._lineShader.disableDepthWrite = true;
  108237. this._lineShader.backFaceCulling = false;
  108238. };
  108239. /** @hidden */
  108240. EdgesRenderer.prototype._rebuild = function () {
  108241. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108242. if (buffer) {
  108243. buffer._rebuild();
  108244. }
  108245. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108246. if (buffer) {
  108247. buffer._rebuild();
  108248. }
  108249. var scene = this._source.getScene();
  108250. var engine = scene.getEngine();
  108251. this._ib = engine.createIndexBuffer(this._linesIndices);
  108252. };
  108253. /**
  108254. * Releases the required resources for the edges renderer
  108255. */
  108256. EdgesRenderer.prototype.dispose = function () {
  108257. this._source.onRebuildObservable.remove(this._meshRebuildObserver);
  108258. this._source.onDisposeObservable.remove(this._meshDisposeObserver);
  108259. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  108260. if (buffer) {
  108261. buffer.dispose();
  108262. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  108263. }
  108264. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  108265. if (buffer) {
  108266. buffer.dispose();
  108267. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  108268. }
  108269. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  108270. this._lineShader.dispose();
  108271. };
  108272. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  108273. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  108274. return 0;
  108275. }
  108276. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  108277. return 1;
  108278. }
  108279. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  108280. return 2;
  108281. }
  108282. return -1;
  108283. };
  108284. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  108285. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  108286. return 0;
  108287. }
  108288. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  108289. return 1;
  108290. }
  108291. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  108292. return 2;
  108293. }
  108294. return -1;
  108295. };
  108296. /**
  108297. * Checks if the pair of p0 and p1 is en edge
  108298. * @param faceIndex
  108299. * @param edge
  108300. * @param faceNormals
  108301. * @param p0
  108302. * @param p1
  108303. * @private
  108304. */
  108305. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108306. var needToCreateLine;
  108307. if (edge === undefined) {
  108308. needToCreateLine = true;
  108309. }
  108310. else {
  108311. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  108312. needToCreateLine = dotProduct < this._epsilon;
  108313. }
  108314. if (needToCreateLine) {
  108315. var offset = this._linesPositions.length / 3;
  108316. var normal = p0.subtract(p1);
  108317. normal.normalize();
  108318. // Positions
  108319. this._linesPositions.push(p0.x);
  108320. this._linesPositions.push(p0.y);
  108321. this._linesPositions.push(p0.z);
  108322. this._linesPositions.push(p0.x);
  108323. this._linesPositions.push(p0.y);
  108324. this._linesPositions.push(p0.z);
  108325. this._linesPositions.push(p1.x);
  108326. this._linesPositions.push(p1.y);
  108327. this._linesPositions.push(p1.z);
  108328. this._linesPositions.push(p1.x);
  108329. this._linesPositions.push(p1.y);
  108330. this._linesPositions.push(p1.z);
  108331. // Normals
  108332. this._linesNormals.push(p1.x);
  108333. this._linesNormals.push(p1.y);
  108334. this._linesNormals.push(p1.z);
  108335. this._linesNormals.push(-1);
  108336. this._linesNormals.push(p1.x);
  108337. this._linesNormals.push(p1.y);
  108338. this._linesNormals.push(p1.z);
  108339. this._linesNormals.push(1);
  108340. this._linesNormals.push(p0.x);
  108341. this._linesNormals.push(p0.y);
  108342. this._linesNormals.push(p0.z);
  108343. this._linesNormals.push(-1);
  108344. this._linesNormals.push(p0.x);
  108345. this._linesNormals.push(p0.y);
  108346. this._linesNormals.push(p0.z);
  108347. this._linesNormals.push(1);
  108348. // Indices
  108349. this._linesIndices.push(offset);
  108350. this._linesIndices.push(offset + 1);
  108351. this._linesIndices.push(offset + 2);
  108352. this._linesIndices.push(offset);
  108353. this._linesIndices.push(offset + 2);
  108354. this._linesIndices.push(offset + 3);
  108355. }
  108356. };
  108357. /**
  108358. * Generates lines edges from adjacencjes
  108359. * @private
  108360. */
  108361. EdgesRenderer.prototype._generateEdgesLines = function () {
  108362. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108363. var indices = this._source.getIndices();
  108364. if (!indices || !positions) {
  108365. return;
  108366. }
  108367. // First let's find adjacencies
  108368. var adjacencies = new Array();
  108369. var faceNormals = new Array();
  108370. var index;
  108371. var faceAdjacencies;
  108372. // Prepare faces
  108373. for (index = 0; index < indices.length; index += 3) {
  108374. faceAdjacencies = new FaceAdjacencies();
  108375. var p0Index = indices[index];
  108376. var p1Index = indices[index + 1];
  108377. var p2Index = indices[index + 2];
  108378. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  108379. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  108380. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  108381. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  108382. faceNormal.normalize();
  108383. faceNormals.push(faceNormal);
  108384. adjacencies.push(faceAdjacencies);
  108385. }
  108386. // Scan
  108387. for (index = 0; index < adjacencies.length; index++) {
  108388. faceAdjacencies = adjacencies[index];
  108389. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  108390. var otherFaceAdjacencies = adjacencies[otherIndex];
  108391. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  108392. break;
  108393. }
  108394. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  108395. continue;
  108396. }
  108397. var otherP0 = indices[otherIndex * 3];
  108398. var otherP1 = indices[otherIndex * 3 + 1];
  108399. var otherP2 = indices[otherIndex * 3 + 2];
  108400. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  108401. var otherEdgeIndex = 0;
  108402. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  108403. continue;
  108404. }
  108405. switch (edgeIndex) {
  108406. case 0:
  108407. if (this._checkVerticesInsteadOfIndices) {
  108408. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108409. }
  108410. else {
  108411. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  108412. }
  108413. break;
  108414. case 1:
  108415. if (this._checkVerticesInsteadOfIndices) {
  108416. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108417. }
  108418. else {
  108419. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  108420. }
  108421. break;
  108422. case 2:
  108423. if (this._checkVerticesInsteadOfIndices) {
  108424. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  108425. }
  108426. else {
  108427. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  108428. }
  108429. break;
  108430. }
  108431. if (otherEdgeIndex === -1) {
  108432. continue;
  108433. }
  108434. faceAdjacencies.edges[edgeIndex] = otherIndex;
  108435. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  108436. faceAdjacencies.edgesConnectedCount++;
  108437. otherFaceAdjacencies.edgesConnectedCount++;
  108438. if (faceAdjacencies.edgesConnectedCount === 3) {
  108439. break;
  108440. }
  108441. }
  108442. }
  108443. }
  108444. // Create lines
  108445. for (index = 0; index < adjacencies.length; index++) {
  108446. // 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
  108447. var current = adjacencies[index];
  108448. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108449. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  108450. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  108451. }
  108452. // Merge into a single mesh
  108453. var engine = this._source.getScene().getEngine();
  108454. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108455. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108456. this._ib = engine.createIndexBuffer(this._linesIndices);
  108457. this._indicesCount = this._linesIndices.length;
  108458. };
  108459. /**
  108460. * Checks wether or not the edges renderer is ready to render.
  108461. * @return true if ready, otherwise false.
  108462. */
  108463. EdgesRenderer.prototype.isReady = function () {
  108464. return this._lineShader.isReady();
  108465. };
  108466. /**
  108467. * Renders the edges of the attached mesh,
  108468. */
  108469. EdgesRenderer.prototype.render = function () {
  108470. var scene = this._source.getScene();
  108471. if (!this.isReady() || !scene.activeCamera) {
  108472. return;
  108473. }
  108474. var engine = scene.getEngine();
  108475. this._lineShader._preBind();
  108476. if (this._source.edgesColor.a !== 1) {
  108477. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  108478. }
  108479. else {
  108480. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  108481. }
  108482. // VBOs
  108483. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  108484. scene.resetCachedMaterial();
  108485. this._lineShader.setColor4("color", this._source.edgesColor);
  108486. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  108487. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  108488. }
  108489. else {
  108490. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  108491. }
  108492. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  108493. this._lineShader.bind(this._source.getWorldMatrix());
  108494. // Draw order
  108495. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  108496. this._lineShader.unbind();
  108497. };
  108498. return EdgesRenderer;
  108499. }());
  108500. BABYLON.EdgesRenderer = EdgesRenderer;
  108501. })(BABYLON || (BABYLON = {}));
  108502. //# sourceMappingURL=babylon.edgesRenderer.js.map
  108503. var BABYLON;
  108504. (function (BABYLON) {
  108505. /**
  108506. * FaceAdjacencies Helper class to generate edges
  108507. */
  108508. var FaceAdjacencies = /** @class */ (function () {
  108509. function FaceAdjacencies() {
  108510. this.edges = new Array();
  108511. this.edgesConnectedCount = 0;
  108512. }
  108513. return FaceAdjacencies;
  108514. }());
  108515. /**
  108516. * LineEdgesRenderer for LineMeshes to remove unnecessary triangulation
  108517. */
  108518. var LineEdgesRenderer = /** @class */ (function (_super) {
  108519. __extends(LineEdgesRenderer, _super);
  108520. /**
  108521. * This constructor turns off auto generating edges line in Edges Renderer to make it here.
  108522. * @param source LineMesh used to generate edges
  108523. * @param epsilon not important (specified angle for edge detection)
  108524. * @param checkVerticesInsteadOfIndices not important for LineMesh
  108525. */
  108526. function LineEdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  108527. if (epsilon === void 0) { epsilon = 0.95; }
  108528. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  108529. var _this = _super.call(this, source, epsilon, checkVerticesInsteadOfIndices, false) || this;
  108530. _this._generateEdgesLines();
  108531. return _this;
  108532. }
  108533. /**
  108534. * Always create the edge since its a line so only important things are p0 and p1
  108535. * @param faceIndex not important for LineMesh
  108536. * @param edge not important for LineMesh
  108537. * @param faceNormals not important for LineMesh
  108538. * @param p0 beginnig of line
  108539. * @param p1 end of line
  108540. */
  108541. LineEdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  108542. var offset = this._linesPositions.length / 3;
  108543. var normal = p0.subtract(p1);
  108544. normal.normalize();
  108545. // Positions
  108546. this._linesPositions.push(p0.x);
  108547. this._linesPositions.push(p0.y);
  108548. this._linesPositions.push(p0.z);
  108549. this._linesPositions.push(p0.x);
  108550. this._linesPositions.push(p0.y);
  108551. this._linesPositions.push(p0.z);
  108552. this._linesPositions.push(p1.x);
  108553. this._linesPositions.push(p1.y);
  108554. this._linesPositions.push(p1.z);
  108555. this._linesPositions.push(p1.x);
  108556. this._linesPositions.push(p1.y);
  108557. this._linesPositions.push(p1.z);
  108558. // Normals
  108559. this._linesNormals.push(p1.x);
  108560. this._linesNormals.push(p1.y);
  108561. this._linesNormals.push(p1.z);
  108562. this._linesNormals.push(-1);
  108563. this._linesNormals.push(p1.x);
  108564. this._linesNormals.push(p1.y);
  108565. this._linesNormals.push(p1.z);
  108566. this._linesNormals.push(1);
  108567. this._linesNormals.push(p0.x);
  108568. this._linesNormals.push(p0.y);
  108569. this._linesNormals.push(p0.z);
  108570. this._linesNormals.push(-1);
  108571. this._linesNormals.push(p0.x);
  108572. this._linesNormals.push(p0.y);
  108573. this._linesNormals.push(p0.z);
  108574. this._linesNormals.push(1);
  108575. // Indices
  108576. this._linesIndices.push(offset);
  108577. this._linesIndices.push(offset + 1);
  108578. this._linesIndices.push(offset + 2);
  108579. this._linesIndices.push(offset);
  108580. this._linesIndices.push(offset + 2);
  108581. this._linesIndices.push(offset + 3);
  108582. };
  108583. /**
  108584. * Generate edges for each line in LinesMesh. Every Line should be rendered as edge.
  108585. */
  108586. LineEdgesRenderer.prototype._generateEdgesLines = function () {
  108587. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  108588. var indices = this._source.getIndices();
  108589. if (!indices || !positions) {
  108590. return;
  108591. }
  108592. // First let's find adjacencies
  108593. var adjacencies = new Array();
  108594. var faceNormals = new Array();
  108595. var index;
  108596. for (var i = 0; i < (positions.length / 3) - 1; i++) {
  108597. var currentAdjecancy = new FaceAdjacencies();
  108598. currentAdjecancy.p0 = new BABYLON.Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]);
  108599. currentAdjecancy.p1 = new BABYLON.Vector3(positions[(i + 1) * 3], positions[(i + 1) * 3 + 1], positions[(i + 1) * 3 + 2]);
  108600. adjacencies.push(currentAdjecancy);
  108601. }
  108602. // Create lines
  108603. for (index = 0; index < adjacencies.length; index++) {
  108604. // 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
  108605. var current = adjacencies[index];
  108606. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  108607. }
  108608. // Merge into a single mesh
  108609. var engine = this._source.getScene().getEngine();
  108610. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  108611. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  108612. this._ib = engine.createIndexBuffer(this._linesIndices);
  108613. this._indicesCount = this._linesIndices.length;
  108614. };
  108615. return LineEdgesRenderer;
  108616. }(BABYLON.EdgesRenderer));
  108617. BABYLON.LineEdgesRenderer = LineEdgesRenderer;
  108618. })(BABYLON || (BABYLON = {}));
  108619. //# sourceMappingURL=babylon.lineEdgesRenderer.js.map
  108620. var BABYLON;
  108621. (function (BABYLON) {
  108622. // Adds the parser to the scene parsers.
  108623. BABYLON.AbstractScene.AddParser(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER, function (parsedData, scene, container, rootUrl) {
  108624. if (parsedData.effectLayers) {
  108625. if (!container.effectLayers) {
  108626. container.effectLayers = new Array();
  108627. }
  108628. for (var index = 0; index < parsedData.effectLayers.length; index++) {
  108629. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  108630. container.effectLayers.push(effectLayer);
  108631. }
  108632. }
  108633. });
  108634. BABYLON.AbstractScene.prototype.removeEffectLayer = function (toRemove) {
  108635. var index = this.effectLayers.indexOf(toRemove);
  108636. if (index !== -1) {
  108637. this.effectLayers.splice(index, 1);
  108638. }
  108639. return index;
  108640. };
  108641. BABYLON.AbstractScene.prototype.addEffectLayer = function (newEffectLayer) {
  108642. this.effectLayers.push(newEffectLayer);
  108643. };
  108644. /**
  108645. * Defines the layer scene component responsible to manage any effect layers
  108646. * in a given scene.
  108647. */
  108648. var EffectLayerSceneComponent = /** @class */ (function () {
  108649. /**
  108650. * Creates a new instance of the component for the given scene
  108651. * @param scene Defines the scene to register the component in
  108652. */
  108653. function EffectLayerSceneComponent(scene) {
  108654. /**
  108655. * The component name helpfull to identify the component in the list of scene components.
  108656. */
  108657. this.name = BABYLON.SceneComponentConstants.NAME_EFFECTLAYER;
  108658. this._renderEffects = false;
  108659. this._needStencil = false;
  108660. this._previousStencilState = false;
  108661. this.scene = scene;
  108662. this._engine = scene.getEngine();
  108663. scene.effectLayers = new Array();
  108664. }
  108665. /**
  108666. * Registers the component in a given scene
  108667. */
  108668. EffectLayerSceneComponent.prototype.register = function () {
  108669. this.scene._isReadyForMeshStage.registerStep(BABYLON.SceneComponentConstants.STEP_ISREADYFORMESH_EFFECTLAYER, this, this._isReadyForMesh);
  108670. this.scene._cameraDrawRenderTargetStage.registerStep(BABYLON.SceneComponentConstants.STEP_CAMERADRAWRENDERTARGET_EFFECTLAYER, this, this._renderMainTexture);
  108671. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_EFFECTLAYER, this, this._setStencil);
  108672. this.scene._afterRenderingGroupDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERRENDERINGGROUPDRAW_EFFECTLAYER_DRAW, this, this._drawRenderingGroup);
  108673. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER, this, this._setStencilBack);
  108674. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_EFFECTLAYER_DRAW, this, this._drawCamera);
  108675. };
  108676. /**
  108677. * Rebuilds the elements related to this component in case of
  108678. * context lost for instance.
  108679. */
  108680. EffectLayerSceneComponent.prototype.rebuild = function () {
  108681. var layers = this.scene.effectLayers;
  108682. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  108683. var effectLayer = layers_1[_i];
  108684. effectLayer._rebuild();
  108685. }
  108686. };
  108687. /**
  108688. * Serializes the component data to the specified json object
  108689. * @param serializationObject The object to serialize to
  108690. */
  108691. EffectLayerSceneComponent.prototype.serialize = function (serializationObject) {
  108692. // Effect layers
  108693. serializationObject.effectLayers = [];
  108694. var layers = this.scene.effectLayers;
  108695. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  108696. var effectLayer = layers_2[_i];
  108697. if (effectLayer.serialize) {
  108698. serializationObject.effectLayers.push(effectLayer.serialize());
  108699. }
  108700. }
  108701. };
  108702. /**
  108703. * Adds all the element from the container to the scene
  108704. * @param container the container holding the elements
  108705. */
  108706. EffectLayerSceneComponent.prototype.addFromContainer = function (container) {
  108707. var _this = this;
  108708. if (!container.effectLayers) {
  108709. return;
  108710. }
  108711. container.effectLayers.forEach(function (o) {
  108712. _this.scene.addEffectLayer(o);
  108713. });
  108714. };
  108715. /**
  108716. * Removes all the elements in the container from the scene
  108717. * @param container contains the elements to remove
  108718. */
  108719. EffectLayerSceneComponent.prototype.removeFromContainer = function (container) {
  108720. var _this = this;
  108721. if (!container.effectLayers) {
  108722. return;
  108723. }
  108724. container.effectLayers.forEach(function (o) {
  108725. _this.scene.removeEffectLayer(o);
  108726. });
  108727. };
  108728. /**
  108729. * Disposes the component and the associated ressources.
  108730. */
  108731. EffectLayerSceneComponent.prototype.dispose = function () {
  108732. var layers = this.scene.effectLayers;
  108733. while (layers.length) {
  108734. layers[0].dispose();
  108735. }
  108736. };
  108737. EffectLayerSceneComponent.prototype._isReadyForMesh = function (mesh, hardwareInstancedRendering) {
  108738. var layers = this.scene.effectLayers;
  108739. for (var _i = 0, layers_3 = layers; _i < layers_3.length; _i++) {
  108740. var layer = layers_3[_i];
  108741. if (!layer.hasMesh(mesh)) {
  108742. continue;
  108743. }
  108744. for (var _a = 0, _b = mesh.subMeshes; _a < _b.length; _a++) {
  108745. var subMesh = _b[_a];
  108746. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  108747. return false;
  108748. }
  108749. }
  108750. }
  108751. return true;
  108752. };
  108753. EffectLayerSceneComponent.prototype._renderMainTexture = function (camera) {
  108754. this._renderEffects = false;
  108755. this._needStencil = false;
  108756. var layers = this.scene.effectLayers;
  108757. if (layers && layers.length > 0) {
  108758. this._previousStencilState = this._engine.getStencilBuffer();
  108759. for (var _i = 0, layers_4 = layers; _i < layers_4.length; _i++) {
  108760. var effectLayer = layers_4[_i];
  108761. if (effectLayer.shouldRender() &&
  108762. (!effectLayer.camera ||
  108763. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  108764. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  108765. this._renderEffects = true;
  108766. this._needStencil = this._needStencil || effectLayer.needStencil();
  108767. var renderTarget = effectLayer._mainTexture;
  108768. if (renderTarget._shouldRender()) {
  108769. this.scene.incrementRenderId();
  108770. renderTarget.render(false, false);
  108771. }
  108772. }
  108773. }
  108774. this.scene.incrementRenderId();
  108775. }
  108776. };
  108777. EffectLayerSceneComponent.prototype._setStencil = function (camera) {
  108778. // Activate effect Layer stencil
  108779. if (this._needStencil) {
  108780. this._engine.setStencilBuffer(true);
  108781. }
  108782. };
  108783. EffectLayerSceneComponent.prototype._setStencilBack = function (camera) {
  108784. // Restore effect Layer stencil
  108785. if (this._needStencil) {
  108786. this._engine.setStencilBuffer(this._previousStencilState);
  108787. }
  108788. };
  108789. EffectLayerSceneComponent.prototype._draw = function (renderingGroupId) {
  108790. if (this._renderEffects) {
  108791. this._engine.setDepthBuffer(false);
  108792. var layers = this.scene.effectLayers;
  108793. for (var i = 0; i < layers.length; i++) {
  108794. var effectLayer = layers[i];
  108795. if (effectLayer.renderingGroupId === renderingGroupId) {
  108796. if (effectLayer.shouldRender()) {
  108797. effectLayer.render();
  108798. }
  108799. }
  108800. }
  108801. this._engine.setDepthBuffer(true);
  108802. }
  108803. };
  108804. EffectLayerSceneComponent.prototype._drawCamera = function (camera) {
  108805. if (this._renderEffects) {
  108806. this._draw(-1);
  108807. }
  108808. };
  108809. EffectLayerSceneComponent.prototype._drawRenderingGroup = function (index) {
  108810. if (!this.scene._isInIntermediateRendering() && this._renderEffects) {
  108811. this._draw(index);
  108812. }
  108813. };
  108814. return EffectLayerSceneComponent;
  108815. }());
  108816. BABYLON.EffectLayerSceneComponent = EffectLayerSceneComponent;
  108817. })(BABYLON || (BABYLON = {}));
  108818. //# sourceMappingURL=babylon.effectLayerSceneComponent.js.map
  108819. var __assign = (this && this.__assign) || function () {
  108820. __assign = Object.assign || function(t) {
  108821. for (var s, i = 1, n = arguments.length; i < n; i++) {
  108822. s = arguments[i];
  108823. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  108824. t[p] = s[p];
  108825. }
  108826. return t;
  108827. };
  108828. return __assign.apply(this, arguments);
  108829. };
  108830. var BABYLON;
  108831. (function (BABYLON) {
  108832. /**
  108833. * The effect layer Helps adding post process effect blended with the main pass.
  108834. *
  108835. * This can be for instance use to generate glow or higlight effects on the scene.
  108836. *
  108837. * The effect layer class can not be used directly and is intented to inherited from to be
  108838. * customized per effects.
  108839. */
  108840. var EffectLayer = /** @class */ (function () {
  108841. /**
  108842. * Instantiates a new effect Layer and references it in the scene.
  108843. * @param name The name of the layer
  108844. * @param scene The scene to use the layer in
  108845. */
  108846. function EffectLayer(
  108847. /** The Friendly of the effect in the scene */
  108848. name, scene) {
  108849. this._vertexBuffers = {};
  108850. this._maxSize = 0;
  108851. this._mainTextureDesiredSize = { width: 0, height: 0 };
  108852. this._shouldRender = true;
  108853. this._postProcesses = [];
  108854. this._textures = [];
  108855. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  108856. /**
  108857. * The clear color of the texture used to generate the glow map.
  108858. */
  108859. this.neutralColor = new BABYLON.Color4();
  108860. /**
  108861. * Specifies wether the highlight layer is enabled or not.
  108862. */
  108863. this.isEnabled = true;
  108864. /**
  108865. * An event triggered when the effect layer has been disposed.
  108866. */
  108867. this.onDisposeObservable = new BABYLON.Observable();
  108868. /**
  108869. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  108870. */
  108871. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  108872. /**
  108873. * An event triggered when the generated texture is being merged in the scene.
  108874. */
  108875. this.onBeforeComposeObservable = new BABYLON.Observable();
  108876. /**
  108877. * An event triggered when the generated texture has been merged in the scene.
  108878. */
  108879. this.onAfterComposeObservable = new BABYLON.Observable();
  108880. /**
  108881. * An event triggered when the efffect layer changes its size.
  108882. */
  108883. this.onSizeChangedObservable = new BABYLON.Observable();
  108884. this.name = name;
  108885. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  108886. var component = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_EFFECTLAYER);
  108887. if (!component) {
  108888. component = new BABYLON.EffectLayerSceneComponent(this._scene);
  108889. this._scene._addComponent(component);
  108890. }
  108891. this._engine = this._scene.getEngine();
  108892. this._maxSize = this._engine.getCaps().maxTextureSize;
  108893. this._scene.effectLayers.push(this);
  108894. // Generate Buffers
  108895. this._generateIndexBuffer();
  108896. this._genrateVertexBuffer();
  108897. }
  108898. Object.defineProperty(EffectLayer.prototype, "camera", {
  108899. /**
  108900. * Gets the camera attached to the layer.
  108901. */
  108902. get: function () {
  108903. return this._effectLayerOptions.camera;
  108904. },
  108905. enumerable: true,
  108906. configurable: true
  108907. });
  108908. Object.defineProperty(EffectLayer.prototype, "renderingGroupId", {
  108909. /**
  108910. * Gets the rendering group id the layer should render in.
  108911. */
  108912. get: function () {
  108913. return this._effectLayerOptions.renderingGroupId;
  108914. },
  108915. enumerable: true,
  108916. configurable: true
  108917. });
  108918. /**
  108919. * Initializes the effect layer with the required options.
  108920. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  108921. */
  108922. EffectLayer.prototype._init = function (options) {
  108923. // Adapt options
  108924. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null, renderingGroupId: -1 }, options);
  108925. this._setMainTextureSize();
  108926. this._createMainTexture();
  108927. this._createTextureAndPostProcesses();
  108928. this._mergeEffect = this._createMergeEffect();
  108929. };
  108930. /**
  108931. * Generates the index buffer of the full screen quad blending to the main canvas.
  108932. */
  108933. EffectLayer.prototype._generateIndexBuffer = function () {
  108934. // Indices
  108935. var indices = [];
  108936. indices.push(0);
  108937. indices.push(1);
  108938. indices.push(2);
  108939. indices.push(0);
  108940. indices.push(2);
  108941. indices.push(3);
  108942. this._indexBuffer = this._engine.createIndexBuffer(indices);
  108943. };
  108944. /**
  108945. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  108946. */
  108947. EffectLayer.prototype._genrateVertexBuffer = function () {
  108948. // VBO
  108949. var vertices = [];
  108950. vertices.push(1, 1);
  108951. vertices.push(-1, 1);
  108952. vertices.push(-1, -1);
  108953. vertices.push(1, -1);
  108954. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  108955. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  108956. };
  108957. /**
  108958. * Sets the main texture desired size which is the closest power of two
  108959. * of the engine canvas size.
  108960. */
  108961. EffectLayer.prototype._setMainTextureSize = function () {
  108962. if (this._effectLayerOptions.mainTextureFixedSize) {
  108963. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  108964. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  108965. }
  108966. else {
  108967. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  108968. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  108969. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  108970. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  108971. }
  108972. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  108973. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  108974. };
  108975. /**
  108976. * Creates the main texture for the effect layer.
  108977. */
  108978. EffectLayer.prototype._createMainTexture = function () {
  108979. var _this = this;
  108980. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  108981. width: this._mainTextureDesiredSize.width,
  108982. height: this._mainTextureDesiredSize.height
  108983. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  108984. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  108985. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108986. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  108987. this._mainTexture.anisotropicFilteringLevel = 1;
  108988. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  108989. this._mainTexture.renderParticles = false;
  108990. this._mainTexture.renderList = null;
  108991. this._mainTexture.ignoreCameraViewport = true;
  108992. // Custom render function
  108993. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  108994. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  108995. var index;
  108996. var engine = _this._scene.getEngine();
  108997. if (depthOnlySubMeshes.length) {
  108998. engine.setColorWrite(false);
  108999. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  109000. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  109001. }
  109002. engine.setColorWrite(true);
  109003. }
  109004. for (index = 0; index < opaqueSubMeshes.length; index++) {
  109005. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  109006. }
  109007. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  109008. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  109009. }
  109010. for (index = 0; index < transparentSubMeshes.length; index++) {
  109011. _this._renderSubMesh(transparentSubMeshes.data[index]);
  109012. }
  109013. };
  109014. this._mainTexture.onClearObservable.add(function (engine) {
  109015. engine.clear(_this.neutralColor, true, true, true);
  109016. });
  109017. };
  109018. /**
  109019. * Checks for the readiness of the element composing the layer.
  109020. * @param subMesh the mesh to check for
  109021. * @param useInstances specify wether or not to use instances to render the mesh
  109022. * @param emissiveTexture the associated emissive texture used to generate the glow
  109023. * @return true if ready otherwise, false
  109024. */
  109025. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  109026. var material = subMesh.getMaterial();
  109027. if (!material) {
  109028. return false;
  109029. }
  109030. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  109031. return false;
  109032. }
  109033. var defines = [];
  109034. var attribs = [BABYLON.VertexBuffer.PositionKind];
  109035. var mesh = subMesh.getMesh();
  109036. var uv1 = false;
  109037. var uv2 = false;
  109038. // Alpha test
  109039. if (material && material.needAlphaTesting()) {
  109040. var alphaTexture = material.getAlphaTestTexture();
  109041. if (alphaTexture) {
  109042. defines.push("#define ALPHATEST");
  109043. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109044. alphaTexture.coordinatesIndex === 1) {
  109045. defines.push("#define DIFFUSEUV2");
  109046. uv2 = true;
  109047. }
  109048. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109049. defines.push("#define DIFFUSEUV1");
  109050. uv1 = true;
  109051. }
  109052. }
  109053. }
  109054. // Emissive
  109055. if (emissiveTexture) {
  109056. defines.push("#define EMISSIVE");
  109057. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  109058. emissiveTexture.coordinatesIndex === 1) {
  109059. defines.push("#define EMISSIVEUV2");
  109060. uv2 = true;
  109061. }
  109062. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  109063. defines.push("#define EMISSIVEUV1");
  109064. uv1 = true;
  109065. }
  109066. }
  109067. if (uv1) {
  109068. attribs.push(BABYLON.VertexBuffer.UVKind);
  109069. defines.push("#define UV1");
  109070. }
  109071. if (uv2) {
  109072. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  109073. defines.push("#define UV2");
  109074. }
  109075. // Bones
  109076. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  109077. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  109078. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  109079. if (mesh.numBoneInfluencers > 4) {
  109080. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  109081. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  109082. }
  109083. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  109084. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  109085. }
  109086. else {
  109087. defines.push("#define NUM_BONE_INFLUENCERS 0");
  109088. }
  109089. // Morph targets
  109090. var manager = mesh.morphTargetManager;
  109091. var morphInfluencers = 0;
  109092. if (manager) {
  109093. if (manager.numInfluencers > 0) {
  109094. defines.push("#define MORPHTARGETS");
  109095. morphInfluencers = manager.numInfluencers;
  109096. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  109097. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  109098. }
  109099. }
  109100. // Instances
  109101. if (useInstances) {
  109102. defines.push("#define INSTANCES");
  109103. attribs.push("world0");
  109104. attribs.push("world1");
  109105. attribs.push("world2");
  109106. attribs.push("world3");
  109107. }
  109108. // Get correct effect
  109109. var join = defines.join("\n");
  109110. if (this._cachedDefines !== join) {
  109111. this._cachedDefines = join;
  109112. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  109113. }
  109114. return this._effectLayerMapGenerationEffect.isReady();
  109115. };
  109116. /**
  109117. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  109118. */
  109119. EffectLayer.prototype.render = function () {
  109120. var currentEffect = this._mergeEffect;
  109121. // Check
  109122. if (!currentEffect.isReady())
  109123. return;
  109124. for (var i = 0; i < this._postProcesses.length; i++) {
  109125. if (!this._postProcesses[i].isReady()) {
  109126. return;
  109127. }
  109128. }
  109129. var engine = this._scene.getEngine();
  109130. this.onBeforeComposeObservable.notifyObservers(this);
  109131. // Render
  109132. engine.enableEffect(currentEffect);
  109133. engine.setState(false);
  109134. // VBOs
  109135. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  109136. // Cache
  109137. var previousAlphaMode = engine.getAlphaMode();
  109138. // Go Blend.
  109139. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  109140. // Blends the map on the main canvas.
  109141. this._internalRender(currentEffect);
  109142. // Restore Alpha
  109143. engine.setAlphaMode(previousAlphaMode);
  109144. this.onAfterComposeObservable.notifyObservers(this);
  109145. // Handle size changes.
  109146. var size = this._mainTexture.getSize();
  109147. this._setMainTextureSize();
  109148. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  109149. // Recreate RTT and post processes on size change.
  109150. this.onSizeChangedObservable.notifyObservers(this);
  109151. this._disposeTextureAndPostProcesses();
  109152. this._createMainTexture();
  109153. this._createTextureAndPostProcesses();
  109154. }
  109155. };
  109156. /**
  109157. * Determine if a given mesh will be used in the current effect.
  109158. * @param mesh mesh to test
  109159. * @returns true if the mesh will be used
  109160. */
  109161. EffectLayer.prototype.hasMesh = function (mesh) {
  109162. if (this.renderingGroupId === -1 || mesh.renderingGroupId === this.renderingGroupId) {
  109163. return true;
  109164. }
  109165. return false;
  109166. };
  109167. /**
  109168. * Returns true if the layer contains information to display, otherwise false.
  109169. * @returns true if the glow layer should be rendered
  109170. */
  109171. EffectLayer.prototype.shouldRender = function () {
  109172. return this.isEnabled && this._shouldRender;
  109173. };
  109174. /**
  109175. * Returns true if the mesh should render, otherwise false.
  109176. * @param mesh The mesh to render
  109177. * @returns true if it should render otherwise false
  109178. */
  109179. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  109180. return true;
  109181. };
  109182. /**
  109183. * Returns true if the mesh should render, otherwise false.
  109184. * @param mesh The mesh to render
  109185. * @returns true if it should render otherwise false
  109186. */
  109187. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  109188. return true;
  109189. };
  109190. /**
  109191. * Renders the submesh passed in parameter to the generation map.
  109192. */
  109193. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  109194. var _this = this;
  109195. if (!this.shouldRender()) {
  109196. return;
  109197. }
  109198. var material = subMesh.getMaterial();
  109199. var mesh = subMesh.getRenderingMesh();
  109200. var scene = this._scene;
  109201. var engine = scene.getEngine();
  109202. if (!material) {
  109203. return;
  109204. }
  109205. // Do not block in blend mode.
  109206. if (material.needAlphaBlendingForMesh(mesh)) {
  109207. return;
  109208. }
  109209. // Culling
  109210. engine.setState(material.backFaceCulling);
  109211. // Managing instances
  109212. var batch = mesh._getInstancesRenderList(subMesh._id);
  109213. if (batch.mustReturn) {
  109214. return;
  109215. }
  109216. // Early Exit per mesh
  109217. if (!this._shouldRenderMesh(mesh)) {
  109218. return;
  109219. }
  109220. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  109221. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  109222. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  109223. engine.enableEffect(this._effectLayerMapGenerationEffect);
  109224. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  109225. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  109226. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  109227. // Alpha test
  109228. if (material && material.needAlphaTesting()) {
  109229. var alphaTexture = material.getAlphaTestTexture();
  109230. if (alphaTexture) {
  109231. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  109232. var textureMatrix = alphaTexture.getTextureMatrix();
  109233. if (textureMatrix) {
  109234. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  109235. }
  109236. }
  109237. }
  109238. // Glow emissive only
  109239. if (this._emissiveTextureAndColor.texture) {
  109240. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  109241. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  109242. }
  109243. // Bones
  109244. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  109245. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  109246. }
  109247. // Morph targets
  109248. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  109249. // Draw
  109250. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  109251. }
  109252. else {
  109253. // Need to reset refresh rate of the main map
  109254. this._mainTexture.resetRefreshCounter();
  109255. }
  109256. };
  109257. /**
  109258. * Rebuild the required buffers.
  109259. * @hidden Internal use only.
  109260. */
  109261. EffectLayer.prototype._rebuild = function () {
  109262. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109263. if (vb) {
  109264. vb._rebuild();
  109265. }
  109266. this._generateIndexBuffer();
  109267. };
  109268. /**
  109269. * Dispose only the render target textures and post process.
  109270. */
  109271. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  109272. this._mainTexture.dispose();
  109273. for (var i = 0; i < this._postProcesses.length; i++) {
  109274. if (this._postProcesses[i]) {
  109275. this._postProcesses[i].dispose();
  109276. }
  109277. }
  109278. this._postProcesses = [];
  109279. for (var i = 0; i < this._textures.length; i++) {
  109280. if (this._textures[i]) {
  109281. this._textures[i].dispose();
  109282. }
  109283. }
  109284. this._textures = [];
  109285. };
  109286. /**
  109287. * Dispose the highlight layer and free resources.
  109288. */
  109289. EffectLayer.prototype.dispose = function () {
  109290. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  109291. if (vertexBuffer) {
  109292. vertexBuffer.dispose();
  109293. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  109294. }
  109295. if (this._indexBuffer) {
  109296. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  109297. this._indexBuffer = null;
  109298. }
  109299. // Clean textures and post processes
  109300. this._disposeTextureAndPostProcesses();
  109301. // Remove from scene
  109302. var index = this._scene.effectLayers.indexOf(this, 0);
  109303. if (index > -1) {
  109304. this._scene.effectLayers.splice(index, 1);
  109305. }
  109306. // Callback
  109307. this.onDisposeObservable.notifyObservers(this);
  109308. this.onDisposeObservable.clear();
  109309. this.onBeforeRenderMainTextureObservable.clear();
  109310. this.onBeforeComposeObservable.clear();
  109311. this.onAfterComposeObservable.clear();
  109312. this.onSizeChangedObservable.clear();
  109313. };
  109314. /**
  109315. * Gets the class name of the effect layer
  109316. * @returns the string with the class name of the effect layer
  109317. */
  109318. EffectLayer.prototype.getClassName = function () {
  109319. return "EffectLayer";
  109320. };
  109321. /**
  109322. * Creates an effect layer from parsed effect layer data
  109323. * @param parsedEffectLayer defines effect layer data
  109324. * @param scene defines the current scene
  109325. * @param rootUrl defines the root URL containing the effect layer information
  109326. * @returns a parsed effect Layer
  109327. */
  109328. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  109329. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  109330. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  109331. };
  109332. __decorate([
  109333. BABYLON.serialize()
  109334. ], EffectLayer.prototype, "name", void 0);
  109335. __decorate([
  109336. BABYLON.serializeAsColor4()
  109337. ], EffectLayer.prototype, "neutralColor", void 0);
  109338. __decorate([
  109339. BABYLON.serialize()
  109340. ], EffectLayer.prototype, "isEnabled", void 0);
  109341. __decorate([
  109342. BABYLON.serializeAsCameraReference()
  109343. ], EffectLayer.prototype, "camera", null);
  109344. __decorate([
  109345. BABYLON.serialize()
  109346. ], EffectLayer.prototype, "renderingGroupId", null);
  109347. return EffectLayer;
  109348. }());
  109349. BABYLON.EffectLayer = EffectLayer;
  109350. })(BABYLON || (BABYLON = {}));
  109351. //# sourceMappingURL=babylon.effectLayer.js.map
  109352. var BABYLON;
  109353. (function (BABYLON) {
  109354. BABYLON.AbstractScene.prototype.getHighlightLayerByName = function (name) {
  109355. for (var index = 0; index < this.effectLayers.length; index++) {
  109356. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === HighlightLayer.EffectName) {
  109357. return this.effectLayers[index];
  109358. }
  109359. }
  109360. return null;
  109361. };
  109362. /**
  109363. * Special Glow Blur post process only blurring the alpha channel
  109364. * It enforces keeping the most luminous color in the color channel.
  109365. */
  109366. var GlowBlurPostProcess = /** @class */ (function (_super) {
  109367. __extends(GlowBlurPostProcess, _super);
  109368. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  109369. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  109370. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  109371. _this.direction = direction;
  109372. _this.kernel = kernel;
  109373. _this.onApplyObservable.add(function (effect) {
  109374. effect.setFloat2("screenSize", _this.width, _this.height);
  109375. effect.setVector2("direction", _this.direction);
  109376. effect.setFloat("blurWidth", _this.kernel);
  109377. });
  109378. return _this;
  109379. }
  109380. return GlowBlurPostProcess;
  109381. }(BABYLON.PostProcess));
  109382. /**
  109383. * The highlight layer Helps adding a glow effect around a mesh.
  109384. *
  109385. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109386. * glowy meshes to your scene.
  109387. *
  109388. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  109389. */
  109390. var HighlightLayer = /** @class */ (function (_super) {
  109391. __extends(HighlightLayer, _super);
  109392. /**
  109393. * Instantiates a new highlight Layer and references it to the scene..
  109394. * @param name The name of the layer
  109395. * @param scene The scene to use the layer in
  109396. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  109397. */
  109398. function HighlightLayer(name, scene, options) {
  109399. var _this = _super.call(this, name, scene) || this;
  109400. _this.name = name;
  109401. /**
  109402. * Specifies whether or not the inner glow is ACTIVE in the layer.
  109403. */
  109404. _this.innerGlow = true;
  109405. /**
  109406. * Specifies whether or not the outer glow is ACTIVE in the layer.
  109407. */
  109408. _this.outerGlow = true;
  109409. /**
  109410. * An event triggered when the highlight layer is being blurred.
  109411. */
  109412. _this.onBeforeBlurObservable = new BABYLON.Observable();
  109413. /**
  109414. * An event triggered when the highlight layer has been blurred.
  109415. */
  109416. _this.onAfterBlurObservable = new BABYLON.Observable();
  109417. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  109418. _this._meshes = {};
  109419. _this._excludedMeshes = {};
  109420. _this.neutralColor = HighlightLayer.NeutralColor;
  109421. // Warn on stencil
  109422. if (!_this._engine.isStencilEnable) {
  109423. 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 }");
  109424. }
  109425. // Adapt options
  109426. _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);
  109427. // Initialize the layer
  109428. _this._init({
  109429. alphaBlendingMode: _this._options.alphaBlendingMode,
  109430. camera: _this._options.camera,
  109431. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109432. mainTextureRatio: _this._options.mainTextureRatio,
  109433. renderingGroupId: _this._options.renderingGroupId
  109434. });
  109435. // Do not render as long as no meshes have been added
  109436. _this._shouldRender = false;
  109437. return _this;
  109438. }
  109439. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  109440. /**
  109441. * Gets the horizontal size of the blur.
  109442. */
  109443. get: function () {
  109444. return this._horizontalBlurPostprocess.kernel;
  109445. },
  109446. /**
  109447. * Specifies the horizontal size of the blur.
  109448. */
  109449. set: function (value) {
  109450. this._horizontalBlurPostprocess.kernel = value;
  109451. },
  109452. enumerable: true,
  109453. configurable: true
  109454. });
  109455. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  109456. /**
  109457. * Gets the vertical size of the blur.
  109458. */
  109459. get: function () {
  109460. return this._verticalBlurPostprocess.kernel;
  109461. },
  109462. /**
  109463. * Specifies the vertical size of the blur.
  109464. */
  109465. set: function (value) {
  109466. this._verticalBlurPostprocess.kernel = value;
  109467. },
  109468. enumerable: true,
  109469. configurable: true
  109470. });
  109471. /**
  109472. * Get the effect name of the layer.
  109473. * @return The effect name
  109474. */
  109475. HighlightLayer.prototype.getEffectName = function () {
  109476. return HighlightLayer.EffectName;
  109477. };
  109478. /**
  109479. * Create the merge effect. This is the shader use to blit the information back
  109480. * to the main canvas at the end of the scene rendering.
  109481. */
  109482. HighlightLayer.prototype._createMergeEffect = function () {
  109483. // Effect
  109484. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  109485. };
  109486. /**
  109487. * Creates the render target textures and post processes used in the highlight layer.
  109488. */
  109489. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  109490. var _this = this;
  109491. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  109492. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  109493. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  109494. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  109495. var textureType = 0;
  109496. if (this._engine.getCaps().textureHalfFloatRender) {
  109497. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  109498. }
  109499. else {
  109500. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  109501. }
  109502. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  109503. width: blurTextureWidth,
  109504. height: blurTextureHeight
  109505. }, this._scene, false, true, textureType);
  109506. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109507. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  109508. this._blurTexture.anisotropicFilteringLevel = 16;
  109509. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  109510. this._blurTexture.renderParticles = false;
  109511. this._blurTexture.ignoreCameraViewport = true;
  109512. this._textures = [this._blurTexture];
  109513. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  109514. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109515. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  109516. effect.setTexture("textureSampler", _this._mainTexture);
  109517. });
  109518. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109519. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109520. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109521. });
  109522. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  109523. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  109524. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  109525. });
  109526. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109527. }
  109528. else {
  109529. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  109530. width: blurTextureWidth,
  109531. height: blurTextureHeight
  109532. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109533. this._horizontalBlurPostprocess.width = blurTextureWidth;
  109534. this._horizontalBlurPostprocess.height = blurTextureHeight;
  109535. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  109536. effect.setTexture("textureSampler", _this._mainTexture);
  109537. });
  109538. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  109539. width: blurTextureWidth,
  109540. height: blurTextureHeight
  109541. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  109542. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  109543. }
  109544. this._mainTexture.onAfterUnbindObservable.add(function () {
  109545. _this.onBeforeBlurObservable.notifyObservers(_this);
  109546. var internalTexture = _this._blurTexture.getInternalTexture();
  109547. if (internalTexture) {
  109548. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  109549. }
  109550. _this.onAfterBlurObservable.notifyObservers(_this);
  109551. });
  109552. // Prevent autoClear.
  109553. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  109554. };
  109555. /**
  109556. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  109557. */
  109558. HighlightLayer.prototype.needStencil = function () {
  109559. return true;
  109560. };
  109561. /**
  109562. * Checks for the readiness of the element composing the layer.
  109563. * @param subMesh the mesh to check for
  109564. * @param useInstances specify wether or not to use instances to render the mesh
  109565. * @param emissiveTexture the associated emissive texture used to generate the glow
  109566. * @return true if ready otherwise, false
  109567. */
  109568. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  109569. var material = subMesh.getMaterial();
  109570. var mesh = subMesh.getRenderingMesh();
  109571. if (!material || !mesh || !this._meshes) {
  109572. return false;
  109573. }
  109574. var emissiveTexture = null;
  109575. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109576. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109577. emissiveTexture = material.emissiveTexture;
  109578. }
  109579. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  109580. };
  109581. /**
  109582. * Implementation specific of rendering the generating effect on the main canvas.
  109583. * @param effect The effect used to render through
  109584. */
  109585. HighlightLayer.prototype._internalRender = function (effect) {
  109586. // Texture
  109587. effect.setTexture("textureSampler", this._blurTexture);
  109588. // Cache
  109589. var engine = this._engine;
  109590. var previousStencilBuffer = engine.getStencilBuffer();
  109591. var previousStencilFunction = engine.getStencilFunction();
  109592. var previousStencilMask = engine.getStencilMask();
  109593. var previousStencilOperationPass = engine.getStencilOperationPass();
  109594. var previousStencilOperationFail = engine.getStencilOperationFail();
  109595. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  109596. var previousStencilReference = engine.getStencilFunctionReference();
  109597. // Stencil operations
  109598. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  109599. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  109600. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  109601. // Draw order
  109602. engine.setStencilMask(0x00);
  109603. engine.setStencilBuffer(true);
  109604. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  109605. // 2 passes inner outer
  109606. if (this.outerGlow) {
  109607. effect.setFloat("offset", 0);
  109608. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  109609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109610. }
  109611. if (this.innerGlow) {
  109612. effect.setFloat("offset", 1);
  109613. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  109614. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  109615. }
  109616. // Restore Cache
  109617. engine.setStencilFunction(previousStencilFunction);
  109618. engine.setStencilMask(previousStencilMask);
  109619. engine.setStencilBuffer(previousStencilBuffer);
  109620. engine.setStencilOperationPass(previousStencilOperationPass);
  109621. engine.setStencilOperationFail(previousStencilOperationFail);
  109622. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  109623. engine.setStencilFunctionReference(previousStencilReference);
  109624. };
  109625. /**
  109626. * Returns true if the layer contains information to display, otherwise false.
  109627. */
  109628. HighlightLayer.prototype.shouldRender = function () {
  109629. if (_super.prototype.shouldRender.call(this)) {
  109630. return this._meshes ? true : false;
  109631. }
  109632. return false;
  109633. };
  109634. /**
  109635. * Returns true if the mesh should render, otherwise false.
  109636. * @param mesh The mesh to render
  109637. * @returns true if it should render otherwise false
  109638. */
  109639. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  109640. // Excluded Mesh
  109641. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  109642. return false;
  109643. }
  109644. ;
  109645. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109646. return false;
  109647. }
  109648. return true;
  109649. };
  109650. /**
  109651. * Sets the required values for both the emissive texture and and the main color.
  109652. */
  109653. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  109654. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  109655. if (highlightLayerMesh) {
  109656. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  109657. }
  109658. else {
  109659. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  109660. }
  109661. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  109662. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  109663. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  109664. }
  109665. else {
  109666. this._emissiveTextureAndColor.texture = null;
  109667. }
  109668. };
  109669. /**
  109670. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  109671. * @param mesh The mesh to exclude from the highlight layer
  109672. */
  109673. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  109674. if (!this._excludedMeshes) {
  109675. return;
  109676. }
  109677. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109678. if (!meshExcluded) {
  109679. this._excludedMeshes[mesh.uniqueId] = {
  109680. mesh: mesh,
  109681. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  109682. mesh.getEngine().setStencilBuffer(false);
  109683. }),
  109684. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  109685. mesh.getEngine().setStencilBuffer(true);
  109686. }),
  109687. };
  109688. }
  109689. };
  109690. /**
  109691. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  109692. * @param mesh The mesh to highlight
  109693. */
  109694. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  109695. if (!this._excludedMeshes) {
  109696. return;
  109697. }
  109698. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  109699. if (meshExcluded) {
  109700. if (meshExcluded.beforeRender) {
  109701. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  109702. }
  109703. if (meshExcluded.afterRender) {
  109704. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  109705. }
  109706. }
  109707. this._excludedMeshes[mesh.uniqueId] = null;
  109708. };
  109709. /**
  109710. * Determine if a given mesh will be highlighted by the current HighlightLayer
  109711. * @param mesh mesh to test
  109712. * @returns true if the mesh will be highlighted by the current HighlightLayer
  109713. */
  109714. HighlightLayer.prototype.hasMesh = function (mesh) {
  109715. if (!this._meshes) {
  109716. return false;
  109717. }
  109718. if (!_super.prototype.hasMesh.call(this, mesh)) {
  109719. return false;
  109720. }
  109721. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  109722. };
  109723. /**
  109724. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  109725. * @param mesh The mesh to highlight
  109726. * @param color The color of the highlight
  109727. * @param glowEmissiveOnly Extract the glow from the emissive texture
  109728. */
  109729. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  109730. var _this = this;
  109731. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  109732. if (!this._meshes) {
  109733. return;
  109734. }
  109735. var meshHighlight = this._meshes[mesh.uniqueId];
  109736. if (meshHighlight) {
  109737. meshHighlight.color = color;
  109738. }
  109739. else {
  109740. this._meshes[mesh.uniqueId] = {
  109741. mesh: mesh,
  109742. color: color,
  109743. // Lambda required for capture due to Observable this context
  109744. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  109745. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  109746. _this._defaultStencilReference(mesh);
  109747. }
  109748. else {
  109749. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  109750. }
  109751. }),
  109752. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  109753. glowEmissiveOnly: glowEmissiveOnly
  109754. };
  109755. mesh.onDisposeObservable.add(function () {
  109756. _this._disposeMesh(mesh);
  109757. });
  109758. }
  109759. this._shouldRender = true;
  109760. };
  109761. /**
  109762. * Remove a mesh from the highlight layer in order to make it stop glowing.
  109763. * @param mesh The mesh to highlight
  109764. */
  109765. HighlightLayer.prototype.removeMesh = function (mesh) {
  109766. if (!this._meshes) {
  109767. return;
  109768. }
  109769. var meshHighlight = this._meshes[mesh.uniqueId];
  109770. if (meshHighlight) {
  109771. if (meshHighlight.observerHighlight) {
  109772. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  109773. }
  109774. if (meshHighlight.observerDefault) {
  109775. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  109776. }
  109777. delete this._meshes[mesh.uniqueId];
  109778. }
  109779. this._shouldRender = false;
  109780. for (var meshHighlightToCheck in this._meshes) {
  109781. if (this._meshes[meshHighlightToCheck]) {
  109782. this._shouldRender = true;
  109783. break;
  109784. }
  109785. }
  109786. };
  109787. /**
  109788. * Force the stencil to the normal expected value for none glowing parts
  109789. */
  109790. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  109791. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  109792. };
  109793. /**
  109794. * Free any resources and references associated to a mesh.
  109795. * Internal use
  109796. * @param mesh The mesh to free.
  109797. * @hidden
  109798. */
  109799. HighlightLayer.prototype._disposeMesh = function (mesh) {
  109800. this.removeMesh(mesh);
  109801. this.removeExcludedMesh(mesh);
  109802. };
  109803. /**
  109804. * Dispose the highlight layer and free resources.
  109805. */
  109806. HighlightLayer.prototype.dispose = function () {
  109807. if (this._meshes) {
  109808. // Clean mesh references
  109809. for (var id in this._meshes) {
  109810. var meshHighlight = this._meshes[id];
  109811. if (meshHighlight && meshHighlight.mesh) {
  109812. if (meshHighlight.observerHighlight) {
  109813. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  109814. }
  109815. if (meshHighlight.observerDefault) {
  109816. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  109817. }
  109818. }
  109819. }
  109820. this._meshes = null;
  109821. }
  109822. if (this._excludedMeshes) {
  109823. for (var id in this._excludedMeshes) {
  109824. var meshHighlight = this._excludedMeshes[id];
  109825. if (meshHighlight) {
  109826. if (meshHighlight.beforeRender) {
  109827. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  109828. }
  109829. if (meshHighlight.afterRender) {
  109830. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  109831. }
  109832. }
  109833. }
  109834. this._excludedMeshes = null;
  109835. }
  109836. _super.prototype.dispose.call(this);
  109837. };
  109838. /**
  109839. * Gets the class name of the effect layer
  109840. * @returns the string with the class name of the effect layer
  109841. */
  109842. HighlightLayer.prototype.getClassName = function () {
  109843. return "HighlightLayer";
  109844. };
  109845. /**
  109846. * Serializes this Highlight layer
  109847. * @returns a serialized Highlight layer object
  109848. */
  109849. HighlightLayer.prototype.serialize = function () {
  109850. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  109851. serializationObject.customType = "BABYLON.HighlightLayer";
  109852. // Highlighted meshes
  109853. serializationObject.meshes = [];
  109854. if (this._meshes) {
  109855. for (var m in this._meshes) {
  109856. var mesh = this._meshes[m];
  109857. if (mesh) {
  109858. serializationObject.meshes.push({
  109859. glowEmissiveOnly: mesh.glowEmissiveOnly,
  109860. color: mesh.color.asArray(),
  109861. meshId: mesh.mesh.id
  109862. });
  109863. }
  109864. }
  109865. }
  109866. // Excluded meshes
  109867. serializationObject.excludedMeshes = [];
  109868. if (this._excludedMeshes) {
  109869. for (var e in this._excludedMeshes) {
  109870. var excludedMesh = this._excludedMeshes[e];
  109871. if (excludedMesh) {
  109872. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  109873. }
  109874. }
  109875. }
  109876. return serializationObject;
  109877. };
  109878. /**
  109879. * Creates a Highlight layer from parsed Highlight layer data
  109880. * @param parsedHightlightLayer defines the Highlight layer data
  109881. * @param scene defines the current scene
  109882. * @param rootUrl defines the root URL containing the Highlight layer information
  109883. * @returns a parsed Highlight layer
  109884. */
  109885. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  109886. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  109887. var index;
  109888. // Excluded meshes
  109889. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  109890. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  109891. if (mesh) {
  109892. hl.addExcludedMesh(mesh);
  109893. }
  109894. }
  109895. // Included meshes
  109896. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  109897. var highlightedMesh = parsedHightlightLayer.meshes[index];
  109898. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  109899. if (mesh) {
  109900. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  109901. }
  109902. }
  109903. return hl;
  109904. };
  109905. /**
  109906. * Effect Name of the highlight layer.
  109907. */
  109908. HighlightLayer.EffectName = "HighlightLayer";
  109909. /**
  109910. * The neutral color used during the preparation of the glow effect.
  109911. * This is black by default as the blend operation is a blend operation.
  109912. */
  109913. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  109914. /**
  109915. * Stencil value used for glowing meshes.
  109916. */
  109917. HighlightLayer.GlowingMeshStencilReference = 0x02;
  109918. /**
  109919. * Stencil value used for the other meshes in the scene.
  109920. */
  109921. HighlightLayer.NormalMeshStencilReference = 0x01;
  109922. __decorate([
  109923. BABYLON.serialize()
  109924. ], HighlightLayer.prototype, "innerGlow", void 0);
  109925. __decorate([
  109926. BABYLON.serialize()
  109927. ], HighlightLayer.prototype, "outerGlow", void 0);
  109928. __decorate([
  109929. BABYLON.serialize()
  109930. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  109931. __decorate([
  109932. BABYLON.serialize()
  109933. ], HighlightLayer.prototype, "blurVerticalSize", null);
  109934. __decorate([
  109935. BABYLON.serialize("options")
  109936. ], HighlightLayer.prototype, "_options", void 0);
  109937. return HighlightLayer;
  109938. }(BABYLON.EffectLayer));
  109939. BABYLON.HighlightLayer = HighlightLayer;
  109940. })(BABYLON || (BABYLON = {}));
  109941. //# sourceMappingURL=babylon.highlightLayer.js.map
  109942. var BABYLON;
  109943. (function (BABYLON) {
  109944. BABYLON.AbstractScene.prototype.getGlowLayerByName = function (name) {
  109945. for (var index = 0; index < this.effectLayers.length; index++) {
  109946. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === GlowLayer.EffectName) {
  109947. return this.effectLayers[index];
  109948. }
  109949. }
  109950. return null;
  109951. };
  109952. /**
  109953. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  109954. *
  109955. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  109956. * glowy meshes to your scene.
  109957. *
  109958. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  109959. */
  109960. var GlowLayer = /** @class */ (function (_super) {
  109961. __extends(GlowLayer, _super);
  109962. /**
  109963. * Instantiates a new glow Layer and references it to the scene.
  109964. * @param name The name of the layer
  109965. * @param scene The scene to use the layer in
  109966. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  109967. */
  109968. function GlowLayer(name, scene, options) {
  109969. var _this = _super.call(this, name, scene) || this;
  109970. _this._intensity = 1.0;
  109971. _this._includedOnlyMeshes = [];
  109972. _this._excludedMeshes = [];
  109973. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  109974. // Adapt options
  109975. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1, renderingGroupId: -1 }, options);
  109976. // Initialize the layer
  109977. _this._init({
  109978. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  109979. camera: _this._options.camera,
  109980. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  109981. mainTextureRatio: _this._options.mainTextureRatio,
  109982. renderingGroupId: _this._options.renderingGroupId
  109983. });
  109984. return _this;
  109985. }
  109986. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  109987. /**
  109988. * Gets the kernel size of the blur.
  109989. */
  109990. get: function () {
  109991. return this._horizontalBlurPostprocess1.kernel;
  109992. },
  109993. /**
  109994. * Sets the kernel size of the blur.
  109995. */
  109996. set: function (value) {
  109997. this._horizontalBlurPostprocess1.kernel = value;
  109998. this._verticalBlurPostprocess1.kernel = value;
  109999. this._horizontalBlurPostprocess2.kernel = value;
  110000. this._verticalBlurPostprocess2.kernel = value;
  110001. },
  110002. enumerable: true,
  110003. configurable: true
  110004. });
  110005. Object.defineProperty(GlowLayer.prototype, "intensity", {
  110006. /**
  110007. * Gets the glow intensity.
  110008. */
  110009. get: function () {
  110010. return this._intensity;
  110011. },
  110012. /**
  110013. * Sets the glow intensity.
  110014. */
  110015. set: function (value) {
  110016. this._intensity = value;
  110017. },
  110018. enumerable: true,
  110019. configurable: true
  110020. });
  110021. /**
  110022. * Get the effect name of the layer.
  110023. * @return The effect name
  110024. */
  110025. GlowLayer.prototype.getEffectName = function () {
  110026. return GlowLayer.EffectName;
  110027. };
  110028. /**
  110029. * Create the merge effect. This is the shader use to blit the information back
  110030. * to the main canvas at the end of the scene rendering.
  110031. */
  110032. GlowLayer.prototype._createMergeEffect = function () {
  110033. // Effect
  110034. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  110035. };
  110036. /**
  110037. * Creates the render target textures and post processes used in the glow layer.
  110038. */
  110039. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  110040. var _this = this;
  110041. var blurTextureWidth = this._mainTextureDesiredSize.width;
  110042. var blurTextureHeight = this._mainTextureDesiredSize.height;
  110043. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  110044. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  110045. var textureType = 0;
  110046. if (this._engine.getCaps().textureHalfFloatRender) {
  110047. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  110048. }
  110049. else {
  110050. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  110051. }
  110052. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  110053. width: blurTextureWidth,
  110054. height: blurTextureHeight
  110055. }, this._scene, false, true, textureType);
  110056. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110057. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110058. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110059. this._blurTexture1.renderParticles = false;
  110060. this._blurTexture1.ignoreCameraViewport = true;
  110061. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  110062. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  110063. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  110064. width: blurTextureWidth2,
  110065. height: blurTextureHeight2
  110066. }, this._scene, false, true, textureType);
  110067. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110068. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  110069. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  110070. this._blurTexture2.renderParticles = false;
  110071. this._blurTexture2.ignoreCameraViewport = true;
  110072. this._textures = [this._blurTexture1, this._blurTexture2];
  110073. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110074. width: blurTextureWidth,
  110075. height: blurTextureHeight
  110076. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110077. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  110078. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  110079. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  110080. effect.setTexture("textureSampler", _this._mainTexture);
  110081. });
  110082. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110083. width: blurTextureWidth,
  110084. height: blurTextureHeight
  110085. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110086. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  110087. width: blurTextureWidth2,
  110088. height: blurTextureHeight2
  110089. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110090. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  110091. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  110092. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  110093. effect.setTexture("textureSampler", _this._blurTexture1);
  110094. });
  110095. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  110096. width: blurTextureWidth2,
  110097. height: blurTextureHeight2
  110098. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  110099. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110100. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  110101. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  110102. this._mainTexture.samples = this._options.mainTextureSamples;
  110103. this._mainTexture.onAfterUnbindObservable.add(function () {
  110104. var internalTexture = _this._blurTexture1.getInternalTexture();
  110105. if (internalTexture) {
  110106. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  110107. internalTexture = _this._blurTexture2.getInternalTexture();
  110108. if (internalTexture) {
  110109. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  110110. }
  110111. }
  110112. });
  110113. // Prevent autoClear.
  110114. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  110115. };
  110116. /**
  110117. * Checks for the readiness of the element composing the layer.
  110118. * @param subMesh the mesh to check for
  110119. * @param useInstances specify wether or not to use instances to render the mesh
  110120. * @param emissiveTexture the associated emissive texture used to generate the glow
  110121. * @return true if ready otherwise, false
  110122. */
  110123. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  110124. var material = subMesh.getMaterial();
  110125. var mesh = subMesh.getRenderingMesh();
  110126. if (!material || !mesh) {
  110127. return false;
  110128. }
  110129. var emissiveTexture = material.emissiveTexture;
  110130. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  110131. };
  110132. /**
  110133. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  110134. */
  110135. GlowLayer.prototype.needStencil = function () {
  110136. return false;
  110137. };
  110138. /**
  110139. * Implementation specific of rendering the generating effect on the main canvas.
  110140. * @param effect The effect used to render through
  110141. */
  110142. GlowLayer.prototype._internalRender = function (effect) {
  110143. // Texture
  110144. effect.setTexture("textureSampler", this._blurTexture1);
  110145. effect.setTexture("textureSampler2", this._blurTexture2);
  110146. effect.setFloat("offset", this._intensity);
  110147. // Cache
  110148. var engine = this._engine;
  110149. var previousStencilBuffer = engine.getStencilBuffer();
  110150. // Draw order
  110151. engine.setStencilBuffer(false);
  110152. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  110153. // Draw order
  110154. engine.setStencilBuffer(previousStencilBuffer);
  110155. };
  110156. /**
  110157. * Sets the required values for both the emissive texture and and the main color.
  110158. */
  110159. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  110160. var textureLevel = 1.0;
  110161. if (this.customEmissiveTextureSelector) {
  110162. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  110163. }
  110164. else {
  110165. if (material) {
  110166. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  110167. if (this._emissiveTextureAndColor.texture) {
  110168. textureLevel = this._emissiveTextureAndColor.texture.level;
  110169. }
  110170. }
  110171. else {
  110172. this._emissiveTextureAndColor.texture = null;
  110173. }
  110174. }
  110175. if (this.customEmissiveColorSelector) {
  110176. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  110177. }
  110178. else {
  110179. if (material.emissiveColor) {
  110180. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  110181. }
  110182. else {
  110183. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  110184. }
  110185. }
  110186. };
  110187. /**
  110188. * Returns true if the mesh should render, otherwise false.
  110189. * @param mesh The mesh to render
  110190. * @returns true if it should render otherwise false
  110191. */
  110192. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  110193. return this.hasMesh(mesh);
  110194. };
  110195. /**
  110196. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  110197. * @param mesh The mesh to exclude from the glow layer
  110198. */
  110199. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  110200. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  110201. this._excludedMeshes.push(mesh.uniqueId);
  110202. }
  110203. };
  110204. /**
  110205. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  110206. * @param mesh The mesh to remove
  110207. */
  110208. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  110209. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  110210. if (index !== -1) {
  110211. this._excludedMeshes.splice(index, 1);
  110212. }
  110213. };
  110214. /**
  110215. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  110216. * @param mesh The mesh to include in the glow layer
  110217. */
  110218. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  110219. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  110220. this._includedOnlyMeshes.push(mesh.uniqueId);
  110221. }
  110222. };
  110223. /**
  110224. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  110225. * @param mesh The mesh to remove
  110226. */
  110227. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  110228. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  110229. if (index !== -1) {
  110230. this._includedOnlyMeshes.splice(index, 1);
  110231. }
  110232. };
  110233. /**
  110234. * Determine if a given mesh will be used in the glow layer
  110235. * @param mesh The mesh to test
  110236. * @returns true if the mesh will be highlighted by the current glow layer
  110237. */
  110238. GlowLayer.prototype.hasMesh = function (mesh) {
  110239. if (!_super.prototype.hasMesh.call(this, mesh)) {
  110240. return false;
  110241. }
  110242. // Included Mesh
  110243. if (this._includedOnlyMeshes.length) {
  110244. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  110245. }
  110246. ;
  110247. // Excluded Mesh
  110248. if (this._excludedMeshes.length) {
  110249. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  110250. }
  110251. ;
  110252. return true;
  110253. };
  110254. /**
  110255. * Free any resources and references associated to a mesh.
  110256. * Internal use
  110257. * @param mesh The mesh to free.
  110258. * @hidden
  110259. */
  110260. GlowLayer.prototype._disposeMesh = function (mesh) {
  110261. this.removeIncludedOnlyMesh(mesh);
  110262. this.removeExcludedMesh(mesh);
  110263. };
  110264. /**
  110265. * Gets the class name of the effect layer
  110266. * @returns the string with the class name of the effect layer
  110267. */
  110268. GlowLayer.prototype.getClassName = function () {
  110269. return "GlowLayer";
  110270. };
  110271. /**
  110272. * Serializes this glow layer
  110273. * @returns a serialized glow layer object
  110274. */
  110275. GlowLayer.prototype.serialize = function () {
  110276. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  110277. serializationObject.customType = "BABYLON.GlowLayer";
  110278. var index;
  110279. // Included meshes
  110280. serializationObject.includedMeshes = [];
  110281. if (this._includedOnlyMeshes.length) {
  110282. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  110283. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  110284. if (mesh) {
  110285. serializationObject.includedMeshes.push(mesh.id);
  110286. }
  110287. }
  110288. }
  110289. // Excluded meshes
  110290. serializationObject.excludedMeshes = [];
  110291. if (this._excludedMeshes.length) {
  110292. for (index = 0; index < this._excludedMeshes.length; index++) {
  110293. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  110294. if (mesh) {
  110295. serializationObject.excludedMeshes.push(mesh.id);
  110296. }
  110297. }
  110298. }
  110299. return serializationObject;
  110300. };
  110301. /**
  110302. * Creates a Glow Layer from parsed glow layer data
  110303. * @param parsedGlowLayer defines glow layer data
  110304. * @param scene defines the current scene
  110305. * @param rootUrl defines the root URL containing the glow layer information
  110306. * @returns a parsed Glow Layer
  110307. */
  110308. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  110309. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  110310. var index;
  110311. // Excluded meshes
  110312. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  110313. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  110314. if (mesh) {
  110315. gl.addExcludedMesh(mesh);
  110316. }
  110317. }
  110318. // Included meshes
  110319. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  110320. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  110321. if (mesh) {
  110322. gl.addIncludedOnlyMesh(mesh);
  110323. }
  110324. }
  110325. return gl;
  110326. };
  110327. /**
  110328. * Effect Name of the layer.
  110329. */
  110330. GlowLayer.EffectName = "GlowLayer";
  110331. /**
  110332. * The default blur kernel size used for the glow.
  110333. */
  110334. GlowLayer.DefaultBlurKernelSize = 32;
  110335. /**
  110336. * The default texture size ratio used for the glow.
  110337. */
  110338. GlowLayer.DefaultTextureRatio = 0.5;
  110339. __decorate([
  110340. BABYLON.serialize()
  110341. ], GlowLayer.prototype, "blurKernelSize", null);
  110342. __decorate([
  110343. BABYLON.serialize()
  110344. ], GlowLayer.prototype, "intensity", null);
  110345. __decorate([
  110346. BABYLON.serialize("options")
  110347. ], GlowLayer.prototype, "_options", void 0);
  110348. return GlowLayer;
  110349. }(BABYLON.EffectLayer));
  110350. BABYLON.GlowLayer = GlowLayer;
  110351. })(BABYLON || (BABYLON = {}));
  110352. //# sourceMappingURL=babylon.glowLayer.js.map
  110353. var BABYLON;
  110354. (function (BABYLON) {
  110355. /**
  110356. * Defines the list of states available for a task inside a AssetsManager
  110357. */
  110358. var AssetTaskState;
  110359. (function (AssetTaskState) {
  110360. /**
  110361. * Initialization
  110362. */
  110363. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  110364. /**
  110365. * Running
  110366. */
  110367. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  110368. /**
  110369. * Done
  110370. */
  110371. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  110372. /**
  110373. * Error
  110374. */
  110375. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  110376. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  110377. /**
  110378. * Define an abstract asset task used with a AssetsManager class to load assets into a scene
  110379. */
  110380. var AbstractAssetTask = /** @class */ (function () {
  110381. /**
  110382. * Creates a new AssetsManager
  110383. * @param name defines the name of the task
  110384. */
  110385. function AbstractAssetTask(
  110386. /**
  110387. * Task name
  110388. */ name) {
  110389. this.name = name;
  110390. this._isCompleted = false;
  110391. this._taskState = AssetTaskState.INIT;
  110392. }
  110393. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  110394. /**
  110395. * Get if the task is completed
  110396. */
  110397. get: function () {
  110398. return this._isCompleted;
  110399. },
  110400. enumerable: true,
  110401. configurable: true
  110402. });
  110403. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  110404. /**
  110405. * Gets the current state of the task
  110406. */
  110407. get: function () {
  110408. return this._taskState;
  110409. },
  110410. enumerable: true,
  110411. configurable: true
  110412. });
  110413. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  110414. /**
  110415. * Gets the current error object (if task is in error)
  110416. */
  110417. get: function () {
  110418. return this._errorObject;
  110419. },
  110420. enumerable: true,
  110421. configurable: true
  110422. });
  110423. /**
  110424. * Internal only
  110425. * @hidden
  110426. */
  110427. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  110428. if (this._errorObject) {
  110429. return;
  110430. }
  110431. this._errorObject = {
  110432. message: message,
  110433. exception: exception
  110434. };
  110435. };
  110436. /**
  110437. * Execute the current task
  110438. * @param scene defines the scene where you want your assets to be loaded
  110439. * @param onSuccess is a callback called when the task is successfully executed
  110440. * @param onError is a callback called if an error occurs
  110441. */
  110442. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110443. var _this = this;
  110444. this._taskState = AssetTaskState.RUNNING;
  110445. this.runTask(scene, function () {
  110446. _this.onDoneCallback(onSuccess, onError);
  110447. }, function (msg, exception) {
  110448. _this.onErrorCallback(onError, msg, exception);
  110449. });
  110450. };
  110451. /**
  110452. * Execute the current task
  110453. * @param scene defines the scene where you want your assets to be loaded
  110454. * @param onSuccess is a callback called when the task is successfully executed
  110455. * @param onError is a callback called if an error occurs
  110456. */
  110457. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110458. throw new Error("runTask is not implemented");
  110459. };
  110460. /**
  110461. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  110462. * This can be used with failed tasks that have the reason for failure fixed.
  110463. */
  110464. AbstractAssetTask.prototype.reset = function () {
  110465. this._taskState = AssetTaskState.INIT;
  110466. };
  110467. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  110468. this._taskState = AssetTaskState.ERROR;
  110469. this._errorObject = {
  110470. message: message,
  110471. exception: exception
  110472. };
  110473. if (this.onError) {
  110474. this.onError(this, message, exception);
  110475. }
  110476. onError();
  110477. };
  110478. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  110479. try {
  110480. this._taskState = AssetTaskState.DONE;
  110481. this._isCompleted = true;
  110482. if (this.onSuccess) {
  110483. this.onSuccess(this);
  110484. }
  110485. onSuccess();
  110486. }
  110487. catch (e) {
  110488. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  110489. }
  110490. };
  110491. return AbstractAssetTask;
  110492. }());
  110493. BABYLON.AbstractAssetTask = AbstractAssetTask;
  110494. /**
  110495. * Class used to share progress information about assets loading
  110496. */
  110497. var AssetsProgressEvent = /** @class */ (function () {
  110498. /**
  110499. * Creates a AssetsProgressEvent
  110500. * @param remainingCount defines the number of remaining tasks to process
  110501. * @param totalCount defines the total number of tasks
  110502. * @param task defines the task that was just processed
  110503. */
  110504. function AssetsProgressEvent(remainingCount, totalCount, task) {
  110505. this.remainingCount = remainingCount;
  110506. this.totalCount = totalCount;
  110507. this.task = task;
  110508. }
  110509. return AssetsProgressEvent;
  110510. }());
  110511. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  110512. /**
  110513. * Define a task used by AssetsManager to load meshes
  110514. */
  110515. var MeshAssetTask = /** @class */ (function (_super) {
  110516. __extends(MeshAssetTask, _super);
  110517. /**
  110518. * Creates a new MeshAssetTask
  110519. * @param name defines the name of the task
  110520. * @param meshesNames defines the list of mesh's names you want to load
  110521. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  110522. * @param sceneFilename defines the filename of the scene to load from
  110523. */
  110524. function MeshAssetTask(
  110525. /**
  110526. * Defines the name of the task
  110527. */
  110528. name,
  110529. /**
  110530. * Defines the list of mesh's names you want to load
  110531. */
  110532. meshesNames,
  110533. /**
  110534. * Defines the root url to use as a base to load your meshes and associated resources
  110535. */
  110536. rootUrl,
  110537. /**
  110538. * Defines the filename of the scene to load from
  110539. */
  110540. sceneFilename) {
  110541. var _this = _super.call(this, name) || this;
  110542. _this.name = name;
  110543. _this.meshesNames = meshesNames;
  110544. _this.rootUrl = rootUrl;
  110545. _this.sceneFilename = sceneFilename;
  110546. return _this;
  110547. }
  110548. /**
  110549. * Execute the current task
  110550. * @param scene defines the scene where you want your assets to be loaded
  110551. * @param onSuccess is a callback called when the task is successfully executed
  110552. * @param onError is a callback called if an error occurs
  110553. */
  110554. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110555. var _this = this;
  110556. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  110557. _this.loadedMeshes = meshes;
  110558. _this.loadedParticleSystems = particleSystems;
  110559. _this.loadedSkeletons = skeletons;
  110560. onSuccess();
  110561. }, null, function (scene, message, exception) {
  110562. onError(message, exception);
  110563. });
  110564. };
  110565. return MeshAssetTask;
  110566. }(AbstractAssetTask));
  110567. BABYLON.MeshAssetTask = MeshAssetTask;
  110568. /**
  110569. * Define a task used by AssetsManager to load text content
  110570. */
  110571. var TextFileAssetTask = /** @class */ (function (_super) {
  110572. __extends(TextFileAssetTask, _super);
  110573. /**
  110574. * Creates a new TextFileAssetTask object
  110575. * @param name defines the name of the task
  110576. * @param url defines the location of the file to load
  110577. */
  110578. function TextFileAssetTask(
  110579. /**
  110580. * Defines the name of the task
  110581. */
  110582. name,
  110583. /**
  110584. * Defines the location of the file to load
  110585. */
  110586. url) {
  110587. var _this = _super.call(this, name) || this;
  110588. _this.name = name;
  110589. _this.url = url;
  110590. return _this;
  110591. }
  110592. /**
  110593. * Execute the current task
  110594. * @param scene defines the scene where you want your assets to be loaded
  110595. * @param onSuccess is a callback called when the task is successfully executed
  110596. * @param onError is a callback called if an error occurs
  110597. */
  110598. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110599. var _this = this;
  110600. scene._loadFile(this.url, function (data) {
  110601. _this.text = data;
  110602. onSuccess();
  110603. }, undefined, false, false, function (request, exception) {
  110604. if (request) {
  110605. onError(request.status + " " + request.statusText, exception);
  110606. }
  110607. });
  110608. };
  110609. return TextFileAssetTask;
  110610. }(AbstractAssetTask));
  110611. BABYLON.TextFileAssetTask = TextFileAssetTask;
  110612. /**
  110613. * Define a task used by AssetsManager to load binary data
  110614. */
  110615. var BinaryFileAssetTask = /** @class */ (function (_super) {
  110616. __extends(BinaryFileAssetTask, _super);
  110617. /**
  110618. * Creates a new BinaryFileAssetTask object
  110619. * @param name defines the name of the new task
  110620. * @param url defines the location of the file to load
  110621. */
  110622. function BinaryFileAssetTask(
  110623. /**
  110624. * Defines the name of the task
  110625. */
  110626. name,
  110627. /**
  110628. * Defines the location of the file to load
  110629. */
  110630. url) {
  110631. var _this = _super.call(this, name) || this;
  110632. _this.name = name;
  110633. _this.url = url;
  110634. return _this;
  110635. }
  110636. /**
  110637. * Execute the current task
  110638. * @param scene defines the scene where you want your assets to be loaded
  110639. * @param onSuccess is a callback called when the task is successfully executed
  110640. * @param onError is a callback called if an error occurs
  110641. */
  110642. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110643. var _this = this;
  110644. scene._loadFile(this.url, function (data) {
  110645. _this.data = data;
  110646. onSuccess();
  110647. }, undefined, true, true, function (request, exception) {
  110648. if (request) {
  110649. onError(request.status + " " + request.statusText, exception);
  110650. }
  110651. });
  110652. };
  110653. return BinaryFileAssetTask;
  110654. }(AbstractAssetTask));
  110655. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  110656. /**
  110657. * Define a task used by AssetsManager to load images
  110658. */
  110659. var ImageAssetTask = /** @class */ (function (_super) {
  110660. __extends(ImageAssetTask, _super);
  110661. /**
  110662. * Creates a new ImageAssetTask
  110663. * @param name defines the name of the task
  110664. * @param url defines the location of the image to load
  110665. */
  110666. function ImageAssetTask(
  110667. /**
  110668. * Defines the name of the task
  110669. */
  110670. name,
  110671. /**
  110672. * Defines the location of the image to load
  110673. */
  110674. url) {
  110675. var _this = _super.call(this, name) || this;
  110676. _this.name = name;
  110677. _this.url = url;
  110678. return _this;
  110679. }
  110680. /**
  110681. * Execute the current task
  110682. * @param scene defines the scene where you want your assets to be loaded
  110683. * @param onSuccess is a callback called when the task is successfully executed
  110684. * @param onError is a callback called if an error occurs
  110685. */
  110686. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110687. var _this = this;
  110688. var img = new Image();
  110689. BABYLON.Tools.SetCorsBehavior(this.url, img);
  110690. img.onload = function () {
  110691. _this.image = img;
  110692. onSuccess();
  110693. };
  110694. img.onerror = function (err) {
  110695. onError("Error loading image", err);
  110696. };
  110697. img.src = this.url;
  110698. };
  110699. return ImageAssetTask;
  110700. }(AbstractAssetTask));
  110701. BABYLON.ImageAssetTask = ImageAssetTask;
  110702. /**
  110703. * Define a task used by AssetsManager to load 2D textures
  110704. */
  110705. var TextureAssetTask = /** @class */ (function (_super) {
  110706. __extends(TextureAssetTask, _super);
  110707. /**
  110708. * Creates a new TextureAssetTask object
  110709. * @param name defines the name of the task
  110710. * @param url defines the location of the file to load
  110711. * @param noMipmap defines if mipmap should not be generated (default is false)
  110712. * @param invertY defines if texture must be inverted on Y axis (default is false)
  110713. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110714. */
  110715. function TextureAssetTask(
  110716. /**
  110717. * Defines the name of the task
  110718. */
  110719. name,
  110720. /**
  110721. * Defines the location of the file to load
  110722. */
  110723. url,
  110724. /**
  110725. * Defines if mipmap should not be generated (default is false)
  110726. */
  110727. noMipmap,
  110728. /**
  110729. * Defines if texture must be inverted on Y axis (default is false)
  110730. */
  110731. invertY,
  110732. /**
  110733. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  110734. */
  110735. samplingMode) {
  110736. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110737. var _this = _super.call(this, name) || this;
  110738. _this.name = name;
  110739. _this.url = url;
  110740. _this.noMipmap = noMipmap;
  110741. _this.invertY = invertY;
  110742. _this.samplingMode = samplingMode;
  110743. return _this;
  110744. }
  110745. /**
  110746. * Execute the current task
  110747. * @param scene defines the scene where you want your assets to be loaded
  110748. * @param onSuccess is a callback called when the task is successfully executed
  110749. * @param onError is a callback called if an error occurs
  110750. */
  110751. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110752. var onload = function () {
  110753. onSuccess();
  110754. };
  110755. var onerror = function (message, exception) {
  110756. onError(message, exception);
  110757. };
  110758. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  110759. };
  110760. return TextureAssetTask;
  110761. }(AbstractAssetTask));
  110762. BABYLON.TextureAssetTask = TextureAssetTask;
  110763. /**
  110764. * Define a task used by AssetsManager to load cube textures
  110765. */
  110766. var CubeTextureAssetTask = /** @class */ (function (_super) {
  110767. __extends(CubeTextureAssetTask, _super);
  110768. /**
  110769. * Creates a new CubeTextureAssetTask
  110770. * @param name defines the name of the task
  110771. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  110772. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  110773. * @param noMipmap defines if mipmaps should not be generated (default is false)
  110774. * @param files defines the explicit list of files (undefined by default)
  110775. */
  110776. function CubeTextureAssetTask(
  110777. /**
  110778. * Defines the name of the task
  110779. */
  110780. name,
  110781. /**
  110782. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  110783. */
  110784. url,
  110785. /**
  110786. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  110787. */
  110788. extensions,
  110789. /**
  110790. * Defines if mipmaps should not be generated (default is false)
  110791. */
  110792. noMipmap,
  110793. /**
  110794. * Defines the explicit list of files (undefined by default)
  110795. */
  110796. files) {
  110797. var _this = _super.call(this, name) || this;
  110798. _this.name = name;
  110799. _this.url = url;
  110800. _this.extensions = extensions;
  110801. _this.noMipmap = noMipmap;
  110802. _this.files = files;
  110803. return _this;
  110804. }
  110805. /**
  110806. * Execute the current task
  110807. * @param scene defines the scene where you want your assets to be loaded
  110808. * @param onSuccess is a callback called when the task is successfully executed
  110809. * @param onError is a callback called if an error occurs
  110810. */
  110811. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  110812. var onload = function () {
  110813. onSuccess();
  110814. };
  110815. var onerror = function (message, exception) {
  110816. onError(message, exception);
  110817. };
  110818. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  110819. };
  110820. return CubeTextureAssetTask;
  110821. }(AbstractAssetTask));
  110822. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  110823. /**
  110824. * Define a task used by AssetsManager to load HDR cube textures
  110825. */
  110826. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  110827. __extends(HDRCubeTextureAssetTask, _super);
  110828. /**
  110829. * Creates a new HDRCubeTextureAssetTask object
  110830. * @param name defines the name of the task
  110831. * @param url defines the location of the file to load
  110832. * @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.
  110833. * @param noMipmap defines if mipmaps should not be generated (default is false)
  110834. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  110835. * @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)
  110836. * @param reserved Internal use only
  110837. */
  110838. function HDRCubeTextureAssetTask(
  110839. /**
  110840. * Defines the name of the task
  110841. */
  110842. name,
  110843. /**
  110844. * Defines the location of the file to load
  110845. */
  110846. url,
  110847. /**
  110848. * Defines the desired size (the more it increases the longer the generation will be)
  110849. */
  110850. size,
  110851. /**
  110852. * Defines if mipmaps should not be generated (default is false)
  110853. */
  110854. noMipmap,
  110855. /**
  110856. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  110857. */
  110858. generateHarmonics,
  110859. /**
  110860. * 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)
  110861. */
  110862. gammaSpace,
  110863. /**
  110864. * Internal Use Only
  110865. */
  110866. reserved) {
  110867. if (noMipmap === void 0) { noMipmap = false; }
  110868. if (generateHarmonics === void 0) { generateHarmonics = true; }
  110869. if (gammaSpace === void 0) { gammaSpace = false; }
  110870. if (reserved === void 0) { reserved = false; }
  110871. var _this = _super.call(this, name) || this;
  110872. _this.name = name;
  110873. _this.url = url;
  110874. _this.size = size;
  110875. _this.noMipmap = noMipmap;
  110876. _this.generateHarmonics = generateHarmonics;
  110877. _this.gammaSpace = gammaSpace;
  110878. _this.reserved = reserved;
  110879. return _this;
  110880. }
  110881. /**
  110882. * Execute the current task
  110883. * @param scene defines the scene where you want your assets to be loaded
  110884. * @param onSuccess is a callback called when the task is successfully executed
  110885. * @param onError is a callback called if an error occurs
  110886. */
  110887. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  110888. var onload = function () {
  110889. onSuccess();
  110890. };
  110891. var onerror = function (message, exception) {
  110892. onError(message, exception);
  110893. };
  110894. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  110895. };
  110896. return HDRCubeTextureAssetTask;
  110897. }(AbstractAssetTask));
  110898. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  110899. /**
  110900. * This class can be used to easily import assets into a scene
  110901. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  110902. */
  110903. var AssetsManager = /** @class */ (function () {
  110904. /**
  110905. * Creates a new AssetsManager
  110906. * @param scene defines the scene to work on
  110907. */
  110908. function AssetsManager(scene) {
  110909. this._isLoading = false;
  110910. this._tasks = new Array();
  110911. this._waitingTasksCount = 0;
  110912. this._totalTasksCount = 0;
  110913. /**
  110914. * Observable called when all tasks are processed
  110915. */
  110916. this.onTaskSuccessObservable = new BABYLON.Observable();
  110917. /**
  110918. * Observable called when a task had an error
  110919. */
  110920. this.onTaskErrorObservable = new BABYLON.Observable();
  110921. /**
  110922. * Observable called when a task is successful
  110923. */
  110924. this.onTasksDoneObservable = new BABYLON.Observable();
  110925. /**
  110926. * Observable called when a task is done (whatever the result is)
  110927. */
  110928. this.onProgressObservable = new BABYLON.Observable();
  110929. /**
  110930. * Gets or sets a boolean defining if the AssetsManager should use the default loading screen
  110931. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  110932. */
  110933. this.useDefaultLoadingScreen = true;
  110934. this._scene = scene;
  110935. }
  110936. /**
  110937. * Add a MeshAssetTask to the list of active tasks
  110938. * @param taskName defines the name of the new task
  110939. * @param meshesNames defines the name of meshes to load
  110940. * @param rootUrl defines the root url to use to locate files
  110941. * @param sceneFilename defines the filename of the scene file
  110942. * @returns a new MeshAssetTask object
  110943. */
  110944. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  110945. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  110946. this._tasks.push(task);
  110947. return task;
  110948. };
  110949. /**
  110950. * Add a TextFileAssetTask to the list of active tasks
  110951. * @param taskName defines the name of the new task
  110952. * @param url defines the url of the file to load
  110953. * @returns a new TextFileAssetTask object
  110954. */
  110955. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  110956. var task = new TextFileAssetTask(taskName, url);
  110957. this._tasks.push(task);
  110958. return task;
  110959. };
  110960. /**
  110961. * Add a BinaryFileAssetTask to the list of active tasks
  110962. * @param taskName defines the name of the new task
  110963. * @param url defines the url of the file to load
  110964. * @returns a new BinaryFileAssetTask object
  110965. */
  110966. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  110967. var task = new BinaryFileAssetTask(taskName, url);
  110968. this._tasks.push(task);
  110969. return task;
  110970. };
  110971. /**
  110972. * Add a ImageAssetTask to the list of active tasks
  110973. * @param taskName defines the name of the new task
  110974. * @param url defines the url of the file to load
  110975. * @returns a new ImageAssetTask object
  110976. */
  110977. AssetsManager.prototype.addImageTask = function (taskName, url) {
  110978. var task = new ImageAssetTask(taskName, url);
  110979. this._tasks.push(task);
  110980. return task;
  110981. };
  110982. /**
  110983. * Add a TextureAssetTask to the list of active tasks
  110984. * @param taskName defines the name of the new task
  110985. * @param url defines the url of the file to load
  110986. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  110987. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  110988. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  110989. * @returns a new TextureAssetTask object
  110990. */
  110991. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  110992. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  110993. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  110994. this._tasks.push(task);
  110995. return task;
  110996. };
  110997. /**
  110998. * Add a CubeTextureAssetTask to the list of active tasks
  110999. * @param taskName defines the name of the new task
  111000. * @param url defines the url of the file to load
  111001. * @param extensions defines the extension to use to load the cube map (can be null)
  111002. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111003. * @param files defines the list of files to load (can be null)
  111004. * @returns a new CubeTextureAssetTask object
  111005. */
  111006. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  111007. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  111008. this._tasks.push(task);
  111009. return task;
  111010. };
  111011. /**
  111012. *
  111013. * Add a HDRCubeTextureAssetTask to the list of active tasks
  111014. * @param taskName defines the name of the new task
  111015. * @param url defines the url of the file to load
  111016. * @param size defines the size you want for the cubemap (can be null)
  111017. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  111018. * @param generateHarmonics defines if you want to automatically generate (true by default)
  111019. * @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)
  111020. * @param reserved Internal use only
  111021. * @returns a new HDRCubeTextureAssetTask object
  111022. */
  111023. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  111024. if (noMipmap === void 0) { noMipmap = false; }
  111025. if (generateHarmonics === void 0) { generateHarmonics = true; }
  111026. if (gammaSpace === void 0) { gammaSpace = false; }
  111027. if (reserved === void 0) { reserved = false; }
  111028. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  111029. this._tasks.push(task);
  111030. return task;
  111031. };
  111032. /**
  111033. * Remove a task from the assets manager.
  111034. * @param task the task to remove
  111035. */
  111036. AssetsManager.prototype.removeTask = function (task) {
  111037. var index = this._tasks.indexOf(task);
  111038. if (index > -1) {
  111039. this._tasks.splice(index, 1);
  111040. }
  111041. };
  111042. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  111043. this._waitingTasksCount--;
  111044. try {
  111045. if (this.onProgress) {
  111046. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  111047. }
  111048. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  111049. }
  111050. catch (e) {
  111051. BABYLON.Tools.Error("Error running progress callbacks.");
  111052. console.log(e);
  111053. }
  111054. if (this._waitingTasksCount === 0) {
  111055. try {
  111056. if (this.onFinish) {
  111057. this.onFinish(this._tasks);
  111058. }
  111059. // Let's remove successfull tasks
  111060. var currentTasks = this._tasks.slice();
  111061. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  111062. var task = currentTasks_1[_i];
  111063. if (task.taskState === AssetTaskState.DONE) {
  111064. var index = this._tasks.indexOf(task);
  111065. if (index > -1) {
  111066. this._tasks.splice(index, 1);
  111067. }
  111068. }
  111069. }
  111070. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111071. }
  111072. catch (e) {
  111073. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  111074. console.log(e);
  111075. }
  111076. this._isLoading = false;
  111077. this._scene.getEngine().hideLoadingUI();
  111078. }
  111079. };
  111080. AssetsManager.prototype._runTask = function (task) {
  111081. var _this = this;
  111082. var done = function () {
  111083. try {
  111084. if (_this.onTaskSuccess) {
  111085. _this.onTaskSuccess(task);
  111086. }
  111087. _this.onTaskSuccessObservable.notifyObservers(task);
  111088. _this._decreaseWaitingTasksCount(task);
  111089. }
  111090. catch (e) {
  111091. error("Error executing task success callbacks", e);
  111092. }
  111093. };
  111094. var error = function (message, exception) {
  111095. task._setErrorObject(message, exception);
  111096. if (_this.onTaskError) {
  111097. _this.onTaskError(task);
  111098. }
  111099. _this.onTaskErrorObservable.notifyObservers(task);
  111100. _this._decreaseWaitingTasksCount(task);
  111101. };
  111102. task.run(this._scene, done, error);
  111103. };
  111104. /**
  111105. * Reset the AssetsManager and remove all tasks
  111106. * @return the current instance of the AssetsManager
  111107. */
  111108. AssetsManager.prototype.reset = function () {
  111109. this._isLoading = false;
  111110. this._tasks = new Array();
  111111. return this;
  111112. };
  111113. /**
  111114. * Start the loading process
  111115. * @return the current instance of the AssetsManager
  111116. */
  111117. AssetsManager.prototype.load = function () {
  111118. if (this._isLoading) {
  111119. return this;
  111120. }
  111121. this._isLoading = true;
  111122. this._waitingTasksCount = this._tasks.length;
  111123. this._totalTasksCount = this._tasks.length;
  111124. if (this._waitingTasksCount === 0) {
  111125. this._isLoading = false;
  111126. if (this.onFinish) {
  111127. this.onFinish(this._tasks);
  111128. }
  111129. this.onTasksDoneObservable.notifyObservers(this._tasks);
  111130. return this;
  111131. }
  111132. if (this.useDefaultLoadingScreen) {
  111133. this._scene.getEngine().displayLoadingUI();
  111134. }
  111135. for (var index = 0; index < this._tasks.length; index++) {
  111136. var task = this._tasks[index];
  111137. if (task.taskState === AssetTaskState.INIT) {
  111138. this._runTask(task);
  111139. }
  111140. }
  111141. return this;
  111142. };
  111143. return AssetsManager;
  111144. }());
  111145. BABYLON.AssetsManager = AssetsManager;
  111146. })(BABYLON || (BABYLON = {}));
  111147. //# sourceMappingURL=babylon.assetsManager.js.map
  111148. var BABYLON;
  111149. (function (BABYLON) {
  111150. var serializedGeometries = [];
  111151. var serializeGeometry = function (geometry, serializationGeometries) {
  111152. if (serializedGeometries[geometry.id]) {
  111153. return;
  111154. }
  111155. if (geometry.doNotSerialize) {
  111156. return;
  111157. }
  111158. if (geometry instanceof BABYLON.BoxGeometry) {
  111159. serializationGeometries.boxes.push(geometry.serialize());
  111160. }
  111161. else if (geometry instanceof BABYLON.SphereGeometry) {
  111162. serializationGeometries.spheres.push(geometry.serialize());
  111163. }
  111164. else if (geometry instanceof BABYLON.CylinderGeometry) {
  111165. serializationGeometries.cylinders.push(geometry.serialize());
  111166. }
  111167. else if (geometry instanceof BABYLON.TorusGeometry) {
  111168. serializationGeometries.toruses.push(geometry.serialize());
  111169. }
  111170. else if (geometry instanceof BABYLON.GroundGeometry) {
  111171. serializationGeometries.grounds.push(geometry.serialize());
  111172. }
  111173. else if (geometry instanceof BABYLON.Plane) {
  111174. serializationGeometries.planes.push(geometry.serialize());
  111175. }
  111176. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  111177. serializationGeometries.torusKnots.push(geometry.serialize());
  111178. }
  111179. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  111180. throw new Error("Unknown primitive type");
  111181. }
  111182. else {
  111183. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  111184. }
  111185. serializedGeometries[geometry.id] = true;
  111186. };
  111187. var serializeMesh = function (mesh, serializationScene) {
  111188. var serializationObject = {};
  111189. // Geometry
  111190. var geometry = mesh._geometry;
  111191. if (geometry) {
  111192. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  111193. // 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
  111194. serializeGeometry(geometry, serializationScene.geometries);
  111195. }
  111196. }
  111197. // Custom
  111198. if (mesh.serialize) {
  111199. mesh.serialize(serializationObject);
  111200. }
  111201. return serializationObject;
  111202. };
  111203. var finalizeSingleMesh = function (mesh, serializationObject) {
  111204. //only works if the mesh is already loaded
  111205. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111206. //serialize material
  111207. if (mesh.material) {
  111208. if (mesh.material instanceof BABYLON.MultiMaterial) {
  111209. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  111210. serializationObject.materials = serializationObject.materials || [];
  111211. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111212. serializationObject.multiMaterials.push(mesh.material.serialize());
  111213. var _loop_1 = function (submaterial) {
  111214. if (submaterial) {
  111215. if (!serializationObject.materials.some(function (mat) { return (mat.id === submaterial.id); })) {
  111216. serializationObject.materials.push(submaterial.serialize());
  111217. }
  111218. }
  111219. };
  111220. for (var _i = 0, _a = mesh.material.subMaterials; _i < _a.length; _i++) {
  111221. var submaterial = _a[_i];
  111222. _loop_1(submaterial);
  111223. }
  111224. }
  111225. }
  111226. else {
  111227. serializationObject.materials = serializationObject.materials || [];
  111228. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  111229. serializationObject.materials.push(mesh.material.serialize());
  111230. }
  111231. }
  111232. }
  111233. //serialize geometry
  111234. var geometry = mesh._geometry;
  111235. if (geometry) {
  111236. if (!serializationObject.geometries) {
  111237. serializationObject.geometries = {};
  111238. serializationObject.geometries.boxes = [];
  111239. serializationObject.geometries.spheres = [];
  111240. serializationObject.geometries.cylinders = [];
  111241. serializationObject.geometries.toruses = [];
  111242. serializationObject.geometries.grounds = [];
  111243. serializationObject.geometries.planes = [];
  111244. serializationObject.geometries.torusKnots = [];
  111245. serializationObject.geometries.vertexData = [];
  111246. }
  111247. serializeGeometry(geometry, serializationObject.geometries);
  111248. }
  111249. // Skeletons
  111250. if (mesh.skeleton) {
  111251. serializationObject.skeletons = serializationObject.skeletons || [];
  111252. serializationObject.skeletons.push(mesh.skeleton.serialize());
  111253. }
  111254. //serialize the actual mesh
  111255. serializationObject.meshes = serializationObject.meshes || [];
  111256. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111257. }
  111258. };
  111259. /**
  111260. * Class used to serialize a scene into a string
  111261. */
  111262. var SceneSerializer = /** @class */ (function () {
  111263. function SceneSerializer() {
  111264. }
  111265. /**
  111266. * Clear cache used by a previous serialization
  111267. */
  111268. SceneSerializer.ClearCache = function () {
  111269. serializedGeometries = [];
  111270. };
  111271. /**
  111272. * Serialize a scene into a JSON compatible object
  111273. * @param scene defines the scene to serialize
  111274. * @returns a JSON compatible object
  111275. */
  111276. SceneSerializer.Serialize = function (scene) {
  111277. var serializationObject = {};
  111278. SceneSerializer.ClearCache();
  111279. // Scene
  111280. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  111281. serializationObject.autoClear = scene.autoClear;
  111282. serializationObject.clearColor = scene.clearColor.asArray();
  111283. serializationObject.ambientColor = scene.ambientColor.asArray();
  111284. serializationObject.gravity = scene.gravity.asArray();
  111285. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  111286. serializationObject.workerCollisions = scene.workerCollisions;
  111287. // Fog
  111288. if (scene.fogMode && scene.fogMode !== 0) {
  111289. serializationObject.fogMode = scene.fogMode;
  111290. serializationObject.fogColor = scene.fogColor.asArray();
  111291. serializationObject.fogStart = scene.fogStart;
  111292. serializationObject.fogEnd = scene.fogEnd;
  111293. serializationObject.fogDensity = scene.fogDensity;
  111294. }
  111295. //Physics
  111296. if (scene.isPhysicsEnabled()) {
  111297. var physicEngine = scene.getPhysicsEngine();
  111298. if (physicEngine) {
  111299. serializationObject.physicsEnabled = true;
  111300. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  111301. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  111302. }
  111303. }
  111304. // Metadata
  111305. if (scene.metadata) {
  111306. serializationObject.metadata = scene.metadata;
  111307. }
  111308. // Morph targets
  111309. serializationObject.morphTargetManagers = [];
  111310. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  111311. var abstractMesh = _a[_i];
  111312. var manager = abstractMesh.morphTargetManager;
  111313. if (manager) {
  111314. serializationObject.morphTargetManagers.push(manager.serialize());
  111315. }
  111316. }
  111317. // Lights
  111318. serializationObject.lights = [];
  111319. var index;
  111320. var light;
  111321. for (index = 0; index < scene.lights.length; index++) {
  111322. light = scene.lights[index];
  111323. if (!light.doNotSerialize) {
  111324. serializationObject.lights.push(light.serialize());
  111325. }
  111326. }
  111327. // Cameras
  111328. serializationObject.cameras = [];
  111329. for (index = 0; index < scene.cameras.length; index++) {
  111330. var camera = scene.cameras[index];
  111331. if (!camera.doNotSerialize) {
  111332. serializationObject.cameras.push(camera.serialize());
  111333. }
  111334. }
  111335. if (scene.activeCamera) {
  111336. serializationObject.activeCameraID = scene.activeCamera.id;
  111337. }
  111338. // Animations
  111339. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  111340. // Materials
  111341. serializationObject.materials = [];
  111342. serializationObject.multiMaterials = [];
  111343. var material;
  111344. for (index = 0; index < scene.materials.length; index++) {
  111345. material = scene.materials[index];
  111346. if (!material.doNotSerialize) {
  111347. serializationObject.materials.push(material.serialize());
  111348. }
  111349. }
  111350. // MultiMaterials
  111351. serializationObject.multiMaterials = [];
  111352. for (index = 0; index < scene.multiMaterials.length; index++) {
  111353. var multiMaterial = scene.multiMaterials[index];
  111354. serializationObject.multiMaterials.push(multiMaterial.serialize());
  111355. }
  111356. // Environment texture
  111357. if (scene.environmentTexture) {
  111358. serializationObject.environmentTexture = scene.environmentTexture.name;
  111359. }
  111360. // Skeletons
  111361. serializationObject.skeletons = [];
  111362. for (index = 0; index < scene.skeletons.length; index++) {
  111363. var skeleton = scene.skeletons[index];
  111364. if (!skeleton.doNotSerialize) {
  111365. serializationObject.skeletons.push(skeleton.serialize());
  111366. }
  111367. }
  111368. // Transform nodes
  111369. serializationObject.transformNodes = [];
  111370. for (index = 0; index < scene.transformNodes.length; index++) {
  111371. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  111372. }
  111373. // Geometries
  111374. serializationObject.geometries = {};
  111375. serializationObject.geometries.boxes = [];
  111376. serializationObject.geometries.spheres = [];
  111377. serializationObject.geometries.cylinders = [];
  111378. serializationObject.geometries.toruses = [];
  111379. serializationObject.geometries.grounds = [];
  111380. serializationObject.geometries.planes = [];
  111381. serializationObject.geometries.torusKnots = [];
  111382. serializationObject.geometries.vertexData = [];
  111383. serializedGeometries = [];
  111384. var geometries = scene.getGeometries();
  111385. for (index = 0; index < geometries.length; index++) {
  111386. var geometry = geometries[index];
  111387. if (geometry.isReady()) {
  111388. serializeGeometry(geometry, serializationObject.geometries);
  111389. }
  111390. }
  111391. // Meshes
  111392. serializationObject.meshes = [];
  111393. for (index = 0; index < scene.meshes.length; index++) {
  111394. var abstractMesh = scene.meshes[index];
  111395. if (abstractMesh instanceof BABYLON.Mesh) {
  111396. var mesh = abstractMesh;
  111397. if (!mesh.doNotSerialize) {
  111398. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  111399. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  111400. }
  111401. }
  111402. }
  111403. }
  111404. // Particles Systems
  111405. serializationObject.particleSystems = [];
  111406. for (index = 0; index < scene.particleSystems.length; index++) {
  111407. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  111408. }
  111409. // Action Manager
  111410. if (scene.actionManager) {
  111411. serializationObject.actions = scene.actionManager.serialize("scene");
  111412. }
  111413. // Components
  111414. for (var _b = 0, _c = scene._serializableComponents; _b < _c.length; _b++) {
  111415. var component = _c[_b];
  111416. component.serialize(serializationObject);
  111417. }
  111418. return serializationObject;
  111419. };
  111420. /**
  111421. * Serialize a mesh into a JSON compatible object
  111422. * @param toSerialize defines the mesh to serialize
  111423. * @param withParents defines if parents must be serialized as well
  111424. * @param withChildren defines if children must be serialized as well
  111425. * @returns a JSON compatible object
  111426. */
  111427. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  111428. if (withParents === void 0) { withParents = false; }
  111429. if (withChildren === void 0) { withChildren = false; }
  111430. var serializationObject = {};
  111431. SceneSerializer.ClearCache();
  111432. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  111433. if (withParents || withChildren) {
  111434. //deliberate for loop! not for each, appended should be processed as well.
  111435. for (var i = 0; i < toSerialize.length; ++i) {
  111436. if (withChildren) {
  111437. toSerialize[i].getDescendants().forEach(function (node) {
  111438. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  111439. toSerialize.push(node);
  111440. }
  111441. });
  111442. }
  111443. //make sure the array doesn't contain the object already
  111444. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  111445. toSerialize.push(toSerialize[i].parent);
  111446. }
  111447. }
  111448. }
  111449. toSerialize.forEach(function (mesh) {
  111450. finalizeSingleMesh(mesh, serializationObject);
  111451. });
  111452. return serializationObject;
  111453. };
  111454. return SceneSerializer;
  111455. }());
  111456. BABYLON.SceneSerializer = SceneSerializer;
  111457. })(BABYLON || (BABYLON = {}));
  111458. //# sourceMappingURL=babylon.sceneSerializer.js.map
  111459. var BABYLON;
  111460. (function (BABYLON) {
  111461. /**
  111462. * Class used to generate realtime reflection / refraction cube textures
  111463. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  111464. */
  111465. var ReflectionProbe = /** @class */ (function () {
  111466. /**
  111467. * Creates a new reflection probe
  111468. * @param name defines the name of the probe
  111469. * @param size defines the texture resolution (for each face)
  111470. * @param scene defines the hosting scene
  111471. * @param generateMipMaps defines if mip maps should be generated automatically (true by default)
  111472. * @param useFloat defines if HDR data (flaot data) should be used to store colors (false by default)
  111473. */
  111474. function ReflectionProbe(
  111475. /** defines the name of the probe */
  111476. name, size, scene, generateMipMaps, useFloat) {
  111477. if (generateMipMaps === void 0) { generateMipMaps = true; }
  111478. if (useFloat === void 0) { useFloat = false; }
  111479. var _this = this;
  111480. this.name = name;
  111481. this._viewMatrix = BABYLON.Matrix.Identity();
  111482. this._target = BABYLON.Vector3.Zero();
  111483. this._add = BABYLON.Vector3.Zero();
  111484. this._invertYAxis = false;
  111485. /** Gets or sets probe position (center of the cube map) */
  111486. this.position = BABYLON.Vector3.Zero();
  111487. this._scene = scene;
  111488. // Create the scene field if not exist.
  111489. if (!this._scene.reflectionProbes) {
  111490. this._scene.reflectionProbes = new Array();
  111491. }
  111492. this._scene.reflectionProbes.push(this);
  111493. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, useFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  111494. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  111495. switch (faceIndex) {
  111496. case 0:
  111497. _this._add.copyFromFloats(1, 0, 0);
  111498. break;
  111499. case 1:
  111500. _this._add.copyFromFloats(-1, 0, 0);
  111501. break;
  111502. case 2:
  111503. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  111504. break;
  111505. case 3:
  111506. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  111507. break;
  111508. case 4:
  111509. _this._add.copyFromFloats(0, 0, 1);
  111510. break;
  111511. case 5:
  111512. _this._add.copyFromFloats(0, 0, -1);
  111513. break;
  111514. }
  111515. if (_this._attachedMesh) {
  111516. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  111517. }
  111518. _this.position.addToRef(_this._add, _this._target);
  111519. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  111520. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  111521. scene._forcedViewPosition = _this.position;
  111522. });
  111523. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  111524. scene._forcedViewPosition = null;
  111525. scene.updateTransformMatrix(true);
  111526. });
  111527. if (scene.activeCamera) {
  111528. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  111529. }
  111530. }
  111531. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  111532. /** Gets or sets the number of samples to use for multi-sampling (0 by default). Required WebGL2 */
  111533. get: function () {
  111534. return this._renderTargetTexture.samples;
  111535. },
  111536. set: function (value) {
  111537. this._renderTargetTexture.samples = value;
  111538. },
  111539. enumerable: true,
  111540. configurable: true
  111541. });
  111542. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  111543. /** Gets or sets the refresh rate to use (on every frame by default) */
  111544. get: function () {
  111545. return this._renderTargetTexture.refreshRate;
  111546. },
  111547. set: function (value) {
  111548. this._renderTargetTexture.refreshRate = value;
  111549. },
  111550. enumerable: true,
  111551. configurable: true
  111552. });
  111553. /**
  111554. * Gets the hosting scene
  111555. * @returns a Scene
  111556. */
  111557. ReflectionProbe.prototype.getScene = function () {
  111558. return this._scene;
  111559. };
  111560. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  111561. /** Gets the internal CubeTexture used to render to */
  111562. get: function () {
  111563. return this._renderTargetTexture;
  111564. },
  111565. enumerable: true,
  111566. configurable: true
  111567. });
  111568. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  111569. /** Gets the list of meshes to render */
  111570. get: function () {
  111571. return this._renderTargetTexture.renderList;
  111572. },
  111573. enumerable: true,
  111574. configurable: true
  111575. });
  111576. /**
  111577. * Attach the probe to a specific mesh (Rendering will be done from attached mesh's position)
  111578. * @param mesh defines the mesh to attach to
  111579. */
  111580. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  111581. this._attachedMesh = mesh;
  111582. };
  111583. /**
  111584. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups
  111585. * @param renderingGroupId The rendering group id corresponding to its index
  111586. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  111587. */
  111588. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  111589. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  111590. };
  111591. /**
  111592. * Clean all associated resources
  111593. */
  111594. ReflectionProbe.prototype.dispose = function () {
  111595. var index = this._scene.reflectionProbes.indexOf(this);
  111596. if (index !== -1) {
  111597. // Remove from the scene if found
  111598. this._scene.reflectionProbes.splice(index, 1);
  111599. }
  111600. if (this._renderTargetTexture) {
  111601. this._renderTargetTexture.dispose();
  111602. this._renderTargetTexture = null;
  111603. }
  111604. };
  111605. return ReflectionProbe;
  111606. }());
  111607. BABYLON.ReflectionProbe = ReflectionProbe;
  111608. })(BABYLON || (BABYLON = {}));
  111609. //# sourceMappingURL=babylon.reflectionProbe.js.map
  111610. var BABYLON;
  111611. (function (BABYLON) {
  111612. /**
  111613. * Defines the layer scene component responsible to manage any layers
  111614. * in a given scene.
  111615. */
  111616. var LayerSceneComponent = /** @class */ (function () {
  111617. /**
  111618. * Creates a new instance of the component for the given scene
  111619. * @param scene Defines the scene to register the component in
  111620. */
  111621. function LayerSceneComponent(scene) {
  111622. /**
  111623. * The component name helpfull to identify the component in the list of scene components.
  111624. */
  111625. this.name = BABYLON.SceneComponentConstants.NAME_LAYER;
  111626. this.scene = scene;
  111627. this._engine = scene.getEngine();
  111628. scene.layers = new Array();
  111629. }
  111630. /**
  111631. * Registers the component in a given scene
  111632. */
  111633. LayerSceneComponent.prototype.register = function () {
  111634. this.scene._beforeCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_BEFORECAMERADRAW_LAYER, this, this._drawBackground);
  111635. this.scene._afterCameraDrawStage.registerStep(BABYLON.SceneComponentConstants.STEP_AFTERCAMERADRAW_LAYER, this, this._drawForeground);
  111636. };
  111637. /**
  111638. * Rebuilds the elements related to this component in case of
  111639. * context lost for instance.
  111640. */
  111641. LayerSceneComponent.prototype.rebuild = function () {
  111642. var layers = this.scene.layers;
  111643. for (var _i = 0, layers_1 = layers; _i < layers_1.length; _i++) {
  111644. var layer = layers_1[_i];
  111645. layer._rebuild();
  111646. }
  111647. };
  111648. /**
  111649. * Disposes the component and the associated ressources.
  111650. */
  111651. LayerSceneComponent.prototype.dispose = function () {
  111652. var layers = this.scene.layers;
  111653. while (layers.length) {
  111654. layers[0].dispose();
  111655. }
  111656. };
  111657. LayerSceneComponent.prototype._draw = function (camera, isBackground) {
  111658. var layers = this.scene.layers;
  111659. if (layers.length) {
  111660. this._engine.setDepthBuffer(false);
  111661. var cameraLayerMask = camera.layerMask;
  111662. for (var _i = 0, layers_2 = layers; _i < layers_2.length; _i++) {
  111663. var layer = layers_2[_i];
  111664. if (layer.isBackground === isBackground && ((layer.layerMask & cameraLayerMask) !== 0)) {
  111665. layer.render();
  111666. }
  111667. }
  111668. this._engine.setDepthBuffer(true);
  111669. }
  111670. };
  111671. LayerSceneComponent.prototype._drawBackground = function (camera) {
  111672. this._draw(camera, true);
  111673. };
  111674. LayerSceneComponent.prototype._drawForeground = function (camera) {
  111675. this._draw(camera, false);
  111676. };
  111677. return LayerSceneComponent;
  111678. }());
  111679. BABYLON.LayerSceneComponent = LayerSceneComponent;
  111680. })(BABYLON || (BABYLON = {}));
  111681. //# sourceMappingURL=babylon.layerSceneComponent.js.map
  111682. var BABYLON;
  111683. (function (BABYLON) {
  111684. /**
  111685. * This represents a full screen 2d layer.
  111686. * This can be usefull to display a picture in the background of your scene for instance.
  111687. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111688. */
  111689. var Layer = /** @class */ (function () {
  111690. /**
  111691. * Instantiates a new layer.
  111692. * This represents a full screen 2d layer.
  111693. * This can be usefull to display a picture in the background of your scene for instance.
  111694. * @see https://www.babylonjs-playground.com/#08A2BS#1
  111695. * @param name Define the name of the layer in the scene
  111696. * @param imgUrl Define the url of the texture to display in the layer
  111697. * @param scene Define the scene the layer belongs to
  111698. * @param isBackground Defines whether the layer is displayed in front or behind the scene
  111699. * @param color Defines a color for the layer
  111700. */
  111701. function Layer(
  111702. /**
  111703. * Define the name of the layer.
  111704. */
  111705. name, imgUrl, scene, isBackground, color) {
  111706. this.name = name;
  111707. /**
  111708. * Define the scale of the layer in order to zoom in out of the texture.
  111709. */
  111710. this.scale = new BABYLON.Vector2(1, 1);
  111711. /**
  111712. * Define an offset for the layer in order to shift the texture.
  111713. */
  111714. this.offset = new BABYLON.Vector2(0, 0);
  111715. /**
  111716. * Define the alpha blending mode used in the layer in case the texture or color has an alpha.
  111717. */
  111718. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  111719. /**
  111720. * Define a mask to restrict the layer to only some of the scene cameras.
  111721. */
  111722. this.layerMask = 0x0FFFFFFF;
  111723. this._vertexBuffers = {};
  111724. /**
  111725. * An event triggered when the layer is disposed.
  111726. */
  111727. this.onDisposeObservable = new BABYLON.Observable();
  111728. /**
  111729. * An event triggered before rendering the scene
  111730. */
  111731. this.onBeforeRenderObservable = new BABYLON.Observable();
  111732. /**
  111733. * An event triggered after rendering the scene
  111734. */
  111735. this.onAfterRenderObservable = new BABYLON.Observable();
  111736. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  111737. this.isBackground = isBackground === undefined ? true : isBackground;
  111738. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  111739. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  111740. var layerComponent = this._scene._getComponent(BABYLON.SceneComponentConstants.NAME_LAYER);
  111741. if (!layerComponent) {
  111742. layerComponent = new BABYLON.LayerSceneComponent(this._scene);
  111743. this._scene._addComponent(layerComponent);
  111744. }
  111745. this._scene.layers.push(this);
  111746. var engine = this._scene.getEngine();
  111747. // VBO
  111748. var vertices = [];
  111749. vertices.push(1, 1);
  111750. vertices.push(-1, 1);
  111751. vertices.push(-1, -1);
  111752. vertices.push(1, -1);
  111753. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  111754. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  111755. this._createIndexBuffer();
  111756. // Effects
  111757. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  111758. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  111759. }
  111760. Object.defineProperty(Layer.prototype, "onDispose", {
  111761. /**
  111762. * Back compatibility with callback before the onDisposeObservable existed.
  111763. * The set callback will be triggered when the layer has been disposed.
  111764. */
  111765. set: function (callback) {
  111766. if (this._onDisposeObserver) {
  111767. this.onDisposeObservable.remove(this._onDisposeObserver);
  111768. }
  111769. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  111770. },
  111771. enumerable: true,
  111772. configurable: true
  111773. });
  111774. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  111775. /**
  111776. * Back compatibility with callback before the onBeforeRenderObservable existed.
  111777. * The set callback will be triggered just before rendering the layer.
  111778. */
  111779. set: function (callback) {
  111780. if (this._onBeforeRenderObserver) {
  111781. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  111782. }
  111783. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  111784. },
  111785. enumerable: true,
  111786. configurable: true
  111787. });
  111788. Object.defineProperty(Layer.prototype, "onAfterRender", {
  111789. /**
  111790. * Back compatibility with callback before the onAfterRenderObservable existed.
  111791. * The set callback will be triggered just after rendering the layer.
  111792. */
  111793. set: function (callback) {
  111794. if (this._onAfterRenderObserver) {
  111795. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  111796. }
  111797. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  111798. },
  111799. enumerable: true,
  111800. configurable: true
  111801. });
  111802. Layer.prototype._createIndexBuffer = function () {
  111803. var engine = this._scene.getEngine();
  111804. // Indices
  111805. var indices = [];
  111806. indices.push(0);
  111807. indices.push(1);
  111808. indices.push(2);
  111809. indices.push(0);
  111810. indices.push(2);
  111811. indices.push(3);
  111812. this._indexBuffer = engine.createIndexBuffer(indices);
  111813. };
  111814. /** @hidden */
  111815. Layer.prototype._rebuild = function () {
  111816. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111817. if (vb) {
  111818. vb._rebuild();
  111819. }
  111820. this._createIndexBuffer();
  111821. };
  111822. /**
  111823. * Renders the layer in the scene.
  111824. */
  111825. Layer.prototype.render = function () {
  111826. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  111827. // Check
  111828. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  111829. return;
  111830. var engine = this._scene.getEngine();
  111831. this.onBeforeRenderObservable.notifyObservers(this);
  111832. // Render
  111833. engine.enableEffect(currentEffect);
  111834. engine.setState(false);
  111835. // Texture
  111836. currentEffect.setTexture("textureSampler", this.texture);
  111837. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  111838. // Color
  111839. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  111840. // Scale / offset
  111841. currentEffect.setVector2("offset", this.offset);
  111842. currentEffect.setVector2("scale", this.scale);
  111843. // VBOs
  111844. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  111845. // Draw order
  111846. if (!this.alphaTest) {
  111847. engine.setAlphaMode(this.alphaBlendingMode);
  111848. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111849. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  111850. }
  111851. else {
  111852. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  111853. }
  111854. this.onAfterRenderObservable.notifyObservers(this);
  111855. };
  111856. /**
  111857. * Disposes and releases the associated ressources.
  111858. */
  111859. Layer.prototype.dispose = function () {
  111860. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  111861. if (vertexBuffer) {
  111862. vertexBuffer.dispose();
  111863. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  111864. }
  111865. if (this._indexBuffer) {
  111866. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  111867. this._indexBuffer = null;
  111868. }
  111869. if (this.texture) {
  111870. this.texture.dispose();
  111871. this.texture = null;
  111872. }
  111873. // Remove from scene
  111874. var index = this._scene.layers.indexOf(this);
  111875. this._scene.layers.splice(index, 1);
  111876. // Callback
  111877. this.onDisposeObservable.notifyObservers(this);
  111878. this.onDisposeObservable.clear();
  111879. this.onAfterRenderObservable.clear();
  111880. this.onBeforeRenderObservable.clear();
  111881. };
  111882. return Layer;
  111883. }());
  111884. BABYLON.Layer = Layer;
  111885. })(BABYLON || (BABYLON = {}));
  111886. //# sourceMappingURL=babylon.layer.js.map
  111887. var BABYLON;
  111888. (function (BABYLON) {
  111889. /**
  111890. * Class used to host texture specific utilities
  111891. */
  111892. var TextureTools = /** @class */ (function () {
  111893. function TextureTools() {
  111894. }
  111895. /**
  111896. * Uses the GPU to create a copy texture rescaled at a given size
  111897. * @param texture Texture to copy from
  111898. * @param width defines the desired width
  111899. * @param height defines the desired height
  111900. * @param useBilinearMode defines if bilinear mode has to be used
  111901. * @return the generated texture
  111902. */
  111903. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  111904. if (useBilinearMode === void 0) { useBilinearMode = true; }
  111905. var scene = texture.getScene();
  111906. var engine = scene.getEngine();
  111907. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  111908. rtt.wrapU = texture.wrapU;
  111909. rtt.wrapV = texture.wrapV;
  111910. rtt.uOffset = texture.uOffset;
  111911. rtt.vOffset = texture.vOffset;
  111912. rtt.uScale = texture.uScale;
  111913. rtt.vScale = texture.vScale;
  111914. rtt.uAng = texture.uAng;
  111915. rtt.vAng = texture.vAng;
  111916. rtt.wAng = texture.wAng;
  111917. rtt.coordinatesIndex = texture.coordinatesIndex;
  111918. rtt.level = texture.level;
  111919. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  111920. rtt._texture.isReady = false;
  111921. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111922. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111923. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  111924. passPostProcess.getEffect().executeWhenCompiled(function () {
  111925. passPostProcess.onApply = function (effect) {
  111926. effect.setTexture("textureSampler", texture);
  111927. };
  111928. var internalTexture = rtt.getInternalTexture();
  111929. if (internalTexture) {
  111930. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  111931. engine.unBindFramebuffer(internalTexture);
  111932. rtt.disposeFramebufferObjects();
  111933. passPostProcess.dispose();
  111934. internalTexture.isReady = true;
  111935. }
  111936. });
  111937. return rtt;
  111938. };
  111939. /**
  111940. * Gets an environment BRDF texture for a given scene
  111941. * @param scene defines the hosting scene
  111942. * @returns the environment BRDF texture
  111943. */
  111944. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  111945. if (!scene._environmentBRDFTexture) {
  111946. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  111947. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111948. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  111949. scene._environmentBRDFTexture = texture;
  111950. }
  111951. return scene._environmentBRDFTexture;
  111952. };
  111953. 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=";
  111954. return TextureTools;
  111955. }());
  111956. BABYLON.TextureTools = TextureTools;
  111957. })(BABYLON || (BABYLON = {}));
  111958. //# sourceMappingURL=babylon.textureTools.js.map
  111959. var BABYLON;
  111960. (function (BABYLON) {
  111961. /**
  111962. * 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.
  111963. * @see http://doc.babylonjs.com/how_to/camera_behaviors#framing-behavior
  111964. */
  111965. var FramingBehavior = /** @class */ (function () {
  111966. function FramingBehavior() {
  111967. this._mode = FramingBehavior.FitFrustumSidesMode;
  111968. this._radiusScale = 1.0;
  111969. this._positionScale = 0.5;
  111970. this._defaultElevation = 0.3;
  111971. this._elevationReturnTime = 1500;
  111972. this._elevationReturnWaitTime = 1000;
  111973. this._zoomStopsAnimation = false;
  111974. this._framingTime = 1500;
  111975. /**
  111976. * Define if the behavior should automatically change the configured
  111977. * camera limits and sensibilities.
  111978. */
  111979. this.autoCorrectCameraLimitsAndSensibility = true;
  111980. this._isPointerDown = false;
  111981. this._lastInteractionTime = -Infinity;
  111982. // Framing control
  111983. this._animatables = new Array();
  111984. this._betaIsAnimating = false;
  111985. }
  111986. Object.defineProperty(FramingBehavior.prototype, "name", {
  111987. /**
  111988. * Gets the name of the behavior.
  111989. */
  111990. get: function () {
  111991. return "Framing";
  111992. },
  111993. enumerable: true,
  111994. configurable: true
  111995. });
  111996. Object.defineProperty(FramingBehavior.prototype, "mode", {
  111997. /**
  111998. * Gets current mode used by the behavior.
  111999. */
  112000. get: function () {
  112001. return this._mode;
  112002. },
  112003. /**
  112004. * Sets the current mode used by the behavior
  112005. */
  112006. set: function (mode) {
  112007. this._mode = mode;
  112008. },
  112009. enumerable: true,
  112010. configurable: true
  112011. });
  112012. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  112013. /**
  112014. * Gets the scale applied to the radius
  112015. */
  112016. get: function () {
  112017. return this._radiusScale;
  112018. },
  112019. /**
  112020. * Sets the scale applied to the radius (1 by default)
  112021. */
  112022. set: function (radius) {
  112023. this._radiusScale = radius;
  112024. },
  112025. enumerable: true,
  112026. configurable: true
  112027. });
  112028. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  112029. /**
  112030. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112031. */
  112032. get: function () {
  112033. return this._positionScale;
  112034. },
  112035. /**
  112036. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  112037. */
  112038. set: function (scale) {
  112039. this._positionScale = scale;
  112040. },
  112041. enumerable: true,
  112042. configurable: true
  112043. });
  112044. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  112045. /**
  112046. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112047. * behaviour is triggered, in radians.
  112048. */
  112049. get: function () {
  112050. return this._defaultElevation;
  112051. },
  112052. /**
  112053. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  112054. * behaviour is triggered, in radians.
  112055. */
  112056. set: function (elevation) {
  112057. this._defaultElevation = elevation;
  112058. },
  112059. enumerable: true,
  112060. configurable: true
  112061. });
  112062. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  112063. /**
  112064. * Gets the time (in milliseconds) taken to return to the default beta position.
  112065. * Negative value indicates camera should not return to default.
  112066. */
  112067. get: function () {
  112068. return this._elevationReturnTime;
  112069. },
  112070. /**
  112071. * Sets the time (in milliseconds) taken to return to the default beta position.
  112072. * Negative value indicates camera should not return to default.
  112073. */
  112074. set: function (speed) {
  112075. this._elevationReturnTime = speed;
  112076. },
  112077. enumerable: true,
  112078. configurable: true
  112079. });
  112080. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  112081. /**
  112082. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112083. */
  112084. get: function () {
  112085. return this._elevationReturnWaitTime;
  112086. },
  112087. /**
  112088. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  112089. */
  112090. set: function (time) {
  112091. this._elevationReturnWaitTime = time;
  112092. },
  112093. enumerable: true,
  112094. configurable: true
  112095. });
  112096. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  112097. /**
  112098. * Gets the flag that indicates if user zooming should stop animation.
  112099. */
  112100. get: function () {
  112101. return this._zoomStopsAnimation;
  112102. },
  112103. /**
  112104. * Sets the flag that indicates if user zooming should stop animation.
  112105. */
  112106. set: function (flag) {
  112107. this._zoomStopsAnimation = flag;
  112108. },
  112109. enumerable: true,
  112110. configurable: true
  112111. });
  112112. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  112113. /**
  112114. * Gets the transition time when framing the mesh, in milliseconds
  112115. */
  112116. get: function () {
  112117. return this._framingTime;
  112118. },
  112119. /**
  112120. * Sets the transition time when framing the mesh, in milliseconds
  112121. */
  112122. set: function (time) {
  112123. this._framingTime = time;
  112124. },
  112125. enumerable: true,
  112126. configurable: true
  112127. });
  112128. /**
  112129. * Initializes the behavior.
  112130. */
  112131. FramingBehavior.prototype.init = function () {
  112132. // Do notihng
  112133. };
  112134. /**
  112135. * Attaches the behavior to its arc rotate camera.
  112136. * @param camera Defines the camera to attach the behavior to
  112137. */
  112138. FramingBehavior.prototype.attach = function (camera) {
  112139. var _this = this;
  112140. this._attachedCamera = camera;
  112141. var scene = this._attachedCamera.getScene();
  112142. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  112143. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112144. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112145. _this._isPointerDown = true;
  112146. return;
  112147. }
  112148. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112149. _this._isPointerDown = false;
  112150. }
  112151. });
  112152. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112153. if (mesh) {
  112154. _this.zoomOnMesh(mesh);
  112155. }
  112156. });
  112157. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112158. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112159. _this._applyUserInteraction();
  112160. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  112161. // back to the default position after a given timeout
  112162. _this._maintainCameraAboveGround();
  112163. });
  112164. };
  112165. /**
  112166. * Detaches the behavior from its current arc rotate camera.
  112167. */
  112168. FramingBehavior.prototype.detach = function () {
  112169. if (!this._attachedCamera) {
  112170. return;
  112171. }
  112172. var scene = this._attachedCamera.getScene();
  112173. if (this._onPrePointerObservableObserver) {
  112174. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112175. }
  112176. if (this._onAfterCheckInputsObserver) {
  112177. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112178. }
  112179. if (this._onMeshTargetChangedObserver) {
  112180. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112181. }
  112182. this._attachedCamera = null;
  112183. };
  112184. /**
  112185. * Targets the given mesh and updates zoom level accordingly.
  112186. * @param mesh The mesh to target.
  112187. * @param radius Optional. If a cached radius position already exists, overrides default.
  112188. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112189. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112190. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112191. */
  112192. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112193. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112194. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112195. mesh.computeWorldMatrix(true);
  112196. var boundingBox = mesh.getBoundingInfo().boundingBox;
  112197. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  112198. };
  112199. /**
  112200. * Targets the given mesh with its children and updates zoom level accordingly.
  112201. * @param mesh The mesh to target.
  112202. * @param radius Optional. If a cached radius position already exists, overrides default.
  112203. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112204. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112205. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112206. */
  112207. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  112208. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112209. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112210. mesh.computeWorldMatrix(true);
  112211. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  112212. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  112213. };
  112214. /**
  112215. * Targets the given meshes with their children and updates zoom level accordingly.
  112216. * @param meshes The mesh to target.
  112217. * @param radius Optional. If a cached radius position already exists, overrides default.
  112218. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  112219. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112220. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112221. */
  112222. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  112223. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112224. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112225. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  112226. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  112227. for (var i = 0; i < meshes.length; i++) {
  112228. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  112229. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  112230. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  112231. }
  112232. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  112233. };
  112234. /**
  112235. * Targets the bounding box info defined by its extends and updates zoom level accordingly.
  112236. * @param minimumWorld Determines the smaller position of the bounding box extend
  112237. * @param maximumWorld Determines the bigger position of the bounding box extend
  112238. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  112239. * @param onAnimationEnd Callback triggered at the end of the framing animation
  112240. */
  112241. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  112242. var _this = this;
  112243. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  112244. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  112245. var zoomTarget;
  112246. if (!this._attachedCamera) {
  112247. return;
  112248. }
  112249. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  112250. var bottom = minimumWorld.y;
  112251. var top = maximumWorld.y;
  112252. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  112253. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  112254. if (focusOnOriginXZ) {
  112255. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  112256. }
  112257. else {
  112258. var centerWorld = minimumWorld.add(radiusWorld);
  112259. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  112260. }
  112261. if (!this._vectorTransition) {
  112262. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  112263. }
  112264. this._betaIsAnimating = true;
  112265. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  112266. if (animatable) {
  112267. this._animatables.push(animatable);
  112268. }
  112269. // sets the radius and lower radius bounds
  112270. // Small delta ensures camera is not always at lower zoom limit.
  112271. var radius = 0;
  112272. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  112273. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112274. if (this.autoCorrectCameraLimitsAndSensibility) {
  112275. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  112276. }
  112277. radius = position;
  112278. }
  112279. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112280. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  112281. if (this.autoCorrectCameraLimitsAndSensibility && this._attachedCamera.lowerRadiusLimit === null) {
  112282. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  112283. }
  112284. }
  112285. // Set sensibilities
  112286. if (this.autoCorrectCameraLimitsAndSensibility) {
  112287. var extend = maximumWorld.subtract(minimumWorld).length();
  112288. this._attachedCamera.panningSensibility = 5000 / extend;
  112289. this._attachedCamera.wheelPrecision = 100 / radius;
  112290. }
  112291. // transition to new radius
  112292. if (!this._radiusTransition) {
  112293. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112294. }
  112295. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  112296. _this.stopAllAnimations();
  112297. if (onAnimationEnd) {
  112298. onAnimationEnd();
  112299. }
  112300. if (_this._attachedCamera && _this._attachedCamera.useInputToRestoreState) {
  112301. _this._attachedCamera.storeState();
  112302. }
  112303. });
  112304. if (animatable) {
  112305. this._animatables.push(animatable);
  112306. }
  112307. };
  112308. /**
  112309. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  112310. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  112311. * frustum width.
  112312. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  112313. * to fully enclose the mesh in the viewing frustum.
  112314. */
  112315. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  112316. var size = maximumWorld.subtract(minimumWorld);
  112317. var boxVectorGlobalDiagonal = size.length();
  112318. var frustumSlope = this._getFrustumSlope();
  112319. // Formula for setting distance
  112320. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  112321. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  112322. // Horizon distance
  112323. var radius = radiusWithoutFraming * this._radiusScale;
  112324. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  112325. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  112326. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  112327. var camera = this._attachedCamera;
  112328. if (!camera) {
  112329. return 0;
  112330. }
  112331. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  112332. // Don't exceed the requested limit
  112333. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  112334. }
  112335. // Don't exceed the upper radius limit
  112336. if (camera.upperRadiusLimit) {
  112337. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  112338. }
  112339. return distance;
  112340. };
  112341. /**
  112342. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  112343. * is automatically returned to its default position (expected to be above ground plane).
  112344. */
  112345. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  112346. var _this = this;
  112347. if (this._elevationReturnTime < 0) {
  112348. return;
  112349. }
  112350. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  112351. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  112352. var limitBeta = Math.PI * 0.5;
  112353. // Bring the camera back up if below the ground plane
  112354. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  112355. this._betaIsAnimating = true;
  112356. //Transition to new position
  112357. this.stopAllAnimations();
  112358. if (!this._betaTransition) {
  112359. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  112360. }
  112361. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  112362. _this._clearAnimationLocks();
  112363. _this.stopAllAnimations();
  112364. });
  112365. if (animatabe) {
  112366. this._animatables.push(animatabe);
  112367. }
  112368. }
  112369. };
  112370. /**
  112371. * Returns the frustum slope based on the canvas ratio and camera FOV
  112372. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  112373. */
  112374. FramingBehavior.prototype._getFrustumSlope = function () {
  112375. // Calculate the viewport ratio
  112376. // Aspect Ratio is Height/Width.
  112377. var camera = this._attachedCamera;
  112378. if (!camera) {
  112379. return BABYLON.Vector2.Zero();
  112380. }
  112381. var engine = camera.getScene().getEngine();
  112382. var aspectRatio = engine.getAspectRatio(camera);
  112383. // Camera FOV is the vertical field of view (top-bottom) in radians.
  112384. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  112385. var frustumSlopeY = Math.tan(camera.fov / 2);
  112386. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  112387. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  112388. // along the forward vector.
  112389. var frustumSlopeX = frustumSlopeY * aspectRatio;
  112390. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  112391. };
  112392. /**
  112393. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  112394. */
  112395. FramingBehavior.prototype._clearAnimationLocks = function () {
  112396. this._betaIsAnimating = false;
  112397. };
  112398. /**
  112399. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112400. */
  112401. FramingBehavior.prototype._applyUserInteraction = function () {
  112402. if (this.isUserIsMoving) {
  112403. this._lastInteractionTime = BABYLON.Tools.Now;
  112404. this.stopAllAnimations();
  112405. this._clearAnimationLocks();
  112406. }
  112407. };
  112408. /**
  112409. * Stops and removes all animations that have been applied to the camera
  112410. */
  112411. FramingBehavior.prototype.stopAllAnimations = function () {
  112412. if (this._attachedCamera) {
  112413. this._attachedCamera.animations = [];
  112414. }
  112415. while (this._animatables.length) {
  112416. if (this._animatables[0]) {
  112417. this._animatables[0].onAnimationEnd = null;
  112418. this._animatables[0].stop();
  112419. }
  112420. this._animatables.shift();
  112421. }
  112422. };
  112423. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  112424. /**
  112425. * Gets a value indicating if the user is moving the camera
  112426. */
  112427. get: function () {
  112428. if (!this._attachedCamera) {
  112429. return false;
  112430. }
  112431. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112432. this._attachedCamera.inertialBetaOffset !== 0 ||
  112433. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112434. this._attachedCamera.inertialPanningX !== 0 ||
  112435. this._attachedCamera.inertialPanningY !== 0 ||
  112436. this._isPointerDown;
  112437. },
  112438. enumerable: true,
  112439. configurable: true
  112440. });
  112441. /**
  112442. * The easing function used by animations
  112443. */
  112444. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  112445. /**
  112446. * The easing mode used by animations
  112447. */
  112448. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  112449. // Statics
  112450. /**
  112451. * The camera can move all the way towards the mesh.
  112452. */
  112453. FramingBehavior.IgnoreBoundsSizeMode = 0;
  112454. /**
  112455. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  112456. */
  112457. FramingBehavior.FitFrustumSidesMode = 1;
  112458. return FramingBehavior;
  112459. }());
  112460. BABYLON.FramingBehavior = FramingBehavior;
  112461. })(BABYLON || (BABYLON = {}));
  112462. //# sourceMappingURL=babylon.framingBehavior.js.map
  112463. var BABYLON;
  112464. (function (BABYLON) {
  112465. /**
  112466. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  112467. * @see http://doc.babylonjs.com/how_to/camera_behaviors#bouncing-behavior
  112468. */
  112469. var BouncingBehavior = /** @class */ (function () {
  112470. function BouncingBehavior() {
  112471. /**
  112472. * The duration of the animation, in milliseconds
  112473. */
  112474. this.transitionDuration = 450;
  112475. /**
  112476. * Length of the distance animated by the transition when lower radius is reached
  112477. */
  112478. this.lowerRadiusTransitionRange = 2;
  112479. /**
  112480. * Length of the distance animated by the transition when upper radius is reached
  112481. */
  112482. this.upperRadiusTransitionRange = -2;
  112483. this._autoTransitionRange = false;
  112484. // Animations
  112485. this._radiusIsAnimating = false;
  112486. this._radiusBounceTransition = null;
  112487. this._animatables = new Array();
  112488. }
  112489. Object.defineProperty(BouncingBehavior.prototype, "name", {
  112490. /**
  112491. * Gets the name of the behavior.
  112492. */
  112493. get: function () {
  112494. return "Bouncing";
  112495. },
  112496. enumerable: true,
  112497. configurable: true
  112498. });
  112499. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  112500. /**
  112501. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112502. */
  112503. get: function () {
  112504. return this._autoTransitionRange;
  112505. },
  112506. /**
  112507. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  112508. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  112509. */
  112510. set: function (value) {
  112511. var _this = this;
  112512. if (this._autoTransitionRange === value) {
  112513. return;
  112514. }
  112515. this._autoTransitionRange = value;
  112516. var camera = this._attachedCamera;
  112517. if (!camera) {
  112518. return;
  112519. }
  112520. if (value) {
  112521. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  112522. if (!mesh) {
  112523. return;
  112524. }
  112525. mesh.computeWorldMatrix(true);
  112526. var diagonal = mesh.getBoundingInfo().diagonalLength;
  112527. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  112528. _this.upperRadiusTransitionRange = diagonal * 0.05;
  112529. });
  112530. }
  112531. else if (this._onMeshTargetChangedObserver) {
  112532. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112533. }
  112534. },
  112535. enumerable: true,
  112536. configurable: true
  112537. });
  112538. /**
  112539. * Initializes the behavior.
  112540. */
  112541. BouncingBehavior.prototype.init = function () {
  112542. // Do notihng
  112543. };
  112544. /**
  112545. * Attaches the behavior to its arc rotate camera.
  112546. * @param camera Defines the camera to attach the behavior to
  112547. */
  112548. BouncingBehavior.prototype.attach = function (camera) {
  112549. var _this = this;
  112550. this._attachedCamera = camera;
  112551. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112552. if (!_this._attachedCamera) {
  112553. return;
  112554. }
  112555. // Add the bounce animation to the lower radius limit
  112556. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  112557. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  112558. }
  112559. // Add the bounce animation to the upper radius limit
  112560. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  112561. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  112562. }
  112563. });
  112564. };
  112565. /**
  112566. * Detaches the behavior from its current arc rotate camera.
  112567. */
  112568. BouncingBehavior.prototype.detach = function () {
  112569. if (!this._attachedCamera) {
  112570. return;
  112571. }
  112572. if (this._onAfterCheckInputsObserver) {
  112573. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112574. }
  112575. if (this._onMeshTargetChangedObserver) {
  112576. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  112577. }
  112578. this._attachedCamera = null;
  112579. };
  112580. /**
  112581. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  112582. * @param radiusLimit The limit to check against.
  112583. * @return Bool to indicate if at limit.
  112584. */
  112585. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  112586. if (!this._attachedCamera) {
  112587. return false;
  112588. }
  112589. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  112590. return true;
  112591. }
  112592. return false;
  112593. };
  112594. /**
  112595. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  112596. * @param radiusDelta The delta by which to animate to. Can be negative.
  112597. */
  112598. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  112599. var _this = this;
  112600. if (!this._attachedCamera) {
  112601. return;
  112602. }
  112603. if (!this._radiusBounceTransition) {
  112604. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  112605. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  112606. }
  112607. // Prevent zoom until bounce has completed
  112608. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  112609. this._attachedCamera.wheelPrecision = Infinity;
  112610. this._attachedCamera.inertialRadiusOffset = 0;
  112611. // Animate to the radius limit
  112612. this.stopAllAnimations();
  112613. this._radiusIsAnimating = true;
  112614. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  112615. if (animatable) {
  112616. this._animatables.push(animatable);
  112617. }
  112618. };
  112619. /**
  112620. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  112621. */
  112622. BouncingBehavior.prototype._clearAnimationLocks = function () {
  112623. this._radiusIsAnimating = false;
  112624. if (this._attachedCamera) {
  112625. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  112626. }
  112627. };
  112628. /**
  112629. * Stops and removes all animations that have been applied to the camera
  112630. */
  112631. BouncingBehavior.prototype.stopAllAnimations = function () {
  112632. if (this._attachedCamera) {
  112633. this._attachedCamera.animations = [];
  112634. }
  112635. while (this._animatables.length) {
  112636. this._animatables[0].onAnimationEnd = null;
  112637. this._animatables[0].stop();
  112638. this._animatables.shift();
  112639. }
  112640. };
  112641. /**
  112642. * The easing function used by animations
  112643. */
  112644. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  112645. /**
  112646. * The easing mode used by animations
  112647. */
  112648. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  112649. return BouncingBehavior;
  112650. }());
  112651. BABYLON.BouncingBehavior = BouncingBehavior;
  112652. })(BABYLON || (BABYLON = {}));
  112653. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  112654. var BABYLON;
  112655. (function (BABYLON) {
  112656. /**
  112657. * The autoRotation behavior (BABYLON.AutoRotationBehavior) is designed to create a smooth rotation of an ArcRotateCamera when there is no user interaction.
  112658. * @see http://doc.babylonjs.com/how_to/camera_behaviors#autorotation-behavior
  112659. */
  112660. var AutoRotationBehavior = /** @class */ (function () {
  112661. function AutoRotationBehavior() {
  112662. this._zoomStopsAnimation = false;
  112663. this._idleRotationSpeed = 0.05;
  112664. this._idleRotationWaitTime = 2000;
  112665. this._idleRotationSpinupTime = 2000;
  112666. this._isPointerDown = false;
  112667. this._lastFrameTime = null;
  112668. this._lastInteractionTime = -Infinity;
  112669. this._cameraRotationSpeed = 0;
  112670. this._lastFrameRadius = 0;
  112671. }
  112672. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  112673. /**
  112674. * Gets the name of the behavior.
  112675. */
  112676. get: function () {
  112677. return "AutoRotation";
  112678. },
  112679. enumerable: true,
  112680. configurable: true
  112681. });
  112682. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  112683. /**
  112684. * Gets the flag that indicates if user zooming should stop animation.
  112685. */
  112686. get: function () {
  112687. return this._zoomStopsAnimation;
  112688. },
  112689. /**
  112690. * Sets the flag that indicates if user zooming should stop animation.
  112691. */
  112692. set: function (flag) {
  112693. this._zoomStopsAnimation = flag;
  112694. },
  112695. enumerable: true,
  112696. configurable: true
  112697. });
  112698. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  112699. /**
  112700. * Gets the default speed at which the camera rotates around the model.
  112701. */
  112702. get: function () {
  112703. return this._idleRotationSpeed;
  112704. },
  112705. /**
  112706. * Sets the default speed at which the camera rotates around the model.
  112707. */
  112708. set: function (speed) {
  112709. this._idleRotationSpeed = speed;
  112710. },
  112711. enumerable: true,
  112712. configurable: true
  112713. });
  112714. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  112715. /**
  112716. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  112717. */
  112718. get: function () {
  112719. return this._idleRotationWaitTime;
  112720. },
  112721. /**
  112722. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  112723. */
  112724. set: function (time) {
  112725. this._idleRotationWaitTime = time;
  112726. },
  112727. enumerable: true,
  112728. configurable: true
  112729. });
  112730. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  112731. /**
  112732. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  112733. */
  112734. get: function () {
  112735. return this._idleRotationSpinupTime;
  112736. },
  112737. /**
  112738. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  112739. */
  112740. set: function (time) {
  112741. this._idleRotationSpinupTime = time;
  112742. },
  112743. enumerable: true,
  112744. configurable: true
  112745. });
  112746. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  112747. /**
  112748. * Gets a value indicating if the camera is currently rotating because of this behavior
  112749. */
  112750. get: function () {
  112751. return Math.abs(this._cameraRotationSpeed) > 0;
  112752. },
  112753. enumerable: true,
  112754. configurable: true
  112755. });
  112756. /**
  112757. * Initializes the behavior.
  112758. */
  112759. AutoRotationBehavior.prototype.init = function () {
  112760. // Do notihng
  112761. };
  112762. /**
  112763. * Attaches the behavior to its arc rotate camera.
  112764. * @param camera Defines the camera to attach the behavior to
  112765. */
  112766. AutoRotationBehavior.prototype.attach = function (camera) {
  112767. var _this = this;
  112768. this._attachedCamera = camera;
  112769. var scene = this._attachedCamera.getScene();
  112770. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  112771. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  112772. _this._isPointerDown = true;
  112773. return;
  112774. }
  112775. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  112776. _this._isPointerDown = false;
  112777. }
  112778. });
  112779. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  112780. var now = BABYLON.Tools.Now;
  112781. var dt = 0;
  112782. if (_this._lastFrameTime != null) {
  112783. dt = now - _this._lastFrameTime;
  112784. }
  112785. _this._lastFrameTime = now;
  112786. // Stop the animation if there is user interaction and the animation should stop for this interaction
  112787. _this._applyUserInteraction();
  112788. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  112789. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  112790. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  112791. // Step camera rotation by rotation speed
  112792. if (_this._attachedCamera) {
  112793. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  112794. }
  112795. });
  112796. };
  112797. /**
  112798. * Detaches the behavior from its current arc rotate camera.
  112799. */
  112800. AutoRotationBehavior.prototype.detach = function () {
  112801. if (!this._attachedCamera) {
  112802. return;
  112803. }
  112804. var scene = this._attachedCamera.getScene();
  112805. if (this._onPrePointerObservableObserver) {
  112806. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  112807. }
  112808. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  112809. this._attachedCamera = null;
  112810. };
  112811. /**
  112812. * Returns true if user is scrolling.
  112813. * @return true if user is scrolling.
  112814. */
  112815. AutoRotationBehavior.prototype._userIsZooming = function () {
  112816. if (!this._attachedCamera) {
  112817. return false;
  112818. }
  112819. return this._attachedCamera.inertialRadiusOffset !== 0;
  112820. };
  112821. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  112822. if (!this._attachedCamera) {
  112823. return false;
  112824. }
  112825. var zoomHasHitLimit = false;
  112826. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  112827. zoomHasHitLimit = true;
  112828. }
  112829. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  112830. this._lastFrameRadius = this._attachedCamera.radius;
  112831. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  112832. };
  112833. /**
  112834. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  112835. */
  112836. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  112837. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  112838. this._lastInteractionTime = BABYLON.Tools.Now;
  112839. }
  112840. };
  112841. // Tools
  112842. AutoRotationBehavior.prototype._userIsMoving = function () {
  112843. if (!this._attachedCamera) {
  112844. return false;
  112845. }
  112846. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  112847. this._attachedCamera.inertialBetaOffset !== 0 ||
  112848. this._attachedCamera.inertialRadiusOffset !== 0 ||
  112849. this._attachedCamera.inertialPanningX !== 0 ||
  112850. this._attachedCamera.inertialPanningY !== 0 ||
  112851. this._isPointerDown;
  112852. };
  112853. return AutoRotationBehavior;
  112854. }());
  112855. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  112856. })(BABYLON || (BABYLON = {}));
  112857. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  112858. var BABYLON;
  112859. (function (BABYLON) {
  112860. /**
  112861. * Options to create the null engine
  112862. */
  112863. var NullEngineOptions = /** @class */ (function () {
  112864. function NullEngineOptions() {
  112865. /**
  112866. * Render width (Default: 512)
  112867. */
  112868. this.renderWidth = 512;
  112869. /**
  112870. * Render height (Default: 256)
  112871. */
  112872. this.renderHeight = 256;
  112873. /**
  112874. * Texture size (Default: 512)
  112875. */
  112876. this.textureSize = 512;
  112877. /**
  112878. * If delta time between frames should be constant
  112879. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112880. */
  112881. this.deterministicLockstep = false;
  112882. /**
  112883. * Maximum about of steps between frames (Default: 4)
  112884. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112885. */
  112886. this.lockstepMaxSteps = 4;
  112887. }
  112888. return NullEngineOptions;
  112889. }());
  112890. BABYLON.NullEngineOptions = NullEngineOptions;
  112891. /**
  112892. * The null engine class provides support for headless version of babylon.js.
  112893. * This can be used in server side scenario or for testing purposes
  112894. */
  112895. var NullEngine = /** @class */ (function (_super) {
  112896. __extends(NullEngine, _super);
  112897. function NullEngine(options) {
  112898. if (options === void 0) { options = new NullEngineOptions(); }
  112899. var _this = _super.call(this, null) || this;
  112900. if (options.deterministicLockstep === undefined) {
  112901. options.deterministicLockstep = false;
  112902. }
  112903. if (options.lockstepMaxSteps === undefined) {
  112904. options.lockstepMaxSteps = 4;
  112905. }
  112906. _this._options = options;
  112907. // Init caps
  112908. // We consider we are on a webgl1 capable device
  112909. _this._caps = new BABYLON.EngineCapabilities();
  112910. _this._caps.maxTexturesImageUnits = 16;
  112911. _this._caps.maxVertexTextureImageUnits = 16;
  112912. _this._caps.maxTextureSize = 512;
  112913. _this._caps.maxCubemapTextureSize = 512;
  112914. _this._caps.maxRenderTextureSize = 512;
  112915. _this._caps.maxVertexAttribs = 16;
  112916. _this._caps.maxVaryingVectors = 16;
  112917. _this._caps.maxFragmentUniformVectors = 16;
  112918. _this._caps.maxVertexUniformVectors = 16;
  112919. // Extensions
  112920. _this._caps.standardDerivatives = false;
  112921. _this._caps.astc = null;
  112922. _this._caps.s3tc = null;
  112923. _this._caps.pvrtc = null;
  112924. _this._caps.etc1 = null;
  112925. _this._caps.etc2 = null;
  112926. _this._caps.textureAnisotropicFilterExtension = null;
  112927. _this._caps.maxAnisotropy = 0;
  112928. _this._caps.uintIndices = false;
  112929. _this._caps.fragmentDepthSupported = false;
  112930. _this._caps.highPrecisionShaderSupported = true;
  112931. _this._caps.colorBufferFloat = false;
  112932. _this._caps.textureFloat = false;
  112933. _this._caps.textureFloatLinearFiltering = false;
  112934. _this._caps.textureFloatRender = false;
  112935. _this._caps.textureHalfFloat = false;
  112936. _this._caps.textureHalfFloatLinearFiltering = false;
  112937. _this._caps.textureHalfFloatRender = false;
  112938. _this._caps.textureLOD = false;
  112939. _this._caps.drawBuffersExtension = false;
  112940. _this._caps.depthTextureExtension = false;
  112941. _this._caps.vertexArrayObject = false;
  112942. _this._caps.instancedArrays = false;
  112943. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  112944. // Wrappers
  112945. if (typeof URL === "undefined") {
  112946. URL = {
  112947. createObjectURL: function () { },
  112948. revokeObjectURL: function () { }
  112949. };
  112950. }
  112951. if (typeof Blob === "undefined") {
  112952. Blob = function () { };
  112953. }
  112954. return _this;
  112955. }
  112956. /**
  112957. * @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  112958. */
  112959. NullEngine.prototype.isDeterministicLockStep = function () {
  112960. return this._options.deterministicLockstep;
  112961. };
  112962. /** @see https://doc.babylonjs.com/babylon101/animations#deterministic-lockstep */
  112963. NullEngine.prototype.getLockstepMaxSteps = function () {
  112964. return this._options.lockstepMaxSteps;
  112965. };
  112966. /**
  112967. * Sets hardware scaling, used to save performance if needed
  112968. * @see https://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  112969. */
  112970. NullEngine.prototype.getHardwareScalingLevel = function () {
  112971. return 1.0;
  112972. };
  112973. NullEngine.prototype.createVertexBuffer = function (vertices) {
  112974. return {
  112975. capacity: 0,
  112976. references: 1,
  112977. is32Bits: false
  112978. };
  112979. };
  112980. NullEngine.prototype.createIndexBuffer = function (indices) {
  112981. return {
  112982. capacity: 0,
  112983. references: 1,
  112984. is32Bits: false
  112985. };
  112986. };
  112987. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  112988. if (stencil === void 0) { stencil = false; }
  112989. };
  112990. NullEngine.prototype.getRenderWidth = function (useScreen) {
  112991. if (useScreen === void 0) { useScreen = false; }
  112992. if (!useScreen && this._currentRenderTarget) {
  112993. return this._currentRenderTarget.width;
  112994. }
  112995. return this._options.renderWidth;
  112996. };
  112997. NullEngine.prototype.getRenderHeight = function (useScreen) {
  112998. if (useScreen === void 0) { useScreen = false; }
  112999. if (!useScreen && this._currentRenderTarget) {
  113000. return this._currentRenderTarget.height;
  113001. }
  113002. return this._options.renderHeight;
  113003. };
  113004. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  113005. this._cachedViewport = viewport;
  113006. };
  113007. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  113008. return {
  113009. transformFeedback: null,
  113010. __SPECTOR_rebuildProgram: null
  113011. };
  113012. };
  113013. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  113014. return [];
  113015. };
  113016. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  113017. return [];
  113018. };
  113019. NullEngine.prototype.bindSamplers = function (effect) {
  113020. this._currentEffect = null;
  113021. };
  113022. NullEngine.prototype.enableEffect = function (effect) {
  113023. this._currentEffect = effect;
  113024. if (effect.onBind) {
  113025. effect.onBind(effect);
  113026. }
  113027. if (effect._onBindObservable) {
  113028. effect._onBindObservable.notifyObservers(effect);
  113029. }
  113030. };
  113031. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  113032. if (zOffset === void 0) { zOffset = 0; }
  113033. if (reverseSide === void 0) { reverseSide = false; }
  113034. };
  113035. NullEngine.prototype.setIntArray = function (uniform, array) {
  113036. };
  113037. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  113038. };
  113039. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  113040. };
  113041. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  113042. };
  113043. NullEngine.prototype.setFloatArray = function (uniform, array) {
  113044. };
  113045. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  113046. };
  113047. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  113048. };
  113049. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  113050. };
  113051. NullEngine.prototype.setArray = function (uniform, array) {
  113052. };
  113053. NullEngine.prototype.setArray2 = function (uniform, array) {
  113054. };
  113055. NullEngine.prototype.setArray3 = function (uniform, array) {
  113056. };
  113057. NullEngine.prototype.setArray4 = function (uniform, array) {
  113058. };
  113059. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  113060. };
  113061. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  113062. };
  113063. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  113064. };
  113065. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  113066. };
  113067. NullEngine.prototype.setFloat = function (uniform, value) {
  113068. };
  113069. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  113070. };
  113071. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  113072. };
  113073. NullEngine.prototype.setBool = function (uniform, bool) {
  113074. };
  113075. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  113076. };
  113077. NullEngine.prototype.setColor3 = function (uniform, color3) {
  113078. };
  113079. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  113080. };
  113081. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  113082. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  113083. if (this._alphaMode === mode) {
  113084. return;
  113085. }
  113086. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  113087. if (!noDepthWriteChange) {
  113088. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  113089. }
  113090. this._alphaMode = mode;
  113091. };
  113092. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  113093. };
  113094. NullEngine.prototype.wipeCaches = function (bruteForce) {
  113095. if (this.preventCacheWipeBetweenFrames) {
  113096. return;
  113097. }
  113098. this.resetTextureCache();
  113099. this._currentEffect = null;
  113100. if (bruteForce) {
  113101. this._currentProgram = null;
  113102. this._stencilState.reset();
  113103. this._depthCullingState.reset();
  113104. this._alphaState.reset();
  113105. }
  113106. this._cachedVertexBuffers = null;
  113107. this._cachedIndexBuffer = null;
  113108. this._cachedEffectForVertexBuffers = null;
  113109. };
  113110. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  113111. };
  113112. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  113113. };
  113114. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  113115. };
  113116. /** @hidden */
  113117. NullEngine.prototype._createTexture = function () {
  113118. return {};
  113119. };
  113120. /** @hidden */
  113121. NullEngine.prototype._releaseTexture = function (texture) {
  113122. };
  113123. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  113124. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  113125. if (onLoad === void 0) { onLoad = null; }
  113126. if (onError === void 0) { onError = null; }
  113127. if (buffer === void 0) { buffer = null; }
  113128. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  113129. var url = String(urlArg);
  113130. texture.url = url;
  113131. texture.generateMipMaps = !noMipmap;
  113132. texture.samplingMode = samplingMode;
  113133. texture.invertY = invertY;
  113134. texture.baseWidth = this._options.textureSize;
  113135. texture.baseHeight = this._options.textureSize;
  113136. texture.width = this._options.textureSize;
  113137. texture.height = this._options.textureSize;
  113138. if (format) {
  113139. texture.format = format;
  113140. }
  113141. texture.isReady = true;
  113142. if (onLoad) {
  113143. onLoad();
  113144. }
  113145. this._internalTexturesCache.push(texture);
  113146. return texture;
  113147. };
  113148. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  113149. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  113150. if (options !== undefined && typeof options === "object") {
  113151. fullOptions.generateMipMaps = options.generateMipMaps;
  113152. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  113153. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  113154. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  113155. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  113156. }
  113157. else {
  113158. fullOptions.generateMipMaps = options;
  113159. fullOptions.generateDepthBuffer = true;
  113160. fullOptions.generateStencilBuffer = false;
  113161. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  113162. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  113163. }
  113164. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  113165. var width = size.width || size;
  113166. var height = size.height || size;
  113167. texture._depthStencilBuffer = {};
  113168. texture._framebuffer = {};
  113169. texture.baseWidth = width;
  113170. texture.baseHeight = height;
  113171. texture.width = width;
  113172. texture.height = height;
  113173. texture.isReady = true;
  113174. texture.samples = 1;
  113175. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  113176. texture.samplingMode = fullOptions.samplingMode;
  113177. texture.type = fullOptions.type;
  113178. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  113179. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  113180. this._internalTexturesCache.push(texture);
  113181. return texture;
  113182. };
  113183. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  113184. texture.samplingMode = samplingMode;
  113185. };
  113186. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  113187. if (this._currentRenderTarget) {
  113188. this.unBindFramebuffer(this._currentRenderTarget);
  113189. }
  113190. this._currentRenderTarget = texture;
  113191. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  113192. if (this._cachedViewport && !forceFullscreenViewport) {
  113193. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  113194. }
  113195. };
  113196. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  113197. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  113198. this._currentRenderTarget = null;
  113199. if (onBeforeUnbind) {
  113200. if (texture._MSAAFramebuffer) {
  113201. this._currentFramebuffer = texture._framebuffer;
  113202. }
  113203. onBeforeUnbind();
  113204. }
  113205. this._currentFramebuffer = null;
  113206. };
  113207. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  113208. var vbo = {
  113209. capacity: 1,
  113210. references: 1,
  113211. is32Bits: false
  113212. };
  113213. return vbo;
  113214. };
  113215. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  113216. if (premulAlpha === void 0) { premulAlpha = false; }
  113217. };
  113218. /**
  113219. * @hidden
  113220. * Get the current error code of the webGL context
  113221. * @returns the error code
  113222. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  113223. */
  113224. NullEngine.prototype.getError = function () {
  113225. return 0;
  113226. };
  113227. /** @hidden */
  113228. NullEngine.prototype._getUnpackAlignement = function () {
  113229. return 1;
  113230. };
  113231. /** @hidden */
  113232. NullEngine.prototype._unpackFlipY = function (value) {
  113233. };
  113234. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  113235. if (offset === void 0) { offset = 0; }
  113236. };
  113237. /**
  113238. * Updates a dynamic vertex buffer.
  113239. * @param vertexBuffer the vertex buffer to update
  113240. * @param data the data used to update the vertex buffer
  113241. * @param byteOffset the byte offset of the data (optional)
  113242. * @param byteLength the byte length of the data (optional)
  113243. */
  113244. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  113245. };
  113246. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  113247. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  113248. this._boundTexturesCache[this._activeChannel] = texture;
  113249. return true;
  113250. }
  113251. return false;
  113252. };
  113253. /** @hidden */
  113254. NullEngine.prototype._bindTexture = function (channel, texture) {
  113255. if (channel < 0) {
  113256. return;
  113257. }
  113258. this._bindTextureDirectly(0, texture);
  113259. };
  113260. /** @hidden */
  113261. NullEngine.prototype._releaseBuffer = function (buffer) {
  113262. buffer.references--;
  113263. if (buffer.references === 0) {
  113264. return true;
  113265. }
  113266. return false;
  113267. };
  113268. NullEngine.prototype.releaseEffects = function () {
  113269. };
  113270. NullEngine.prototype.displayLoadingUI = function () {
  113271. };
  113272. NullEngine.prototype.hideLoadingUI = function () {
  113273. };
  113274. /** @hidden */
  113275. NullEngine.prototype._uploadCompressedDataToTextureDirectly = function (texture, internalFormat, width, height, data, faceIndex, lod) {
  113276. if (faceIndex === void 0) { faceIndex = 0; }
  113277. if (lod === void 0) { lod = 0; }
  113278. };
  113279. /** @hidden */
  113280. NullEngine.prototype._uploadDataToTextureDirectly = function (texture, imageData, faceIndex, lod) {
  113281. if (faceIndex === void 0) { faceIndex = 0; }
  113282. if (lod === void 0) { lod = 0; }
  113283. };
  113284. /** @hidden */
  113285. NullEngine.prototype._uploadArrayBufferViewToTexture = function (texture, imageData, faceIndex, lod) {
  113286. if (faceIndex === void 0) { faceIndex = 0; }
  113287. if (lod === void 0) { lod = 0; }
  113288. };
  113289. /** @hidden */
  113290. NullEngine.prototype._uploadImageToTexture = function (texture, image, faceIndex, lod) {
  113291. if (faceIndex === void 0) { faceIndex = 0; }
  113292. if (lod === void 0) { lod = 0; }
  113293. };
  113294. return NullEngine;
  113295. }(BABYLON.Engine));
  113296. BABYLON.NullEngine = NullEngine;
  113297. })(BABYLON || (BABYLON = {}));
  113298. //# sourceMappingURL=babylon.nullEngine.js.map
  113299. var BABYLON;
  113300. (function (BABYLON) {
  113301. /**
  113302. * This class can be used to get instrumentation data from a Babylon engine
  113303. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113304. */
  113305. var EngineInstrumentation = /** @class */ (function () {
  113306. /**
  113307. * Instantiates a new engine instrumentation.
  113308. * This class can be used to get instrumentation data from a Babylon engine
  113309. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  113310. * @param engine Defines the engine to instrument
  113311. */
  113312. function EngineInstrumentation(
  113313. /**
  113314. * Define the instrumented engine.
  113315. */
  113316. engine) {
  113317. this.engine = engine;
  113318. this._captureGPUFrameTime = false;
  113319. this._gpuFrameTime = new BABYLON.PerfCounter();
  113320. this._captureShaderCompilationTime = false;
  113321. this._shaderCompilationTime = new BABYLON.PerfCounter();
  113322. // Observers
  113323. this._onBeginFrameObserver = null;
  113324. this._onEndFrameObserver = null;
  113325. this._onBeforeShaderCompilationObserver = null;
  113326. this._onAfterShaderCompilationObserver = null;
  113327. }
  113328. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  113329. // Properties
  113330. /**
  113331. * Gets the perf counter used for GPU frame time
  113332. */
  113333. get: function () {
  113334. return this._gpuFrameTime;
  113335. },
  113336. enumerable: true,
  113337. configurable: true
  113338. });
  113339. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  113340. /**
  113341. * Gets the GPU frame time capture status
  113342. */
  113343. get: function () {
  113344. return this._captureGPUFrameTime;
  113345. },
  113346. /**
  113347. * Enable or disable the GPU frame time capture
  113348. */
  113349. set: function (value) {
  113350. var _this = this;
  113351. if (value === this._captureGPUFrameTime) {
  113352. return;
  113353. }
  113354. this._captureGPUFrameTime = value;
  113355. if (value) {
  113356. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  113357. if (!_this._gpuFrameTimeToken) {
  113358. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  113359. }
  113360. });
  113361. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  113362. if (!_this._gpuFrameTimeToken) {
  113363. return;
  113364. }
  113365. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  113366. if (time > -1) {
  113367. _this._gpuFrameTimeToken = null;
  113368. _this._gpuFrameTime.fetchNewFrame();
  113369. _this._gpuFrameTime.addCount(time, true);
  113370. }
  113371. });
  113372. }
  113373. else {
  113374. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113375. this._onBeginFrameObserver = null;
  113376. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113377. this._onEndFrameObserver = null;
  113378. }
  113379. },
  113380. enumerable: true,
  113381. configurable: true
  113382. });
  113383. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  113384. /**
  113385. * Gets the perf counter used for shader compilation time
  113386. */
  113387. get: function () {
  113388. return this._shaderCompilationTime;
  113389. },
  113390. enumerable: true,
  113391. configurable: true
  113392. });
  113393. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  113394. /**
  113395. * Gets the shader compilation time capture status
  113396. */
  113397. get: function () {
  113398. return this._captureShaderCompilationTime;
  113399. },
  113400. /**
  113401. * Enable or disable the shader compilation time capture
  113402. */
  113403. set: function (value) {
  113404. var _this = this;
  113405. if (value === this._captureShaderCompilationTime) {
  113406. return;
  113407. }
  113408. this._captureShaderCompilationTime = value;
  113409. if (value) {
  113410. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  113411. _this._shaderCompilationTime.fetchNewFrame();
  113412. _this._shaderCompilationTime.beginMonitoring();
  113413. });
  113414. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  113415. _this._shaderCompilationTime.endMonitoring();
  113416. });
  113417. }
  113418. else {
  113419. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113420. this._onBeforeShaderCompilationObserver = null;
  113421. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113422. this._onAfterShaderCompilationObserver = null;
  113423. }
  113424. },
  113425. enumerable: true,
  113426. configurable: true
  113427. });
  113428. /**
  113429. * Dispose and release associated resources.
  113430. */
  113431. EngineInstrumentation.prototype.dispose = function () {
  113432. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  113433. this._onBeginFrameObserver = null;
  113434. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  113435. this._onEndFrameObserver = null;
  113436. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  113437. this._onBeforeShaderCompilationObserver = null;
  113438. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  113439. this._onAfterShaderCompilationObserver = null;
  113440. this.engine = null;
  113441. };
  113442. return EngineInstrumentation;
  113443. }());
  113444. BABYLON.EngineInstrumentation = EngineInstrumentation;
  113445. })(BABYLON || (BABYLON = {}));
  113446. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  113447. var BABYLON;
  113448. (function (BABYLON) {
  113449. /**
  113450. * This class can be used to get instrumentation data from a Babylon engine
  113451. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113452. */
  113453. var SceneInstrumentation = /** @class */ (function () {
  113454. /**
  113455. * Instantiates a new scene instrumentation.
  113456. * This class can be used to get instrumentation data from a Babylon engine
  113457. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#sceneinstrumentation
  113458. * @param scene Defines the scene to instrument
  113459. */
  113460. function SceneInstrumentation(
  113461. /**
  113462. * Defines the scene to instrument
  113463. */
  113464. scene) {
  113465. var _this = this;
  113466. this.scene = scene;
  113467. this._captureActiveMeshesEvaluationTime = false;
  113468. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  113469. this._captureRenderTargetsRenderTime = false;
  113470. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  113471. this._captureFrameTime = false;
  113472. this._frameTime = new BABYLON.PerfCounter();
  113473. this._captureRenderTime = false;
  113474. this._renderTime = new BABYLON.PerfCounter();
  113475. this._captureInterFrameTime = false;
  113476. this._interFrameTime = new BABYLON.PerfCounter();
  113477. this._captureParticlesRenderTime = false;
  113478. this._particlesRenderTime = new BABYLON.PerfCounter();
  113479. this._captureSpritesRenderTime = false;
  113480. this._spritesRenderTime = new BABYLON.PerfCounter();
  113481. this._capturePhysicsTime = false;
  113482. this._physicsTime = new BABYLON.PerfCounter();
  113483. this._captureAnimationsTime = false;
  113484. this._animationsTime = new BABYLON.PerfCounter();
  113485. this._captureCameraRenderTime = false;
  113486. this._cameraRenderTime = new BABYLON.PerfCounter();
  113487. // Observers
  113488. this._onBeforeActiveMeshesEvaluationObserver = null;
  113489. this._onAfterActiveMeshesEvaluationObserver = null;
  113490. this._onBeforeRenderTargetsRenderObserver = null;
  113491. this._onAfterRenderTargetsRenderObserver = null;
  113492. this._onAfterRenderObserver = null;
  113493. this._onBeforeDrawPhaseObserver = null;
  113494. this._onAfterDrawPhaseObserver = null;
  113495. this._onBeforeAnimationsObserver = null;
  113496. this._onBeforeParticlesRenderingObserver = null;
  113497. this._onAfterParticlesRenderingObserver = null;
  113498. this._onBeforeSpritesRenderingObserver = null;
  113499. this._onAfterSpritesRenderingObserver = null;
  113500. this._onBeforePhysicsObserver = null;
  113501. this._onAfterPhysicsObserver = null;
  113502. this._onAfterAnimationsObserver = null;
  113503. this._onBeforeCameraRenderObserver = null;
  113504. this._onAfterCameraRenderObserver = null;
  113505. // Before render
  113506. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  113507. if (_this._captureActiveMeshesEvaluationTime) {
  113508. _this._activeMeshesEvaluationTime.fetchNewFrame();
  113509. }
  113510. if (_this._captureRenderTargetsRenderTime) {
  113511. _this._renderTargetsRenderTime.fetchNewFrame();
  113512. }
  113513. if (_this._captureFrameTime) {
  113514. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  113515. _this._frameTime.beginMonitoring();
  113516. }
  113517. if (_this._captureInterFrameTime) {
  113518. _this._interFrameTime.endMonitoring();
  113519. }
  113520. if (_this._captureParticlesRenderTime) {
  113521. _this._particlesRenderTime.fetchNewFrame();
  113522. }
  113523. if (_this._captureSpritesRenderTime) {
  113524. _this._spritesRenderTime.fetchNewFrame();
  113525. }
  113526. if (_this._captureAnimationsTime) {
  113527. _this._animationsTime.beginMonitoring();
  113528. }
  113529. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  113530. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  113531. });
  113532. // After render
  113533. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  113534. if (_this._captureFrameTime) {
  113535. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  113536. _this._frameTime.endMonitoring();
  113537. }
  113538. if (_this._captureRenderTime) {
  113539. _this._renderTime.endMonitoring(false);
  113540. }
  113541. if (_this._captureInterFrameTime) {
  113542. _this._interFrameTime.beginMonitoring();
  113543. }
  113544. });
  113545. }
  113546. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  113547. // Properties
  113548. /**
  113549. * Gets the perf counter used for active meshes evaluation time
  113550. */
  113551. get: function () {
  113552. return this._activeMeshesEvaluationTime;
  113553. },
  113554. enumerable: true,
  113555. configurable: true
  113556. });
  113557. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  113558. /**
  113559. * Gets the active meshes evaluation time capture status
  113560. */
  113561. get: function () {
  113562. return this._captureActiveMeshesEvaluationTime;
  113563. },
  113564. /**
  113565. * Enable or disable the active meshes evaluation time capture
  113566. */
  113567. set: function (value) {
  113568. var _this = this;
  113569. if (value === this._captureActiveMeshesEvaluationTime) {
  113570. return;
  113571. }
  113572. this._captureActiveMeshesEvaluationTime = value;
  113573. if (value) {
  113574. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  113575. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  113576. _this._activeMeshesEvaluationTime.beginMonitoring();
  113577. });
  113578. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  113579. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  113580. _this._activeMeshesEvaluationTime.endMonitoring();
  113581. });
  113582. }
  113583. else {
  113584. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113585. this._onBeforeActiveMeshesEvaluationObserver = null;
  113586. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113587. this._onAfterActiveMeshesEvaluationObserver = null;
  113588. }
  113589. },
  113590. enumerable: true,
  113591. configurable: true
  113592. });
  113593. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  113594. /**
  113595. * Gets the perf counter used for render targets render time
  113596. */
  113597. get: function () {
  113598. return this._renderTargetsRenderTime;
  113599. },
  113600. enumerable: true,
  113601. configurable: true
  113602. });
  113603. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  113604. /**
  113605. * Gets the render targets render time capture status
  113606. */
  113607. get: function () {
  113608. return this._captureRenderTargetsRenderTime;
  113609. },
  113610. /**
  113611. * Enable or disable the render targets render time capture
  113612. */
  113613. set: function (value) {
  113614. var _this = this;
  113615. if (value === this._captureRenderTargetsRenderTime) {
  113616. return;
  113617. }
  113618. this._captureRenderTargetsRenderTime = value;
  113619. if (value) {
  113620. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  113621. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  113622. _this._renderTargetsRenderTime.beginMonitoring();
  113623. });
  113624. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  113625. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  113626. _this._renderTargetsRenderTime.endMonitoring(false);
  113627. });
  113628. }
  113629. else {
  113630. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113631. this._onBeforeRenderTargetsRenderObserver = null;
  113632. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113633. this._onAfterRenderTargetsRenderObserver = null;
  113634. }
  113635. },
  113636. enumerable: true,
  113637. configurable: true
  113638. });
  113639. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  113640. /**
  113641. * Gets the perf counter used for particles render time
  113642. */
  113643. get: function () {
  113644. return this._particlesRenderTime;
  113645. },
  113646. enumerable: true,
  113647. configurable: true
  113648. });
  113649. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  113650. /**
  113651. * Gets the particles render time capture status
  113652. */
  113653. get: function () {
  113654. return this._captureParticlesRenderTime;
  113655. },
  113656. /**
  113657. * Enable or disable the particles render time capture
  113658. */
  113659. set: function (value) {
  113660. var _this = this;
  113661. if (value === this._captureParticlesRenderTime) {
  113662. return;
  113663. }
  113664. this._captureParticlesRenderTime = value;
  113665. if (value) {
  113666. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  113667. BABYLON.Tools.StartPerformanceCounter("Particles");
  113668. _this._particlesRenderTime.beginMonitoring();
  113669. });
  113670. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  113671. BABYLON.Tools.EndPerformanceCounter("Particles");
  113672. _this._particlesRenderTime.endMonitoring(false);
  113673. });
  113674. }
  113675. else {
  113676. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  113677. this._onBeforeParticlesRenderingObserver = null;
  113678. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  113679. this._onAfterParticlesRenderingObserver = null;
  113680. }
  113681. },
  113682. enumerable: true,
  113683. configurable: true
  113684. });
  113685. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  113686. /**
  113687. * Gets the perf counter used for sprites render time
  113688. */
  113689. get: function () {
  113690. return this._spritesRenderTime;
  113691. },
  113692. enumerable: true,
  113693. configurable: true
  113694. });
  113695. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  113696. /**
  113697. * Gets the sprites render time capture status
  113698. */
  113699. get: function () {
  113700. return this._captureSpritesRenderTime;
  113701. },
  113702. /**
  113703. * Enable or disable the sprites render time capture
  113704. */
  113705. set: function (value) {
  113706. var _this = this;
  113707. if (value === this._captureSpritesRenderTime) {
  113708. return;
  113709. }
  113710. this._captureSpritesRenderTime = value;
  113711. if (!this.scene.spriteManagers) {
  113712. return;
  113713. }
  113714. if (value) {
  113715. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  113716. BABYLON.Tools.StartPerformanceCounter("Sprites");
  113717. _this._spritesRenderTime.beginMonitoring();
  113718. });
  113719. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  113720. BABYLON.Tools.EndPerformanceCounter("Sprites");
  113721. _this._spritesRenderTime.endMonitoring(false);
  113722. });
  113723. }
  113724. else {
  113725. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  113726. this._onBeforeSpritesRenderingObserver = null;
  113727. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  113728. this._onAfterSpritesRenderingObserver = null;
  113729. }
  113730. },
  113731. enumerable: true,
  113732. configurable: true
  113733. });
  113734. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  113735. /**
  113736. * Gets the perf counter used for physics time
  113737. */
  113738. get: function () {
  113739. return this._physicsTime;
  113740. },
  113741. enumerable: true,
  113742. configurable: true
  113743. });
  113744. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  113745. /**
  113746. * Gets the physics time capture status
  113747. */
  113748. get: function () {
  113749. return this._capturePhysicsTime;
  113750. },
  113751. /**
  113752. * Enable or disable the physics time capture
  113753. */
  113754. set: function (value) {
  113755. var _this = this;
  113756. if (value === this._capturePhysicsTime) {
  113757. return;
  113758. }
  113759. if (!this.scene.onBeforePhysicsObservable) {
  113760. return;
  113761. }
  113762. this._capturePhysicsTime = value;
  113763. if (value) {
  113764. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  113765. BABYLON.Tools.StartPerformanceCounter("Physics");
  113766. _this._physicsTime.beginMonitoring();
  113767. });
  113768. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  113769. BABYLON.Tools.EndPerformanceCounter("Physics");
  113770. _this._physicsTime.endMonitoring();
  113771. });
  113772. }
  113773. else {
  113774. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  113775. this._onBeforePhysicsObserver = null;
  113776. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  113777. this._onAfterPhysicsObserver = null;
  113778. }
  113779. },
  113780. enumerable: true,
  113781. configurable: true
  113782. });
  113783. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  113784. /**
  113785. * Gets the perf counter used for animations time
  113786. */
  113787. get: function () {
  113788. return this._animationsTime;
  113789. },
  113790. enumerable: true,
  113791. configurable: true
  113792. });
  113793. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  113794. /**
  113795. * Gets the animations time capture status
  113796. */
  113797. get: function () {
  113798. return this._captureAnimationsTime;
  113799. },
  113800. /**
  113801. * Enable or disable the animations time capture
  113802. */
  113803. set: function (value) {
  113804. var _this = this;
  113805. if (value === this._captureAnimationsTime) {
  113806. return;
  113807. }
  113808. this._captureAnimationsTime = value;
  113809. if (value) {
  113810. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  113811. _this._animationsTime.endMonitoring();
  113812. });
  113813. }
  113814. else {
  113815. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  113816. this._onAfterAnimationsObserver = null;
  113817. }
  113818. },
  113819. enumerable: true,
  113820. configurable: true
  113821. });
  113822. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  113823. /**
  113824. * Gets the perf counter used for frame time capture
  113825. */
  113826. get: function () {
  113827. return this._frameTime;
  113828. },
  113829. enumerable: true,
  113830. configurable: true
  113831. });
  113832. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  113833. /**
  113834. * Gets the frame time capture status
  113835. */
  113836. get: function () {
  113837. return this._captureFrameTime;
  113838. },
  113839. /**
  113840. * Enable or disable the frame time capture
  113841. */
  113842. set: function (value) {
  113843. this._captureFrameTime = value;
  113844. },
  113845. enumerable: true,
  113846. configurable: true
  113847. });
  113848. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  113849. /**
  113850. * Gets the perf counter used for inter-frames time capture
  113851. */
  113852. get: function () {
  113853. return this._interFrameTime;
  113854. },
  113855. enumerable: true,
  113856. configurable: true
  113857. });
  113858. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  113859. /**
  113860. * Gets the inter-frames time capture status
  113861. */
  113862. get: function () {
  113863. return this._captureInterFrameTime;
  113864. },
  113865. /**
  113866. * Enable or disable the inter-frames time capture
  113867. */
  113868. set: function (value) {
  113869. this._captureInterFrameTime = value;
  113870. },
  113871. enumerable: true,
  113872. configurable: true
  113873. });
  113874. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  113875. /**
  113876. * Gets the perf counter used for render time capture
  113877. */
  113878. get: function () {
  113879. return this._renderTime;
  113880. },
  113881. enumerable: true,
  113882. configurable: true
  113883. });
  113884. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  113885. /**
  113886. * Gets the render time capture status
  113887. */
  113888. get: function () {
  113889. return this._captureRenderTime;
  113890. },
  113891. /**
  113892. * Enable or disable the render time capture
  113893. */
  113894. set: function (value) {
  113895. var _this = this;
  113896. if (value === this._captureRenderTime) {
  113897. return;
  113898. }
  113899. this._captureRenderTime = value;
  113900. if (value) {
  113901. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  113902. _this._renderTime.beginMonitoring();
  113903. BABYLON.Tools.StartPerformanceCounter("Main render");
  113904. });
  113905. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  113906. _this._renderTime.endMonitoring(false);
  113907. BABYLON.Tools.EndPerformanceCounter("Main render");
  113908. });
  113909. }
  113910. else {
  113911. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  113912. this._onBeforeDrawPhaseObserver = null;
  113913. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  113914. this._onAfterDrawPhaseObserver = null;
  113915. }
  113916. },
  113917. enumerable: true,
  113918. configurable: true
  113919. });
  113920. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  113921. /**
  113922. * Gets the perf counter used for camera render time capture
  113923. */
  113924. get: function () {
  113925. return this._cameraRenderTime;
  113926. },
  113927. enumerable: true,
  113928. configurable: true
  113929. });
  113930. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  113931. /**
  113932. * Gets the camera render time capture status
  113933. */
  113934. get: function () {
  113935. return this._captureCameraRenderTime;
  113936. },
  113937. /**
  113938. * Enable or disable the camera render time capture
  113939. */
  113940. set: function (value) {
  113941. var _this = this;
  113942. if (value === this._captureCameraRenderTime) {
  113943. return;
  113944. }
  113945. this._captureCameraRenderTime = value;
  113946. if (value) {
  113947. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  113948. _this._cameraRenderTime.beginMonitoring();
  113949. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  113950. });
  113951. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  113952. _this._cameraRenderTime.endMonitoring(false);
  113953. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  113954. });
  113955. }
  113956. else {
  113957. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  113958. this._onBeforeCameraRenderObserver = null;
  113959. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  113960. this._onAfterCameraRenderObserver = null;
  113961. }
  113962. },
  113963. enumerable: true,
  113964. configurable: true
  113965. });
  113966. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  113967. /**
  113968. * Gets the perf counter used for draw calls
  113969. */
  113970. get: function () {
  113971. return this.scene.getEngine()._drawCalls;
  113972. },
  113973. enumerable: true,
  113974. configurable: true
  113975. });
  113976. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  113977. /**
  113978. * Gets the perf counter used for texture collisions
  113979. */
  113980. get: function () {
  113981. return this.scene.getEngine()._textureCollisions;
  113982. },
  113983. enumerable: true,
  113984. configurable: true
  113985. });
  113986. /**
  113987. * Dispose and release associated resources.
  113988. */
  113989. SceneInstrumentation.prototype.dispose = function () {
  113990. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  113991. this._onAfterRenderObserver = null;
  113992. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  113993. this._onBeforeActiveMeshesEvaluationObserver = null;
  113994. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  113995. this._onAfterActiveMeshesEvaluationObserver = null;
  113996. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  113997. this._onBeforeRenderTargetsRenderObserver = null;
  113998. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  113999. this._onAfterRenderTargetsRenderObserver = null;
  114000. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  114001. this._onBeforeAnimationsObserver = null;
  114002. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  114003. this._onBeforeParticlesRenderingObserver = null;
  114004. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  114005. this._onAfterParticlesRenderingObserver = null;
  114006. if (this._onBeforeSpritesRenderingObserver) {
  114007. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  114008. this._onBeforeSpritesRenderingObserver = null;
  114009. }
  114010. if (this._onAfterSpritesRenderingObserver) {
  114011. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  114012. this._onAfterSpritesRenderingObserver = null;
  114013. }
  114014. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  114015. this._onBeforeDrawPhaseObserver = null;
  114016. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  114017. this._onAfterDrawPhaseObserver = null;
  114018. if (this._onBeforePhysicsObserver) {
  114019. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  114020. this._onBeforePhysicsObserver = null;
  114021. }
  114022. if (this._onAfterPhysicsObserver) {
  114023. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  114024. this._onAfterPhysicsObserver = null;
  114025. }
  114026. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  114027. this._onAfterAnimationsObserver = null;
  114028. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  114029. this._onBeforeCameraRenderObserver = null;
  114030. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  114031. this._onAfterCameraRenderObserver = null;
  114032. this.scene = null;
  114033. };
  114034. return SceneInstrumentation;
  114035. }());
  114036. BABYLON.SceneInstrumentation = SceneInstrumentation;
  114037. })(BABYLON || (BABYLON = {}));
  114038. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  114039. var BABYLON;
  114040. (function (BABYLON) {
  114041. /**
  114042. * @hidden
  114043. **/
  114044. var _TimeToken = /** @class */ (function () {
  114045. function _TimeToken() {
  114046. this._timeElapsedQueryEnded = false;
  114047. }
  114048. return _TimeToken;
  114049. }());
  114050. BABYLON._TimeToken = _TimeToken;
  114051. })(BABYLON || (BABYLON = {}));
  114052. //# sourceMappingURL=babylon.timeToken.js.map
  114053. var BABYLON;
  114054. (function (BABYLON) {
  114055. /**
  114056. * Background material defines definition.
  114057. * @hidden Mainly internal Use
  114058. */
  114059. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  114060. __extends(BackgroundMaterialDefines, _super);
  114061. /**
  114062. * Constructor of the defines.
  114063. */
  114064. function BackgroundMaterialDefines() {
  114065. var _this = _super.call(this) || this;
  114066. /**
  114067. * True if the diffuse texture is in use.
  114068. */
  114069. _this.DIFFUSE = false;
  114070. /**
  114071. * The direct UV channel to use.
  114072. */
  114073. _this.DIFFUSEDIRECTUV = 0;
  114074. /**
  114075. * True if the diffuse texture is in gamma space.
  114076. */
  114077. _this.GAMMADIFFUSE = false;
  114078. /**
  114079. * True if the diffuse texture has opacity in the alpha channel.
  114080. */
  114081. _this.DIFFUSEHASALPHA = false;
  114082. /**
  114083. * True if you want the material to fade to transparent at grazing angle.
  114084. */
  114085. _this.OPACITYFRESNEL = false;
  114086. /**
  114087. * True if an extra blur needs to be added in the reflection.
  114088. */
  114089. _this.REFLECTIONBLUR = false;
  114090. /**
  114091. * True if you want the material to fade to reflection at grazing angle.
  114092. */
  114093. _this.REFLECTIONFRESNEL = false;
  114094. /**
  114095. * True if you want the material to falloff as far as you move away from the scene center.
  114096. */
  114097. _this.REFLECTIONFALLOFF = false;
  114098. /**
  114099. * False if the current Webgl implementation does not support the texture lod extension.
  114100. */
  114101. _this.TEXTURELODSUPPORT = false;
  114102. /**
  114103. * True to ensure the data are premultiplied.
  114104. */
  114105. _this.PREMULTIPLYALPHA = false;
  114106. /**
  114107. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  114108. */
  114109. _this.USERGBCOLOR = false;
  114110. /**
  114111. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  114112. * stays aligned with the desired configuration.
  114113. */
  114114. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  114115. /**
  114116. * True to add noise in order to reduce the banding effect.
  114117. */
  114118. _this.NOISE = false;
  114119. /**
  114120. * is the reflection texture in BGR color scheme?
  114121. * Mainly used to solve a bug in ios10 video tag
  114122. */
  114123. _this.REFLECTIONBGR = false;
  114124. _this.IMAGEPROCESSING = false;
  114125. _this.VIGNETTE = false;
  114126. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  114127. _this.VIGNETTEBLENDMODEOPAQUE = false;
  114128. _this.TONEMAPPING = false;
  114129. _this.TONEMAPPING_ACES = false;
  114130. _this.CONTRAST = false;
  114131. _this.COLORCURVES = false;
  114132. _this.COLORGRADING = false;
  114133. _this.COLORGRADING3D = false;
  114134. _this.SAMPLER3DGREENDEPTH = false;
  114135. _this.SAMPLER3DBGRMAP = false;
  114136. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  114137. _this.EXPOSURE = false;
  114138. // Reflection.
  114139. _this.REFLECTION = false;
  114140. _this.REFLECTIONMAP_3D = false;
  114141. _this.REFLECTIONMAP_SPHERICAL = false;
  114142. _this.REFLECTIONMAP_PLANAR = false;
  114143. _this.REFLECTIONMAP_CUBIC = false;
  114144. _this.REFLECTIONMAP_PROJECTION = false;
  114145. _this.REFLECTIONMAP_SKYBOX = false;
  114146. _this.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114147. _this.REFLECTIONMAP_EXPLICIT = false;
  114148. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114149. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114150. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114151. _this.INVERTCUBICMAP = false;
  114152. _this.REFLECTIONMAP_OPPOSITEZ = false;
  114153. _this.LODINREFLECTIONALPHA = false;
  114154. _this.GAMMAREFLECTION = false;
  114155. _this.RGBDREFLECTION = false;
  114156. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  114157. // Default BJS.
  114158. _this.MAINUV1 = false;
  114159. _this.MAINUV2 = false;
  114160. _this.UV1 = false;
  114161. _this.UV2 = false;
  114162. _this.CLIPPLANE = false;
  114163. _this.CLIPPLANE2 = false;
  114164. _this.CLIPPLANE3 = false;
  114165. _this.CLIPPLANE4 = false;
  114166. _this.POINTSIZE = false;
  114167. _this.FOG = false;
  114168. _this.NORMAL = false;
  114169. _this.NUM_BONE_INFLUENCERS = 0;
  114170. _this.BonesPerMesh = 0;
  114171. _this.INSTANCES = false;
  114172. _this.SHADOWFLOAT = false;
  114173. _this.rebuild();
  114174. return _this;
  114175. }
  114176. return BackgroundMaterialDefines;
  114177. }(BABYLON.MaterialDefines));
  114178. /**
  114179. * Background material used to create an efficient environement around your scene.
  114180. */
  114181. var BackgroundMaterial = /** @class */ (function (_super) {
  114182. __extends(BackgroundMaterial, _super);
  114183. /**
  114184. * Instantiates a Background Material in the given scene
  114185. * @param name The friendly name of the material
  114186. * @param scene The scene to add the material to
  114187. */
  114188. function BackgroundMaterial(name, scene) {
  114189. var _this = _super.call(this, name, scene) || this;
  114190. /**
  114191. * Key light Color (multiply against the environement texture)
  114192. */
  114193. _this.primaryColor = BABYLON.Color3.White();
  114194. _this._primaryColorShadowLevel = 0;
  114195. _this._primaryColorHighlightLevel = 0;
  114196. /**
  114197. * Reflection Texture used in the material.
  114198. * Should be author in a specific way for the best result (refer to the documentation).
  114199. */
  114200. _this.reflectionTexture = null;
  114201. /**
  114202. * Reflection Texture level of blur.
  114203. *
  114204. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  114205. * texture twice.
  114206. */
  114207. _this.reflectionBlur = 0;
  114208. /**
  114209. * Diffuse Texture used in the material.
  114210. * Should be author in a specific way for the best result (refer to the documentation).
  114211. */
  114212. _this.diffuseTexture = null;
  114213. _this._shadowLights = null;
  114214. /**
  114215. * Specify the list of lights casting shadow on the material.
  114216. * All scene shadow lights will be included if null.
  114217. */
  114218. _this.shadowLights = null;
  114219. /**
  114220. * Helps adjusting the shadow to a softer level if required.
  114221. * 0 means black shadows and 1 means no shadows.
  114222. */
  114223. _this.shadowLevel = 0;
  114224. /**
  114225. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  114226. * It is usually zero but might be interesting to modify according to your setup.
  114227. */
  114228. _this.sceneCenter = BABYLON.Vector3.Zero();
  114229. /**
  114230. * This helps specifying that the material is falling off to the sky box at grazing angle.
  114231. * This helps ensuring a nice transition when the camera goes under the ground.
  114232. */
  114233. _this.opacityFresnel = true;
  114234. /**
  114235. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  114236. * This helps adding a mirror texture on the ground.
  114237. */
  114238. _this.reflectionFresnel = false;
  114239. /**
  114240. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  114241. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  114242. */
  114243. _this.reflectionFalloffDistance = 0.0;
  114244. /**
  114245. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  114246. */
  114247. _this.reflectionAmount = 1.0;
  114248. /**
  114249. * This specifies the weight of the reflection at grazing angle.
  114250. */
  114251. _this.reflectionReflectance0 = 0.05;
  114252. /**
  114253. * This specifies the weight of the reflection at a perpendicular point of view.
  114254. */
  114255. _this.reflectionReflectance90 = 0.5;
  114256. /**
  114257. * Helps to directly use the maps channels instead of their level.
  114258. */
  114259. _this.useRGBColor = true;
  114260. /**
  114261. * This helps reducing the banding effect that could occur on the background.
  114262. */
  114263. _this.enableNoise = false;
  114264. _this._fovMultiplier = 1.0;
  114265. /**
  114266. * Enable the FOV adjustment feature controlled by fovMultiplier.
  114267. */
  114268. _this.useEquirectangularFOV = false;
  114269. _this._maxSimultaneousLights = 4;
  114270. /**
  114271. * Number of Simultaneous lights allowed on the material.
  114272. */
  114273. _this.maxSimultaneousLights = 4;
  114274. /**
  114275. * Keep track of the image processing observer to allow dispose and replace.
  114276. */
  114277. _this._imageProcessingObserver = null;
  114278. /**
  114279. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  114280. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  114281. */
  114282. _this.switchToBGR = false;
  114283. // Temp values kept as cache in the material.
  114284. _this._renderTargets = new BABYLON.SmartArray(16);
  114285. _this._reflectionControls = BABYLON.Vector4.Zero();
  114286. _this._white = BABYLON.Color3.White();
  114287. _this._primaryShadowColor = BABYLON.Color3.Black();
  114288. _this._primaryHighlightColor = BABYLON.Color3.Black();
  114289. // Setup the default processing configuration to the scene.
  114290. _this._attachImageProcessingConfiguration(null);
  114291. _this.getRenderTargetTextures = function () {
  114292. _this._renderTargets.reset();
  114293. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  114294. _this._renderTargets.push(_this._diffuseTexture);
  114295. }
  114296. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  114297. _this._renderTargets.push(_this._reflectionTexture);
  114298. }
  114299. return _this._renderTargets;
  114300. };
  114301. return _this;
  114302. }
  114303. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  114304. /**
  114305. * Experimental Internal Use Only.
  114306. *
  114307. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  114308. * This acts as a helper to set the primary color to a more "human friendly" value.
  114309. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  114310. * output color as close as possible from the chosen value.
  114311. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  114312. * part of lighting setup.)
  114313. */
  114314. get: function () {
  114315. return this.__perceptualColor;
  114316. },
  114317. set: function (value) {
  114318. this.__perceptualColor = value;
  114319. this._computePrimaryColorFromPerceptualColor();
  114320. this._markAllSubMeshesAsLightsDirty();
  114321. },
  114322. enumerable: true,
  114323. configurable: true
  114324. });
  114325. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  114326. /**
  114327. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  114328. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  114329. */
  114330. get: function () {
  114331. return this._primaryColorShadowLevel;
  114332. },
  114333. set: function (value) {
  114334. this._primaryColorShadowLevel = value;
  114335. this._computePrimaryColors();
  114336. this._markAllSubMeshesAsLightsDirty();
  114337. },
  114338. enumerable: true,
  114339. configurable: true
  114340. });
  114341. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  114342. /**
  114343. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  114344. * The primary color is used at the level chosen to define what the white area would look.
  114345. */
  114346. get: function () {
  114347. return this._primaryColorHighlightLevel;
  114348. },
  114349. set: function (value) {
  114350. this._primaryColorHighlightLevel = value;
  114351. this._computePrimaryColors();
  114352. this._markAllSubMeshesAsLightsDirty();
  114353. },
  114354. enumerable: true,
  114355. configurable: true
  114356. });
  114357. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  114358. /**
  114359. * Sets the reflection reflectance fresnel values according to the default standard
  114360. * empirically know to work well :-)
  114361. */
  114362. set: function (value) {
  114363. var reflectionWeight = value;
  114364. if (reflectionWeight < 0.5) {
  114365. reflectionWeight = reflectionWeight * 2.0;
  114366. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  114367. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  114368. }
  114369. else {
  114370. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  114371. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  114372. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  114373. }
  114374. },
  114375. enumerable: true,
  114376. configurable: true
  114377. });
  114378. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  114379. /**
  114380. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  114381. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  114382. * Recommended to be keep at 1.0 except for special cases.
  114383. */
  114384. get: function () {
  114385. return this._fovMultiplier;
  114386. },
  114387. set: function (value) {
  114388. if (isNaN(value)) {
  114389. value = 1.0;
  114390. }
  114391. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  114392. },
  114393. enumerable: true,
  114394. configurable: true
  114395. });
  114396. /**
  114397. * Attaches a new image processing configuration to the PBR Material.
  114398. * @param configuration (if null the scene configuration will be use)
  114399. */
  114400. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  114401. var _this = this;
  114402. if (configuration === this._imageProcessingConfiguration) {
  114403. return;
  114404. }
  114405. // Detaches observer.
  114406. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  114407. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  114408. }
  114409. // Pick the scene configuration if needed.
  114410. if (!configuration) {
  114411. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  114412. }
  114413. else {
  114414. this._imageProcessingConfiguration = configuration;
  114415. }
  114416. // Attaches observer.
  114417. if (this._imageProcessingConfiguration) {
  114418. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  114419. _this._computePrimaryColorFromPerceptualColor();
  114420. _this._markAllSubMeshesAsImageProcessingDirty();
  114421. });
  114422. }
  114423. };
  114424. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  114425. /**
  114426. * Gets the image processing configuration used either in this material.
  114427. */
  114428. get: function () {
  114429. return this._imageProcessingConfiguration;
  114430. },
  114431. /**
  114432. * Sets the Default image processing configuration used either in the this material.
  114433. *
  114434. * If sets to null, the scene one is in use.
  114435. */
  114436. set: function (value) {
  114437. this._attachImageProcessingConfiguration(value);
  114438. // Ensure the effect will be rebuilt.
  114439. this._markAllSubMeshesAsTexturesDirty();
  114440. },
  114441. enumerable: true,
  114442. configurable: true
  114443. });
  114444. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  114445. /**
  114446. * Gets wether the color curves effect is enabled.
  114447. */
  114448. get: function () {
  114449. return this.imageProcessingConfiguration.colorCurvesEnabled;
  114450. },
  114451. /**
  114452. * Sets wether the color curves effect is enabled.
  114453. */
  114454. set: function (value) {
  114455. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  114456. },
  114457. enumerable: true,
  114458. configurable: true
  114459. });
  114460. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  114461. /**
  114462. * Gets wether the color grading effect is enabled.
  114463. */
  114464. get: function () {
  114465. return this.imageProcessingConfiguration.colorGradingEnabled;
  114466. },
  114467. /**
  114468. * Gets wether the color grading effect is enabled.
  114469. */
  114470. set: function (value) {
  114471. this.imageProcessingConfiguration.colorGradingEnabled = value;
  114472. },
  114473. enumerable: true,
  114474. configurable: true
  114475. });
  114476. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  114477. /**
  114478. * Gets wether tonemapping is enabled or not.
  114479. */
  114480. get: function () {
  114481. return this._imageProcessingConfiguration.toneMappingEnabled;
  114482. },
  114483. /**
  114484. * Sets wether tonemapping is enabled or not
  114485. */
  114486. set: function (value) {
  114487. this._imageProcessingConfiguration.toneMappingEnabled = value;
  114488. },
  114489. enumerable: true,
  114490. configurable: true
  114491. });
  114492. ;
  114493. ;
  114494. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  114495. /**
  114496. * The camera exposure used on this material.
  114497. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114498. * This corresponds to a photographic exposure.
  114499. */
  114500. get: function () {
  114501. return this._imageProcessingConfiguration.exposure;
  114502. },
  114503. /**
  114504. * The camera exposure used on this material.
  114505. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  114506. * This corresponds to a photographic exposure.
  114507. */
  114508. set: function (value) {
  114509. this._imageProcessingConfiguration.exposure = value;
  114510. },
  114511. enumerable: true,
  114512. configurable: true
  114513. });
  114514. ;
  114515. ;
  114516. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  114517. /**
  114518. * Gets The camera contrast used on this material.
  114519. */
  114520. get: function () {
  114521. return this._imageProcessingConfiguration.contrast;
  114522. },
  114523. /**
  114524. * Sets The camera contrast used on this material.
  114525. */
  114526. set: function (value) {
  114527. this._imageProcessingConfiguration.contrast = value;
  114528. },
  114529. enumerable: true,
  114530. configurable: true
  114531. });
  114532. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  114533. /**
  114534. * Gets the Color Grading 2D Lookup Texture.
  114535. */
  114536. get: function () {
  114537. return this._imageProcessingConfiguration.colorGradingTexture;
  114538. },
  114539. /**
  114540. * Sets the Color Grading 2D Lookup Texture.
  114541. */
  114542. set: function (value) {
  114543. this.imageProcessingConfiguration.colorGradingTexture = value;
  114544. },
  114545. enumerable: true,
  114546. configurable: true
  114547. });
  114548. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  114549. /**
  114550. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114551. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114552. * 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;
  114553. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114554. */
  114555. get: function () {
  114556. return this.imageProcessingConfiguration.colorCurves;
  114557. },
  114558. /**
  114559. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  114560. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  114561. * 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;
  114562. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  114563. */
  114564. set: function (value) {
  114565. this.imageProcessingConfiguration.colorCurves = value;
  114566. },
  114567. enumerable: true,
  114568. configurable: true
  114569. });
  114570. Object.defineProperty(BackgroundMaterial.prototype, "hasRenderTargetTextures", {
  114571. /**
  114572. * Gets a boolean indicating that current material needs to register RTT
  114573. */
  114574. get: function () {
  114575. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114576. return true;
  114577. }
  114578. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114579. return true;
  114580. }
  114581. return false;
  114582. },
  114583. enumerable: true,
  114584. configurable: true
  114585. });
  114586. /**
  114587. * The entire material has been created in order to prevent overdraw.
  114588. * @returns false
  114589. */
  114590. BackgroundMaterial.prototype.needAlphaTesting = function () {
  114591. return true;
  114592. };
  114593. /**
  114594. * The entire material has been created in order to prevent overdraw.
  114595. * @returns true if blending is enable
  114596. */
  114597. BackgroundMaterial.prototype.needAlphaBlending = function () {
  114598. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  114599. };
  114600. /**
  114601. * Checks wether the material is ready to be rendered for a given mesh.
  114602. * @param mesh The mesh to render
  114603. * @param subMesh The submesh to check against
  114604. * @param useInstances Specify wether or not the material is used with instances
  114605. * @returns true if all the dependencies are ready (Textures, Effects...)
  114606. */
  114607. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  114608. var _this = this;
  114609. if (useInstances === void 0) { useInstances = false; }
  114610. if (subMesh.effect && this.isFrozen) {
  114611. if (this._wasPreviouslyReady) {
  114612. return true;
  114613. }
  114614. }
  114615. if (!subMesh._materialDefines) {
  114616. subMesh._materialDefines = new BackgroundMaterialDefines();
  114617. }
  114618. var scene = this.getScene();
  114619. var defines = subMesh._materialDefines;
  114620. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  114621. if (defines._renderId === scene.getRenderId()) {
  114622. return true;
  114623. }
  114624. }
  114625. var engine = scene.getEngine();
  114626. // Lights
  114627. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  114628. defines._needNormals = true;
  114629. // Textures
  114630. if (defines._areTexturesDirty) {
  114631. defines._needUVs = false;
  114632. if (scene.texturesEnabled) {
  114633. if (scene.getEngine().getCaps().textureLOD) {
  114634. defines.TEXTURELODSUPPORT = true;
  114635. }
  114636. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114637. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  114638. return false;
  114639. }
  114640. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  114641. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  114642. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  114643. defines.OPACITYFRESNEL = this._opacityFresnel;
  114644. }
  114645. else {
  114646. defines.DIFFUSE = false;
  114647. defines.DIFFUSEHASALPHA = false;
  114648. defines.GAMMADIFFUSE = false;
  114649. defines.OPACITYFRESNEL = false;
  114650. }
  114651. var reflectionTexture = this._reflectionTexture;
  114652. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114653. if (!reflectionTexture.isReadyOrNotBlocking()) {
  114654. return false;
  114655. }
  114656. defines.REFLECTION = true;
  114657. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  114658. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  114659. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  114660. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  114661. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  114662. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  114663. defines.REFLECTIONBGR = this.switchToBGR;
  114664. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  114665. defines.INVERTCUBICMAP = true;
  114666. }
  114667. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  114668. switch (reflectionTexture.coordinatesMode) {
  114669. case BABYLON.Texture.EXPLICIT_MODE:
  114670. defines.REFLECTIONMAP_EXPLICIT = true;
  114671. break;
  114672. case BABYLON.Texture.PLANAR_MODE:
  114673. defines.REFLECTIONMAP_PLANAR = true;
  114674. break;
  114675. case BABYLON.Texture.PROJECTION_MODE:
  114676. defines.REFLECTIONMAP_PROJECTION = true;
  114677. break;
  114678. case BABYLON.Texture.SKYBOX_MODE:
  114679. defines.REFLECTIONMAP_SKYBOX = true;
  114680. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = !reflectionTexture.getReflectionTextureMatrix().isIdentity();
  114681. break;
  114682. case BABYLON.Texture.SPHERICAL_MODE:
  114683. defines.REFLECTIONMAP_SPHERICAL = true;
  114684. break;
  114685. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  114686. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  114687. break;
  114688. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  114689. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  114690. break;
  114691. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  114692. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  114693. break;
  114694. case BABYLON.Texture.CUBIC_MODE:
  114695. case BABYLON.Texture.INVCUBIC_MODE:
  114696. default:
  114697. defines.REFLECTIONMAP_CUBIC = true;
  114698. break;
  114699. }
  114700. if (this.reflectionFresnel) {
  114701. defines.REFLECTIONFRESNEL = true;
  114702. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  114703. this._reflectionControls.x = this.reflectionAmount;
  114704. this._reflectionControls.y = this.reflectionReflectance0;
  114705. this._reflectionControls.z = this.reflectionReflectance90;
  114706. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  114707. }
  114708. else {
  114709. defines.REFLECTIONFRESNEL = false;
  114710. defines.REFLECTIONFALLOFF = false;
  114711. }
  114712. }
  114713. else {
  114714. defines.REFLECTION = false;
  114715. defines.REFLECTIONFRESNEL = false;
  114716. defines.REFLECTIONFALLOFF = false;
  114717. defines.REFLECTIONBLUR = false;
  114718. defines.REFLECTIONMAP_3D = false;
  114719. defines.REFLECTIONMAP_SPHERICAL = false;
  114720. defines.REFLECTIONMAP_PLANAR = false;
  114721. defines.REFLECTIONMAP_CUBIC = false;
  114722. defines.REFLECTIONMAP_PROJECTION = false;
  114723. defines.REFLECTIONMAP_SKYBOX = false;
  114724. defines.REFLECTIONMAP_SKYBOX_TRANSFORMED = false;
  114725. defines.REFLECTIONMAP_EXPLICIT = false;
  114726. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  114727. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  114728. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  114729. defines.INVERTCUBICMAP = false;
  114730. defines.REFLECTIONMAP_OPPOSITEZ = false;
  114731. defines.LODINREFLECTIONALPHA = false;
  114732. defines.GAMMAREFLECTION = false;
  114733. defines.RGBDREFLECTION = false;
  114734. }
  114735. }
  114736. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  114737. defines.USERGBCOLOR = this._useRGBColor;
  114738. defines.NOISE = this._enableNoise;
  114739. }
  114740. if (defines._areLightsDirty) {
  114741. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  114742. }
  114743. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  114744. if (!this._imageProcessingConfiguration.isReady()) {
  114745. return false;
  114746. }
  114747. this._imageProcessingConfiguration.prepareDefines(defines);
  114748. }
  114749. // Misc.
  114750. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  114751. // Values that need to be evaluated on every frame
  114752. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  114753. // Attribs
  114754. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  114755. if (mesh) {
  114756. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  114757. mesh.createNormals(true);
  114758. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  114759. }
  114760. }
  114761. }
  114762. // Get correct effect
  114763. if (defines.isDirty) {
  114764. defines.markAsProcessed();
  114765. scene.resetCachedMaterial();
  114766. // Fallbacks
  114767. var fallbacks = new BABYLON.EffectFallbacks();
  114768. if (defines.FOG) {
  114769. fallbacks.addFallback(0, "FOG");
  114770. }
  114771. if (defines.POINTSIZE) {
  114772. fallbacks.addFallback(1, "POINTSIZE");
  114773. }
  114774. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  114775. if (defines.NUM_BONE_INFLUENCERS > 0) {
  114776. fallbacks.addCPUSkinningFallback(0, mesh);
  114777. }
  114778. //Attributes
  114779. var attribs = [BABYLON.VertexBuffer.PositionKind];
  114780. if (defines.NORMAL) {
  114781. attribs.push(BABYLON.VertexBuffer.NormalKind);
  114782. }
  114783. if (defines.UV1) {
  114784. attribs.push(BABYLON.VertexBuffer.UVKind);
  114785. }
  114786. if (defines.UV2) {
  114787. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  114788. }
  114789. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  114790. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  114791. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  114792. "vFogInfos", "vFogColor", "pointSize",
  114793. "vClipPlane", "vClipPlane2", "vClipPlane3", "vClipPlane4", "mBones",
  114794. "vPrimaryColor", "vPrimaryColorShadow",
  114795. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  114796. "shadowLevel", "alpha",
  114797. "vBackgroundCenter", "vReflectionControl",
  114798. "vDiffuseInfos", "diffuseMatrix",
  114799. ];
  114800. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  114801. var uniformBuffers = ["Material", "Scene"];
  114802. if (BABYLON.ImageProcessingConfiguration) {
  114803. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  114804. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  114805. }
  114806. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  114807. uniformsNames: uniforms,
  114808. uniformBuffersNames: uniformBuffers,
  114809. samplers: samplers,
  114810. defines: defines,
  114811. maxSimultaneousLights: this._maxSimultaneousLights
  114812. });
  114813. var onCompiled = function (effect) {
  114814. if (_this.onCompiled) {
  114815. _this.onCompiled(effect);
  114816. }
  114817. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  114818. };
  114819. var join = defines.toString();
  114820. subMesh.setEffect(scene.getEngine().createEffect("background", {
  114821. attributes: attribs,
  114822. uniformsNames: uniforms,
  114823. uniformBuffersNames: uniformBuffers,
  114824. samplers: samplers,
  114825. defines: join,
  114826. fallbacks: fallbacks,
  114827. onCompiled: onCompiled,
  114828. onError: this.onError,
  114829. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  114830. }, engine), defines);
  114831. this.buildUniformLayout();
  114832. }
  114833. if (!subMesh.effect || !subMesh.effect.isReady()) {
  114834. return false;
  114835. }
  114836. defines._renderId = scene.getRenderId();
  114837. this._wasPreviouslyReady = true;
  114838. return true;
  114839. };
  114840. /**
  114841. * Compute the primary color according to the chosen perceptual color.
  114842. */
  114843. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  114844. if (!this.__perceptualColor) {
  114845. return;
  114846. }
  114847. this._primaryColor.copyFrom(this.__perceptualColor);
  114848. // Revert gamma space.
  114849. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  114850. // Revert image processing configuration.
  114851. if (this._imageProcessingConfiguration) {
  114852. // Revert Exposure.
  114853. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  114854. }
  114855. this._computePrimaryColors();
  114856. };
  114857. /**
  114858. * Compute the highlights and shadow colors according to their chosen levels.
  114859. */
  114860. BackgroundMaterial.prototype._computePrimaryColors = function () {
  114861. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  114862. return;
  114863. }
  114864. // Find the highlight color based on the configuration.
  114865. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  114866. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  114867. // Find the shadow color based on the configuration.
  114868. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  114869. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  114870. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  114871. };
  114872. /**
  114873. * Build the uniform buffer used in the material.
  114874. */
  114875. BackgroundMaterial.prototype.buildUniformLayout = function () {
  114876. // Order is important !
  114877. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  114878. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  114879. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  114880. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  114881. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  114882. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  114883. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  114884. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  114885. this._uniformBuffer.addUniform("pointSize", 1);
  114886. this._uniformBuffer.addUniform("shadowLevel", 1);
  114887. this._uniformBuffer.addUniform("alpha", 1);
  114888. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  114889. this._uniformBuffer.addUniform("vReflectionControl", 4);
  114890. this._uniformBuffer.create();
  114891. };
  114892. /**
  114893. * Unbind the material.
  114894. */
  114895. BackgroundMaterial.prototype.unbind = function () {
  114896. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  114897. this._uniformBuffer.setTexture("diffuseSampler", null);
  114898. }
  114899. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  114900. this._uniformBuffer.setTexture("reflectionSampler", null);
  114901. }
  114902. _super.prototype.unbind.call(this);
  114903. };
  114904. /**
  114905. * Bind only the world matrix to the material.
  114906. * @param world The world matrix to bind.
  114907. */
  114908. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  114909. this._activeEffect.setMatrix("world", world);
  114910. };
  114911. /**
  114912. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  114913. * @param world The world matrix to bind.
  114914. * @param subMesh The submesh to bind for.
  114915. */
  114916. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  114917. var scene = this.getScene();
  114918. var defines = subMesh._materialDefines;
  114919. if (!defines) {
  114920. return;
  114921. }
  114922. var effect = subMesh.effect;
  114923. if (!effect) {
  114924. return;
  114925. }
  114926. this._activeEffect = effect;
  114927. // Matrices
  114928. this.bindOnlyWorldMatrix(world);
  114929. // Bones
  114930. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  114931. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  114932. if (mustRebind) {
  114933. this._uniformBuffer.bindToEffect(effect, "Material");
  114934. this.bindViewProjection(effect);
  114935. var reflectionTexture = this._reflectionTexture;
  114936. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  114937. // Texture uniforms
  114938. if (scene.texturesEnabled) {
  114939. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114940. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  114941. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  114942. }
  114943. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114944. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  114945. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  114946. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  114947. }
  114948. }
  114949. if (this.shadowLevel > 0) {
  114950. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  114951. }
  114952. this._uniformBuffer.updateFloat("alpha", this.alpha);
  114953. // Point size
  114954. if (this.pointsCloud) {
  114955. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  114956. }
  114957. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  114958. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  114959. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  114960. }
  114961. else {
  114962. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  114963. }
  114964. }
  114965. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  114966. // Textures
  114967. if (scene.texturesEnabled) {
  114968. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  114969. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  114970. }
  114971. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  114972. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  114973. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  114974. }
  114975. else if (!defines.REFLECTIONBLUR) {
  114976. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  114977. }
  114978. else {
  114979. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  114980. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  114981. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  114982. }
  114983. if (defines.REFLECTIONFRESNEL) {
  114984. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  114985. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  114986. }
  114987. }
  114988. }
  114989. // Clip plane
  114990. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  114991. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  114992. }
  114993. if (mustRebind || !this.isFrozen) {
  114994. if (scene.lightsEnabled) {
  114995. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  114996. }
  114997. // View
  114998. this.bindView(effect);
  114999. // Fog
  115000. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect, true);
  115001. // image processing
  115002. if (this._imageProcessingConfiguration) {
  115003. this._imageProcessingConfiguration.bind(this._activeEffect);
  115004. }
  115005. }
  115006. this._uniformBuffer.update();
  115007. this._afterBind(mesh, this._activeEffect);
  115008. };
  115009. /**
  115010. * Dispose the material.
  115011. * @param forceDisposeEffect Force disposal of the associated effect.
  115012. * @param forceDisposeTextures Force disposal of the associated textures.
  115013. */
  115014. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  115015. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  115016. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  115017. if (forceDisposeTextures) {
  115018. if (this.diffuseTexture) {
  115019. this.diffuseTexture.dispose();
  115020. }
  115021. if (this.reflectionTexture) {
  115022. this.reflectionTexture.dispose();
  115023. }
  115024. }
  115025. this._renderTargets.dispose();
  115026. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  115027. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  115028. }
  115029. _super.prototype.dispose.call(this, forceDisposeEffect);
  115030. };
  115031. /**
  115032. * Clones the material.
  115033. * @param name The cloned name.
  115034. * @returns The cloned material.
  115035. */
  115036. BackgroundMaterial.prototype.clone = function (name) {
  115037. var _this = this;
  115038. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  115039. };
  115040. /**
  115041. * Serializes the current material to its JSON representation.
  115042. * @returns The JSON representation.
  115043. */
  115044. BackgroundMaterial.prototype.serialize = function () {
  115045. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  115046. serializationObject.customType = "BABYLON.BackgroundMaterial";
  115047. return serializationObject;
  115048. };
  115049. /**
  115050. * Gets the class name of the material
  115051. * @returns "BackgroundMaterial"
  115052. */
  115053. BackgroundMaterial.prototype.getClassName = function () {
  115054. return "BackgroundMaterial";
  115055. };
  115056. /**
  115057. * Parse a JSON input to create back a background material.
  115058. * @param source The JSON data to parse
  115059. * @param scene The scene to create the parsed material in
  115060. * @param rootUrl The root url of the assets the material depends upon
  115061. * @returns the instantiated BackgroundMaterial.
  115062. */
  115063. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  115064. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  115065. };
  115066. /**
  115067. * Standard reflectance value at parallel view angle.
  115068. */
  115069. BackgroundMaterial.StandardReflectance0 = 0.05;
  115070. /**
  115071. * Standard reflectance value at grazing angle.
  115072. */
  115073. BackgroundMaterial.StandardReflectance90 = 0.5;
  115074. __decorate([
  115075. BABYLON.serializeAsColor3()
  115076. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  115077. __decorate([
  115078. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115079. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  115080. __decorate([
  115081. BABYLON.serializeAsColor3()
  115082. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  115083. __decorate([
  115084. BABYLON.serialize()
  115085. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  115086. __decorate([
  115087. BABYLON.serialize()
  115088. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  115089. __decorate([
  115090. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  115091. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  115092. __decorate([
  115093. BABYLON.serializeAsTexture()
  115094. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  115095. __decorate([
  115096. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115097. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  115098. __decorate([
  115099. BABYLON.serialize()
  115100. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  115101. __decorate([
  115102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115103. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  115104. __decorate([
  115105. BABYLON.serializeAsTexture()
  115106. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  115107. __decorate([
  115108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115109. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  115110. __decorate([
  115111. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115112. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  115113. __decorate([
  115114. BABYLON.serialize()
  115115. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  115116. __decorate([
  115117. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115118. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  115119. __decorate([
  115120. BABYLON.serializeAsVector3()
  115121. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  115122. __decorate([
  115123. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115124. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  115125. __decorate([
  115126. BABYLON.serialize()
  115127. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  115128. __decorate([
  115129. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115130. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  115131. __decorate([
  115132. BABYLON.serialize()
  115133. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  115134. __decorate([
  115135. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115136. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  115137. __decorate([
  115138. BABYLON.serialize()
  115139. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  115140. __decorate([
  115141. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115142. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  115143. __decorate([
  115144. BABYLON.serialize()
  115145. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  115146. __decorate([
  115147. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115148. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  115149. __decorate([
  115150. BABYLON.serialize()
  115151. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  115152. __decorate([
  115153. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115154. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  115155. __decorate([
  115156. BABYLON.serialize()
  115157. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  115158. __decorate([
  115159. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115160. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  115161. __decorate([
  115162. BABYLON.serialize()
  115163. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  115164. __decorate([
  115165. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115166. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  115167. __decorate([
  115168. BABYLON.serialize()
  115169. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  115170. __decorate([
  115171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115172. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  115173. __decorate([
  115174. BABYLON.serialize()
  115175. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  115176. __decorate([
  115177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  115178. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  115179. __decorate([
  115180. BABYLON.serializeAsImageProcessingConfiguration()
  115181. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  115182. return BackgroundMaterial;
  115183. }(BABYLON.PushMaterial));
  115184. BABYLON.BackgroundMaterial = BackgroundMaterial;
  115185. })(BABYLON || (BABYLON = {}));
  115186. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  115187. var __assign = (this && this.__assign) || function () {
  115188. __assign = Object.assign || function(t) {
  115189. for (var s, i = 1, n = arguments.length; i < n; i++) {
  115190. s = arguments[i];
  115191. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  115192. t[p] = s[p];
  115193. }
  115194. return t;
  115195. };
  115196. return __assign.apply(this, arguments);
  115197. };
  115198. var BABYLON;
  115199. (function (BABYLON) {
  115200. /**
  115201. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  115202. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  115203. * It also helps with the default setup of your imageProcessing configuration.
  115204. */
  115205. var EnvironmentHelper = /** @class */ (function () {
  115206. /**
  115207. * constructor
  115208. * @param options
  115209. * @param scene The scene to add the material to
  115210. */
  115211. function EnvironmentHelper(options, scene) {
  115212. var _this = this;
  115213. this._errorHandler = function (message, exception) {
  115214. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  115215. };
  115216. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  115217. this._scene = scene;
  115218. this.onErrorObservable = new BABYLON.Observable();
  115219. this._setupBackground();
  115220. this._setupImageProcessing();
  115221. }
  115222. /**
  115223. * Creates the default options for the helper.
  115224. */
  115225. EnvironmentHelper._getDefaultOptions = function () {
  115226. return {
  115227. createGround: true,
  115228. groundSize: 15,
  115229. groundTexture: this._groundTextureCDNUrl,
  115230. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115231. groundOpacity: 0.9,
  115232. enableGroundShadow: true,
  115233. groundShadowLevel: 0.5,
  115234. enableGroundMirror: false,
  115235. groundMirrorSizeRatio: 0.3,
  115236. groundMirrorBlurKernel: 64,
  115237. groundMirrorAmount: 1,
  115238. groundMirrorFresnelWeight: 1,
  115239. groundMirrorFallOffDistance: 0,
  115240. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  115241. groundYBias: 0.00001,
  115242. createSkybox: true,
  115243. skyboxSize: 20,
  115244. skyboxTexture: this._skyboxTextureCDNUrl,
  115245. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  115246. backgroundYRotation: 0,
  115247. sizeAuto: true,
  115248. rootPosition: BABYLON.Vector3.Zero(),
  115249. setupImageProcessing: true,
  115250. environmentTexture: this._environmentTextureCDNUrl,
  115251. cameraExposure: 0.8,
  115252. cameraContrast: 1.2,
  115253. toneMappingEnabled: true,
  115254. };
  115255. };
  115256. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  115257. /**
  115258. * Gets the root mesh created by the helper.
  115259. */
  115260. get: function () {
  115261. return this._rootMesh;
  115262. },
  115263. enumerable: true,
  115264. configurable: true
  115265. });
  115266. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  115267. /**
  115268. * Gets the skybox created by the helper.
  115269. */
  115270. get: function () {
  115271. return this._skybox;
  115272. },
  115273. enumerable: true,
  115274. configurable: true
  115275. });
  115276. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  115277. /**
  115278. * Gets the skybox texture created by the helper.
  115279. */
  115280. get: function () {
  115281. return this._skyboxTexture;
  115282. },
  115283. enumerable: true,
  115284. configurable: true
  115285. });
  115286. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  115287. /**
  115288. * Gets the skybox material created by the helper.
  115289. */
  115290. get: function () {
  115291. return this._skyboxMaterial;
  115292. },
  115293. enumerable: true,
  115294. configurable: true
  115295. });
  115296. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  115297. /**
  115298. * Gets the ground mesh created by the helper.
  115299. */
  115300. get: function () {
  115301. return this._ground;
  115302. },
  115303. enumerable: true,
  115304. configurable: true
  115305. });
  115306. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  115307. /**
  115308. * Gets the ground texture created by the helper.
  115309. */
  115310. get: function () {
  115311. return this._groundTexture;
  115312. },
  115313. enumerable: true,
  115314. configurable: true
  115315. });
  115316. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  115317. /**
  115318. * Gets the ground mirror created by the helper.
  115319. */
  115320. get: function () {
  115321. return this._groundMirror;
  115322. },
  115323. enumerable: true,
  115324. configurable: true
  115325. });
  115326. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  115327. /**
  115328. * Gets the ground mirror render list to helps pushing the meshes
  115329. * you wish in the ground reflection.
  115330. */
  115331. get: function () {
  115332. if (this._groundMirror) {
  115333. return this._groundMirror.renderList;
  115334. }
  115335. return null;
  115336. },
  115337. enumerable: true,
  115338. configurable: true
  115339. });
  115340. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  115341. /**
  115342. * Gets the ground material created by the helper.
  115343. */
  115344. get: function () {
  115345. return this._groundMaterial;
  115346. },
  115347. enumerable: true,
  115348. configurable: true
  115349. });
  115350. /**
  115351. * Updates the background according to the new options
  115352. * @param options
  115353. */
  115354. EnvironmentHelper.prototype.updateOptions = function (options) {
  115355. var newOptions = __assign({}, this._options, options);
  115356. if (this._ground && !newOptions.createGround) {
  115357. this._ground.dispose();
  115358. this._ground = null;
  115359. }
  115360. if (this._groundMaterial && !newOptions.createGround) {
  115361. this._groundMaterial.dispose();
  115362. this._groundMaterial = null;
  115363. }
  115364. if (this._groundTexture) {
  115365. if (this._options.groundTexture != newOptions.groundTexture) {
  115366. this._groundTexture.dispose();
  115367. this._groundTexture = null;
  115368. }
  115369. }
  115370. if (this._skybox && !newOptions.createSkybox) {
  115371. this._skybox.dispose();
  115372. this._skybox = null;
  115373. }
  115374. if (this._skyboxMaterial && !newOptions.createSkybox) {
  115375. this._skyboxMaterial.dispose();
  115376. this._skyboxMaterial = null;
  115377. }
  115378. if (this._skyboxTexture) {
  115379. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  115380. this._skyboxTexture.dispose();
  115381. this._skyboxTexture = null;
  115382. }
  115383. }
  115384. if (this._groundMirror && !newOptions.enableGroundMirror) {
  115385. this._groundMirror.dispose();
  115386. this._groundMirror = null;
  115387. }
  115388. if (this._scene.environmentTexture) {
  115389. if (this._options.environmentTexture != newOptions.environmentTexture) {
  115390. this._scene.environmentTexture.dispose();
  115391. }
  115392. }
  115393. this._options = newOptions;
  115394. this._setupBackground();
  115395. this._setupImageProcessing();
  115396. };
  115397. /**
  115398. * Sets the primary color of all the available elements.
  115399. * @param color the main color to affect to the ground and the background
  115400. */
  115401. EnvironmentHelper.prototype.setMainColor = function (color) {
  115402. if (this.groundMaterial) {
  115403. this.groundMaterial.primaryColor = color;
  115404. }
  115405. if (this.skyboxMaterial) {
  115406. this.skyboxMaterial.primaryColor = color;
  115407. }
  115408. if (this.groundMirror) {
  115409. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  115410. }
  115411. };
  115412. /**
  115413. * Setup the image processing according to the specified options.
  115414. */
  115415. EnvironmentHelper.prototype._setupImageProcessing = function () {
  115416. if (this._options.setupImageProcessing) {
  115417. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  115418. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  115419. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  115420. this._setupEnvironmentTexture();
  115421. }
  115422. };
  115423. /**
  115424. * Setup the environment texture according to the specified options.
  115425. */
  115426. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  115427. if (this._scene.environmentTexture) {
  115428. return;
  115429. }
  115430. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  115431. this._scene.environmentTexture = this._options.environmentTexture;
  115432. return;
  115433. }
  115434. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  115435. this._scene.environmentTexture = environmentTexture;
  115436. };
  115437. /**
  115438. * Setup the background according to the specified options.
  115439. */
  115440. EnvironmentHelper.prototype._setupBackground = function () {
  115441. if (!this._rootMesh) {
  115442. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  115443. }
  115444. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  115445. var sceneSize = this._getSceneSize();
  115446. if (this._options.createGround) {
  115447. this._setupGround(sceneSize);
  115448. this._setupGroundMaterial();
  115449. this._setupGroundDiffuseTexture();
  115450. if (this._options.enableGroundMirror) {
  115451. this._setupGroundMirrorTexture(sceneSize);
  115452. }
  115453. this._setupMirrorInGroundMaterial();
  115454. }
  115455. if (this._options.createSkybox) {
  115456. this._setupSkybox(sceneSize);
  115457. this._setupSkyboxMaterial();
  115458. this._setupSkyboxReflectionTexture();
  115459. }
  115460. this._rootMesh.position.x = sceneSize.rootPosition.x;
  115461. this._rootMesh.position.z = sceneSize.rootPosition.z;
  115462. this._rootMesh.position.y = sceneSize.rootPosition.y;
  115463. };
  115464. /**
  115465. * Get the scene sizes according to the setup.
  115466. */
  115467. EnvironmentHelper.prototype._getSceneSize = function () {
  115468. var _this = this;
  115469. var groundSize = this._options.groundSize;
  115470. var skyboxSize = this._options.skyboxSize;
  115471. var rootPosition = this._options.rootPosition;
  115472. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  115473. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115474. }
  115475. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  115476. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  115477. });
  115478. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  115479. if (this._options.sizeAuto) {
  115480. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  115481. this._scene.activeCamera.upperRadiusLimit) {
  115482. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  115483. skyboxSize = groundSize;
  115484. }
  115485. var sceneDiagonalLenght = sceneDiagonal.length();
  115486. if (sceneDiagonalLenght > groundSize) {
  115487. groundSize = sceneDiagonalLenght * 2;
  115488. skyboxSize = groundSize;
  115489. }
  115490. // 10 % bigger.
  115491. groundSize *= 1.1;
  115492. skyboxSize *= 1.5;
  115493. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  115494. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  115495. }
  115496. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  115497. };
  115498. /**
  115499. * Setup the ground according to the specified options.
  115500. */
  115501. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  115502. var _this = this;
  115503. if (!this._ground || this._ground.isDisposed()) {
  115504. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  115505. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  115506. this._ground.parent = this._rootMesh;
  115507. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  115508. }
  115509. this._ground.receiveShadows = this._options.enableGroundShadow;
  115510. };
  115511. /**
  115512. * Setup the ground material according to the specified options.
  115513. */
  115514. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  115515. if (!this._groundMaterial) {
  115516. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  115517. }
  115518. this._groundMaterial.alpha = this._options.groundOpacity;
  115519. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  115520. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  115521. this._groundMaterial.primaryColor = this._options.groundColor;
  115522. this._groundMaterial.useRGBColor = false;
  115523. this._groundMaterial.enableNoise = true;
  115524. if (this._ground) {
  115525. this._ground.material = this._groundMaterial;
  115526. }
  115527. };
  115528. /**
  115529. * Setup the ground diffuse texture according to the specified options.
  115530. */
  115531. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  115532. if (!this._groundMaterial) {
  115533. return;
  115534. }
  115535. if (this._groundTexture) {
  115536. return;
  115537. }
  115538. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  115539. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  115540. return;
  115541. }
  115542. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115543. diffuseTexture.gammaSpace = false;
  115544. diffuseTexture.hasAlpha = true;
  115545. this._groundMaterial.diffuseTexture = diffuseTexture;
  115546. };
  115547. /**
  115548. * Setup the ground mirror texture according to the specified options.
  115549. */
  115550. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  115551. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115552. if (!this._groundMirror) {
  115553. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  115554. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  115555. this._groundMirror.anisotropicFilteringLevel = 1;
  115556. this._groundMirror.wrapU = wrapping;
  115557. this._groundMirror.wrapV = wrapping;
  115558. this._groundMirror.gammaSpace = false;
  115559. if (this._groundMirror.renderList) {
  115560. for (var i = 0; i < this._scene.meshes.length; i++) {
  115561. var mesh = this._scene.meshes[i];
  115562. if (mesh !== this._ground &&
  115563. mesh !== this._skybox &&
  115564. mesh !== this._rootMesh) {
  115565. this._groundMirror.renderList.push(mesh);
  115566. }
  115567. }
  115568. }
  115569. }
  115570. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  115571. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  115572. };
  115573. /**
  115574. * Setup the ground to receive the mirror texture.
  115575. */
  115576. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  115577. if (this._groundMaterial) {
  115578. this._groundMaterial.reflectionTexture = this._groundMirror;
  115579. this._groundMaterial.reflectionFresnel = true;
  115580. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  115581. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  115582. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  115583. }
  115584. };
  115585. /**
  115586. * Setup the skybox according to the specified options.
  115587. */
  115588. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  115589. var _this = this;
  115590. if (!this._skybox || this._skybox.isDisposed()) {
  115591. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  115592. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  115593. }
  115594. this._skybox.parent = this._rootMesh;
  115595. };
  115596. /**
  115597. * Setup the skybox material according to the specified options.
  115598. */
  115599. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  115600. if (!this._skybox) {
  115601. return;
  115602. }
  115603. if (!this._skyboxMaterial) {
  115604. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  115605. }
  115606. this._skyboxMaterial.useRGBColor = false;
  115607. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  115608. this._skyboxMaterial.enableNoise = true;
  115609. this._skybox.material = this._skyboxMaterial;
  115610. };
  115611. /**
  115612. * Setup the skybox reflection texture according to the specified options.
  115613. */
  115614. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  115615. if (!this._skyboxMaterial) {
  115616. return;
  115617. }
  115618. if (this._skyboxTexture) {
  115619. return;
  115620. }
  115621. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  115622. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  115623. return;
  115624. }
  115625. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  115626. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  115627. this._skyboxTexture.gammaSpace = false;
  115628. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  115629. };
  115630. /**
  115631. * Dispose all the elements created by the Helper.
  115632. */
  115633. EnvironmentHelper.prototype.dispose = function () {
  115634. if (this._groundMaterial) {
  115635. this._groundMaterial.dispose(true, true);
  115636. }
  115637. if (this._skyboxMaterial) {
  115638. this._skyboxMaterial.dispose(true, true);
  115639. }
  115640. this._rootMesh.dispose(false);
  115641. };
  115642. /**
  115643. * Default ground texture URL.
  115644. */
  115645. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  115646. /**
  115647. * Default skybox texture URL.
  115648. */
  115649. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  115650. /**
  115651. * Default environment texture URL.
  115652. */
  115653. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  115654. return EnvironmentHelper;
  115655. }());
  115656. BABYLON.EnvironmentHelper = EnvironmentHelper;
  115657. })(BABYLON || (BABYLON = {}));
  115658. //# sourceMappingURL=babylon.environmentHelper.js.map
  115659. var BABYLON;
  115660. (function (BABYLON) {
  115661. /** Internal class used to store shapes for emitters */
  115662. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  115663. function ParticleSystemSetEmitterCreationOptions() {
  115664. }
  115665. return ParticleSystemSetEmitterCreationOptions;
  115666. }());
  115667. /**
  115668. * Represents a set of particle systems working together to create a specific effect
  115669. */
  115670. var ParticleSystemSet = /** @class */ (function () {
  115671. function ParticleSystemSet() {
  115672. /**
  115673. * Gets the particle system list
  115674. */
  115675. this.systems = new Array();
  115676. }
  115677. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  115678. /**
  115679. * Gets the emitter node used with this set
  115680. */
  115681. get: function () {
  115682. return this._emitterNode;
  115683. },
  115684. enumerable: true,
  115685. configurable: true
  115686. });
  115687. /**
  115688. * Creates a new emitter mesh as a sphere
  115689. * @param options defines the options used to create the sphere
  115690. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  115691. * @param scene defines the hosting scene
  115692. */
  115693. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  115694. if (this._emitterNode) {
  115695. this._emitterNode.dispose();
  115696. }
  115697. this._emitterCreationOptions = {
  115698. kind: "Sphere",
  115699. options: options,
  115700. renderingGroupId: renderingGroupId
  115701. };
  115702. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  115703. emitterMesh.renderingGroupId = renderingGroupId;
  115704. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  115705. material.emissiveColor = options.color;
  115706. emitterMesh.material = material;
  115707. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115708. var system = _a[_i];
  115709. system.emitter = emitterMesh;
  115710. }
  115711. this._emitterNode = emitterMesh;
  115712. };
  115713. /**
  115714. * Starts all particle systems of the set
  115715. * @param emitter defines an optional mesh to use as emitter for the particle systems
  115716. */
  115717. ParticleSystemSet.prototype.start = function (emitter) {
  115718. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115719. var system = _a[_i];
  115720. if (emitter) {
  115721. system.emitter = emitter;
  115722. }
  115723. system.start();
  115724. }
  115725. };
  115726. /**
  115727. * Release all associated resources
  115728. */
  115729. ParticleSystemSet.prototype.dispose = function () {
  115730. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115731. var system = _a[_i];
  115732. system.dispose();
  115733. }
  115734. this.systems = [];
  115735. if (this._emitterNode) {
  115736. this._emitterNode.dispose();
  115737. this._emitterNode = null;
  115738. }
  115739. };
  115740. /**
  115741. * Serialize the set into a JSON compatible object
  115742. * @returns a JSON compatible representation of the set
  115743. */
  115744. ParticleSystemSet.prototype.serialize = function () {
  115745. var result = {};
  115746. result.systems = [];
  115747. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  115748. var system = _a[_i];
  115749. result.systems.push(system.serialize());
  115750. }
  115751. if (this._emitterNode) {
  115752. result.emitter = this._emitterCreationOptions;
  115753. }
  115754. return result;
  115755. };
  115756. /**
  115757. * Parse a new ParticleSystemSet from a serialized source
  115758. * @param data defines a JSON compatible representation of the set
  115759. * @param scene defines the hosting scene
  115760. * @param gpu defines if we want GPU particles or CPU particles
  115761. * @returns a new ParticleSystemSet
  115762. */
  115763. ParticleSystemSet.Parse = function (data, scene, gpu) {
  115764. if (gpu === void 0) { gpu = false; }
  115765. var result = new ParticleSystemSet();
  115766. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  115767. scene = scene || BABYLON.Engine.LastCreatedScene;
  115768. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  115769. var system = _a[_i];
  115770. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl, true) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl, true));
  115771. }
  115772. if (data.emitter) {
  115773. var options = data.emitter.options;
  115774. switch (data.emitter.kind) {
  115775. case "Sphere":
  115776. result.setEmitterAsSphere({
  115777. diameter: options.diameter,
  115778. segments: options.segments,
  115779. color: BABYLON.Color3.FromArray(options.color)
  115780. }, data.emitter.renderingGroupId, scene);
  115781. break;
  115782. }
  115783. }
  115784. return result;
  115785. };
  115786. return ParticleSystemSet;
  115787. }());
  115788. BABYLON.ParticleSystemSet = ParticleSystemSet;
  115789. })(BABYLON || (BABYLON = {}));
  115790. //# sourceMappingURL=babylon.particleSystemSet.js.map
  115791. var BABYLON;
  115792. (function (BABYLON) {
  115793. /**
  115794. * This class is made for on one-liner static method to help creating particle system set.
  115795. */
  115796. var ParticleHelper = /** @class */ (function () {
  115797. function ParticleHelper() {
  115798. }
  115799. /**
  115800. * Create a default particle system that you can tweak
  115801. * @param emitter defines the emitter to use
  115802. * @param capacity defines the system capacity (default is 500 particles)
  115803. * @param scene defines the hosting scene
  115804. * @param useGPU defines if a GPUParticleSystem must be created (default is false)
  115805. * @returns the new Particle system
  115806. */
  115807. ParticleHelper.CreateDefault = function (emitter, capacity, scene, useGPU) {
  115808. if (capacity === void 0) { capacity = 500; }
  115809. if (useGPU === void 0) { useGPU = false; }
  115810. var system;
  115811. if (useGPU) {
  115812. system = new BABYLON.GPUParticleSystem("default system", { capacity: capacity }, scene);
  115813. }
  115814. else {
  115815. system = new BABYLON.ParticleSystem("default system", capacity, scene);
  115816. }
  115817. system.emitter = emitter;
  115818. system.particleTexture = new BABYLON.Texture("https://www.babylonjs.com/assets/Flare.png", system.getScene());
  115819. system.createConeEmitter(0.1, Math.PI / 4);
  115820. // Particle color
  115821. system.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  115822. system.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  115823. system.colorDead = new BABYLON.Color4(1.0, 1.0, 1.0, 0.0);
  115824. // Particle Size
  115825. system.minSize = 0.1;
  115826. system.maxSize = 0.1;
  115827. // Emission speed
  115828. system.minEmitPower = 2;
  115829. system.maxEmitPower = 2;
  115830. // Update speed
  115831. system.updateSpeed = 1 / 60;
  115832. system.emitRate = 30;
  115833. return system;
  115834. };
  115835. /**
  115836. * This is the main static method (one-liner) of this helper to create different particle systems
  115837. * @param type This string represents the type to the particle system to create
  115838. * @param scene The scene where the particle system should live
  115839. * @param gpu If the system will use gpu
  115840. * @returns the ParticleSystemSet created
  115841. */
  115842. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  115843. if (gpu === void 0) { gpu = false; }
  115844. if (!scene) {
  115845. scene = BABYLON.Engine.LastCreatedScene;
  115846. ;
  115847. }
  115848. var token = {};
  115849. scene._addPendingData(token);
  115850. return new Promise(function (resolve, reject) {
  115851. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  115852. scene._removePendingData(token);
  115853. return reject("Particle system with GPU is not supported.");
  115854. }
  115855. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  115856. scene._removePendingData(token);
  115857. var newData = JSON.parse(data.toString());
  115858. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  115859. }, undefined, undefined, undefined, function (req, exception) {
  115860. scene._removePendingData(token);
  115861. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  115862. });
  115863. });
  115864. };
  115865. /**
  115866. * Static function used to export a particle system to a ParticleSystemSet variable.
  115867. * Please note that the emitter shape is not exported
  115868. * @param systems defines the particle systems to export
  115869. * @returns the created particle system set
  115870. */
  115871. ParticleHelper.ExportSet = function (systems) {
  115872. var set = new BABYLON.ParticleSystemSet();
  115873. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  115874. var system = systems_1[_i];
  115875. set.systems.push(system);
  115876. }
  115877. return set;
  115878. };
  115879. /**
  115880. * Gets or sets base Assets URL
  115881. */
  115882. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  115883. return ParticleHelper;
  115884. }());
  115885. BABYLON.ParticleHelper = ParticleHelper;
  115886. })(BABYLON || (BABYLON = {}));
  115887. //# sourceMappingURL=babylon.particleHelper.js.map
  115888. var BABYLON;
  115889. (function (BABYLON) {
  115890. /**
  115891. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  115892. * As a subclass of TransformNode, this allow parenting to the camera or multiple videos with different locations in the scene.
  115893. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  115894. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  115895. */
  115896. var VideoDome = /** @class */ (function (_super) {
  115897. __extends(VideoDome, _super);
  115898. /**
  115899. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  115900. * @param name Element's name, child elements will append suffixes for their own names.
  115901. * @param urlsOrVideo defines the url(s) or the video element to use
  115902. * @param options An object containing optional or exposed sub element properties
  115903. */
  115904. function VideoDome(name, urlsOrVideo, options, scene) {
  115905. var _this = _super.call(this, name, scene) || this;
  115906. _this._useDirectMapping = false;
  115907. // set defaults and manage values
  115908. name = name || "videoDome";
  115909. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  115910. options.clickToPlay = Boolean(options.clickToPlay);
  115911. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  115912. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  115913. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  115914. if (options.useDirectMapping === undefined) {
  115915. _this._useDirectMapping = true;
  115916. }
  115917. else {
  115918. _this._useDirectMapping = options.useDirectMapping;
  115919. }
  115920. _this._setReady(false);
  115921. // create
  115922. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  115923. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  115924. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  115925. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  115926. texture.onLoadObservable.addOnce(function () {
  115927. _this._setReady(true);
  115928. });
  115929. // configure material
  115930. material.useEquirectangularFOV = true;
  115931. material.fovMultiplier = 1.0;
  115932. material.opacityFresnel = false;
  115933. if (_this._useDirectMapping) {
  115934. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115935. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115936. material.diffuseTexture = texture;
  115937. }
  115938. else {
  115939. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  115940. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  115941. material.reflectionTexture = texture;
  115942. }
  115943. // configure mesh
  115944. _this._mesh.material = material;
  115945. _this._mesh.parent = _this;
  115946. // optional configuration
  115947. if (options.clickToPlay) {
  115948. scene.onPointerUp = function () {
  115949. _this._videoTexture.video.play();
  115950. };
  115951. }
  115952. return _this;
  115953. }
  115954. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  115955. /**
  115956. * Gets the video texture being displayed on the sphere
  115957. */
  115958. get: function () {
  115959. return this._videoTexture;
  115960. },
  115961. enumerable: true,
  115962. configurable: true
  115963. });
  115964. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  115965. /**
  115966. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  115967. * Also see the options.resolution property.
  115968. */
  115969. get: function () {
  115970. return this._material.fovMultiplier;
  115971. },
  115972. set: function (value) {
  115973. this._material.fovMultiplier = value;
  115974. },
  115975. enumerable: true,
  115976. configurable: true
  115977. });
  115978. /**
  115979. * Releases resources associated with this node.
  115980. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  115981. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  115982. */
  115983. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  115984. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  115985. this._videoTexture.dispose();
  115986. this._mesh.dispose();
  115987. this._material.dispose();
  115988. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  115989. };
  115990. return VideoDome;
  115991. }(BABYLON.TransformNode));
  115992. BABYLON.VideoDome = VideoDome;
  115993. })(BABYLON || (BABYLON = {}));
  115994. //# sourceMappingURL=babylon.videoDome.js.map
  115995. var BABYLON;
  115996. (function (BABYLON) {
  115997. /**
  115998. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  115999. * As a subclass of TransformNode, this allow parenting to the camera with different locations in the scene.
  116000. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  116001. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  116002. */
  116003. var PhotoDome = /** @class */ (function (_super) {
  116004. __extends(PhotoDome, _super);
  116005. /**
  116006. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  116007. * @param name Element's name, child elements will append suffixes for their own names.
  116008. * @param urlsOfPhoto defines the url of the photo to display
  116009. * @param options defines an object containing optional or exposed sub element properties
  116010. * @param onError defines a callback called when an error occured while loading the texture
  116011. */
  116012. function PhotoDome(name, urlOfPhoto, options, scene, onError) {
  116013. if (onError === void 0) { onError = null; }
  116014. var _this = _super.call(this, name, scene) || this;
  116015. _this._useDirectMapping = false;
  116016. /**
  116017. * Observable raised when an error occured while loading the 360 image
  116018. */
  116019. _this.onLoadErrorObservable = new BABYLON.Observable();
  116020. // set defaults and manage values
  116021. name = name || "photoDome";
  116022. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  116023. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  116024. if (options.useDirectMapping === undefined) {
  116025. _this._useDirectMapping = true;
  116026. }
  116027. else {
  116028. _this._useDirectMapping = options.useDirectMapping;
  116029. }
  116030. _this._setReady(false);
  116031. // create
  116032. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  116033. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  116034. // configure material
  116035. material.opacityFresnel = false;
  116036. material.useEquirectangularFOV = true;
  116037. material.fovMultiplier = 1.0;
  116038. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping, undefined, undefined, function (message, exception) {
  116039. _this.onLoadErrorObservable.notifyObservers(message || "Unknown error occured");
  116040. if (onError) {
  116041. onError(message, exception);
  116042. }
  116043. });
  116044. _this.photoTexture.onLoadObservable.addOnce(function () {
  116045. _this._setReady(true);
  116046. });
  116047. // configure mesh
  116048. _this._mesh.material = material;
  116049. _this._mesh.parent = _this;
  116050. return _this;
  116051. }
  116052. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  116053. /**
  116054. * Gets or sets the texture being displayed on the sphere
  116055. */
  116056. get: function () {
  116057. return this._photoTexture;
  116058. },
  116059. set: function (value) {
  116060. if (this._photoTexture === value) {
  116061. return;
  116062. }
  116063. this._photoTexture = value;
  116064. if (this._useDirectMapping) {
  116065. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116066. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116067. this._material.diffuseTexture = this._photoTexture;
  116068. }
  116069. else {
  116070. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  116071. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  116072. this._material.reflectionTexture = this._photoTexture;
  116073. }
  116074. },
  116075. enumerable: true,
  116076. configurable: true
  116077. });
  116078. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  116079. /**
  116080. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  116081. * Also see the options.resolution property.
  116082. */
  116083. get: function () {
  116084. return this._material.fovMultiplier;
  116085. },
  116086. set: function (value) {
  116087. this._material.fovMultiplier = value;
  116088. },
  116089. enumerable: true,
  116090. configurable: true
  116091. });
  116092. /**
  116093. * Releases resources associated with this node.
  116094. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  116095. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  116096. */
  116097. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  116098. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  116099. this._photoTexture.dispose();
  116100. this._mesh.dispose();
  116101. this._material.dispose();
  116102. this.onLoadErrorObservable.clear();
  116103. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  116104. };
  116105. return PhotoDome;
  116106. }(BABYLON.TransformNode));
  116107. BABYLON.PhotoDome = PhotoDome;
  116108. })(BABYLON || (BABYLON = {}));
  116109. //# sourceMappingURL=babylon.photoDome.js.map
  116110. var BABYLON;
  116111. (function (BABYLON) {
  116112. /** @hidden */
  116113. var _OcclusionDataStorage = /** @class */ (function () {
  116114. function _OcclusionDataStorage() {
  116115. /** @hidden */
  116116. this.occlusionInternalRetryCounter = 0;
  116117. /** @hidden */
  116118. this.isOcclusionQueryInProgress = false;
  116119. /** @hidden */
  116120. this.isOccluded = false;
  116121. /** @hidden */
  116122. this.occlusionRetryCount = -1;
  116123. /** @hidden */
  116124. this.occlusionType = BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE;
  116125. /** @hidden */
  116126. this.occlusionQueryAlgorithmType = BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  116127. }
  116128. return _OcclusionDataStorage;
  116129. }());
  116130. BABYLON.Engine.prototype.createQuery = function () {
  116131. return this._gl.createQuery();
  116132. };
  116133. BABYLON.Engine.prototype.deleteQuery = function (query) {
  116134. this._gl.deleteQuery(query);
  116135. return this;
  116136. };
  116137. BABYLON.Engine.prototype.isQueryResultAvailable = function (query) {
  116138. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  116139. };
  116140. BABYLON.Engine.prototype.getQueryResult = function (query) {
  116141. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  116142. };
  116143. BABYLON.Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  116144. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116145. this._gl.beginQuery(glAlgorithm, query);
  116146. return this;
  116147. };
  116148. BABYLON.Engine.prototype.endOcclusionQuery = function (algorithmType) {
  116149. var glAlgorithm = this._getGlAlgorithmType(algorithmType);
  116150. this._gl.endQuery(glAlgorithm);
  116151. return this;
  116152. };
  116153. BABYLON.Engine.prototype._createTimeQuery = function () {
  116154. var timerQuery = this.getCaps().timerQuery;
  116155. if (timerQuery.createQueryEXT) {
  116156. return timerQuery.createQueryEXT();
  116157. }
  116158. return this.createQuery();
  116159. };
  116160. BABYLON.Engine.prototype._deleteTimeQuery = function (query) {
  116161. var timerQuery = this.getCaps().timerQuery;
  116162. if (timerQuery.deleteQueryEXT) {
  116163. timerQuery.deleteQueryEXT(query);
  116164. return;
  116165. }
  116166. this.deleteQuery(query);
  116167. };
  116168. BABYLON.Engine.prototype._getTimeQueryResult = function (query) {
  116169. var timerQuery = this.getCaps().timerQuery;
  116170. if (timerQuery.getQueryObjectEXT) {
  116171. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  116172. }
  116173. return this.getQueryResult(query);
  116174. };
  116175. BABYLON.Engine.prototype._getTimeQueryAvailability = function (query) {
  116176. var timerQuery = this.getCaps().timerQuery;
  116177. if (timerQuery.getQueryObjectEXT) {
  116178. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  116179. }
  116180. return this.isQueryResultAvailable(query);
  116181. };
  116182. BABYLON.Engine.prototype.startTimeQuery = function () {
  116183. var caps = this.getCaps();
  116184. var timerQuery = caps.timerQuery;
  116185. if (!timerQuery) {
  116186. return null;
  116187. }
  116188. var token = new BABYLON._TimeToken();
  116189. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116190. if (caps.canUseTimestampForTimerQuery) {
  116191. token._startTimeQuery = this._createTimeQuery();
  116192. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  116193. }
  116194. else {
  116195. if (this._currentNonTimestampToken) {
  116196. return this._currentNonTimestampToken;
  116197. }
  116198. token._timeElapsedQuery = this._createTimeQuery();
  116199. if (timerQuery.beginQueryEXT) {
  116200. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116201. }
  116202. else {
  116203. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  116204. }
  116205. this._currentNonTimestampToken = token;
  116206. }
  116207. return token;
  116208. };
  116209. BABYLON.Engine.prototype.endTimeQuery = function (token) {
  116210. var caps = this.getCaps();
  116211. var timerQuery = caps.timerQuery;
  116212. if (!timerQuery || !token) {
  116213. return -1;
  116214. }
  116215. if (caps.canUseTimestampForTimerQuery) {
  116216. if (!token._startTimeQuery) {
  116217. return -1;
  116218. }
  116219. if (!token._endTimeQuery) {
  116220. token._endTimeQuery = this._createTimeQuery();
  116221. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  116222. }
  116223. }
  116224. else if (!token._timeElapsedQueryEnded) {
  116225. if (!token._timeElapsedQuery) {
  116226. return -1;
  116227. }
  116228. if (timerQuery.endQueryEXT) {
  116229. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  116230. }
  116231. else {
  116232. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  116233. }
  116234. token._timeElapsedQueryEnded = true;
  116235. }
  116236. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  116237. var available = false;
  116238. if (token._endTimeQuery) {
  116239. available = this._getTimeQueryAvailability(token._endTimeQuery);
  116240. }
  116241. else if (token._timeElapsedQuery) {
  116242. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  116243. }
  116244. if (available && !disjoint) {
  116245. var result = 0;
  116246. if (caps.canUseTimestampForTimerQuery) {
  116247. if (!token._startTimeQuery || !token._endTimeQuery) {
  116248. return -1;
  116249. }
  116250. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  116251. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  116252. result = timeEnd - timeStart;
  116253. this._deleteTimeQuery(token._startTimeQuery);
  116254. this._deleteTimeQuery(token._endTimeQuery);
  116255. token._startTimeQuery = null;
  116256. token._endTimeQuery = null;
  116257. }
  116258. else {
  116259. if (!token._timeElapsedQuery) {
  116260. return -1;
  116261. }
  116262. result = this._getTimeQueryResult(token._timeElapsedQuery);
  116263. this._deleteTimeQuery(token._timeElapsedQuery);
  116264. token._timeElapsedQuery = null;
  116265. token._timeElapsedQueryEnded = false;
  116266. this._currentNonTimestampToken = null;
  116267. }
  116268. return result;
  116269. }
  116270. return -1;
  116271. };
  116272. BABYLON.Engine.prototype._getGlAlgorithmType = function (algorithmType) {
  116273. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  116274. };
  116275. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  116276. get: function () {
  116277. return this._occlusionDataStorage.isOcclusionQueryInProgress;
  116278. },
  116279. enumerable: false,
  116280. configurable: true
  116281. });
  116282. Object.defineProperty(BABYLON.AbstractMesh.prototype, "_occlusionDataStorage", {
  116283. get: function () {
  116284. if (!this.__occlusionDataStorage) {
  116285. this.__occlusionDataStorage = new _OcclusionDataStorage();
  116286. }
  116287. return this.__occlusionDataStorage;
  116288. },
  116289. enumerable: false,
  116290. configurable: true
  116291. });
  116292. Object.defineProperty(BABYLON.AbstractMesh.prototype, "isOccluded", {
  116293. get: function () {
  116294. return this._occlusionDataStorage.isOccluded;
  116295. },
  116296. set: function (value) {
  116297. this._occlusionDataStorage.isOccluded = value;
  116298. },
  116299. enumerable: true,
  116300. configurable: true
  116301. });
  116302. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionQueryAlgorithmType", {
  116303. get: function () {
  116304. return this._occlusionDataStorage.occlusionQueryAlgorithmType;
  116305. },
  116306. set: function (value) {
  116307. this._occlusionDataStorage.occlusionQueryAlgorithmType = value;
  116308. },
  116309. enumerable: true,
  116310. configurable: true
  116311. });
  116312. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionType", {
  116313. get: function () {
  116314. return this._occlusionDataStorage.occlusionType;
  116315. },
  116316. set: function (value) {
  116317. this._occlusionDataStorage.occlusionType = value;
  116318. },
  116319. enumerable: true,
  116320. configurable: true
  116321. });
  116322. Object.defineProperty(BABYLON.AbstractMesh.prototype, "occlusionRetryCount", {
  116323. get: function () {
  116324. return this._occlusionDataStorage.occlusionRetryCount;
  116325. },
  116326. set: function (value) {
  116327. this._occlusionDataStorage.occlusionRetryCount = value;
  116328. },
  116329. enumerable: true,
  116330. configurable: true
  116331. });
  116332. // We also need to update AbstractMesh as there is a portion of the code there
  116333. BABYLON.AbstractMesh.prototype._checkOcclusionQuery = function () {
  116334. var dataStorage = this._occlusionDataStorage;
  116335. if (dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_NONE) {
  116336. dataStorage.isOccluded = false;
  116337. return false;
  116338. }
  116339. var engine = this.getEngine();
  116340. if (engine.webGLVersion < 2) {
  116341. dataStorage.isOccluded = false;
  116342. return false;
  116343. }
  116344. if (!engine.isQueryResultAvailable) { // Occlusion query where not referenced
  116345. dataStorage.isOccluded = false;
  116346. return false;
  116347. }
  116348. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  116349. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  116350. if (isOcclusionQueryAvailable) {
  116351. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  116352. dataStorage.isOcclusionQueryInProgress = false;
  116353. dataStorage.occlusionInternalRetryCounter = 0;
  116354. dataStorage.isOccluded = occlusionQueryResult === 1 ? false : true;
  116355. }
  116356. else {
  116357. dataStorage.occlusionInternalRetryCounter++;
  116358. if (dataStorage.occlusionRetryCount !== -1 && dataStorage.occlusionInternalRetryCounter > dataStorage.occlusionRetryCount) {
  116359. dataStorage.isOcclusionQueryInProgress = false;
  116360. dataStorage.occlusionInternalRetryCounter = 0;
  116361. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  116362. // if strict continue the last state of the object.
  116363. dataStorage.isOccluded = dataStorage.occlusionType === BABYLON.AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : dataStorage.isOccluded;
  116364. }
  116365. else {
  116366. return false;
  116367. }
  116368. }
  116369. }
  116370. var scene = this.getScene();
  116371. if (scene.getBoundingBoxRenderer) {
  116372. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  116373. if (!this._occlusionQuery) {
  116374. this._occlusionQuery = engine.createQuery();
  116375. }
  116376. engine.beginOcclusionQuery(dataStorage.occlusionQueryAlgorithmType, this._occlusionQuery);
  116377. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  116378. engine.endOcclusionQuery(dataStorage.occlusionQueryAlgorithmType);
  116379. this._occlusionDataStorage.isOcclusionQueryInProgress = true;
  116380. }
  116381. return dataStorage.isOccluded;
  116382. };
  116383. })(BABYLON || (BABYLON = {}));
  116384. //# sourceMappingURL=babylon.engine.occlusionQuery.js.map
  116385. var BABYLON;
  116386. (function (BABYLON) {
  116387. /**
  116388. * Class used to generate noise procedural textures
  116389. */
  116390. var NoiseProceduralTexture = /** @class */ (function (_super) {
  116391. __extends(NoiseProceduralTexture, _super);
  116392. /**
  116393. * Creates a new NoiseProceduralTexture
  116394. * @param name defines the name fo the texture
  116395. * @param size defines the size of the texture (default is 256)
  116396. * @param scene defines the hosting scene
  116397. * @param fallbackTexture defines the texture to use if the NoiseProceduralTexture can't be created
  116398. * @param generateMipMaps defines if mipmaps must be generated (true by default)
  116399. */
  116400. function NoiseProceduralTexture(name, size, scene, fallbackTexture, generateMipMaps) {
  116401. if (size === void 0) { size = 256; }
  116402. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  116403. var _this = _super.call(this, name, size, "noise", scene, fallbackTexture, generateMipMaps) || this;
  116404. _this._time = 0;
  116405. /** Gets or sets a value between 0 and 1 indicating the overall brightness of the texture (default is 0.2) */
  116406. _this.brightness = 0.2;
  116407. /** Defines the number of octaves to process */
  116408. _this.octaves = 3;
  116409. /** Defines the level of persistence (0.8 by default) */
  116410. _this.persistence = 0.8;
  116411. /** Gets or sets animation speed factor (default is 1) */
  116412. _this.animationSpeedFactor = 1;
  116413. _this._updateShaderUniforms();
  116414. return _this;
  116415. }
  116416. NoiseProceduralTexture.prototype._updateShaderUniforms = function () {
  116417. var scene = this.getScene();
  116418. if (!scene) {
  116419. return;
  116420. }
  116421. this._time += scene.getAnimationRatio() * this.animationSpeedFactor * 0.01;
  116422. this.setFloat("brightness", this.brightness);
  116423. this.setFloat("persistence", this.persistence);
  116424. this.setFloat("timeScale", this._time);
  116425. };
  116426. NoiseProceduralTexture.prototype._getDefines = function () {
  116427. return "#define OCTAVES " + (this.octaves | 0);
  116428. };
  116429. /** Generate the current state of the procedural texture */
  116430. NoiseProceduralTexture.prototype.render = function (useCameraPostProcess) {
  116431. this._updateShaderUniforms();
  116432. _super.prototype.render.call(this, useCameraPostProcess);
  116433. };
  116434. /**
  116435. * Serializes this noise procedural texture
  116436. * @returns a serialized noise procedural texture object
  116437. */
  116438. NoiseProceduralTexture.prototype.serialize = function () {
  116439. var serializationObject = {};
  116440. serializationObject.customType = "BABYLON.NoiseProceduralTexture";
  116441. serializationObject.brightness = this.brightness;
  116442. serializationObject.octaves = this.octaves;
  116443. serializationObject.persistence = this.persistence;
  116444. serializationObject.animationSpeedFactor = this.animationSpeedFactor;
  116445. serializationObject.size = this.getSize().width;
  116446. serializationObject.generateMipMaps = this._generateMipMaps;
  116447. return serializationObject;
  116448. };
  116449. /**
  116450. * Creates a NoiseProceduralTexture from parsed noise procedural texture data
  116451. * @param parsedTexture defines parsed texture data
  116452. * @param scene defines the current scene
  116453. * @param rootUrl defines the root URL containing noise procedural texture information
  116454. * @returns a parsed NoiseProceduralTexture
  116455. */
  116456. NoiseProceduralTexture.Parse = function (parsedTexture, scene, rootUrl) {
  116457. var texture = new NoiseProceduralTexture(parsedTexture.name, parsedTexture.size, scene, undefined, parsedTexture.generateMipMaps);
  116458. texture.brightness = parsedTexture.brightness;
  116459. texture.octaves = parsedTexture.octaves;
  116460. texture.persistence = parsedTexture.persistence;
  116461. texture.animationSpeedFactor = parsedTexture.animationSpeedFactor;
  116462. return texture;
  116463. };
  116464. return NoiseProceduralTexture;
  116465. }(BABYLON.ProceduralTexture));
  116466. BABYLON.NoiseProceduralTexture = NoiseProceduralTexture;
  116467. })(BABYLON || (BABYLON = {}));
  116468. //# sourceMappingURL=babylon.noiseProceduralTexture.js.map
  116469. var __assign = (this && this.__assign) || function () {
  116470. __assign = Object.assign || function(t) {
  116471. for (var s, i = 1, n = arguments.length; i < n; i++) {
  116472. s = arguments[i];
  116473. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  116474. t[p] = s[p];
  116475. }
  116476. return t;
  116477. };
  116478. return __assign.apply(this, arguments);
  116479. };
  116480. var BABYLON;
  116481. (function (BABYLON) {
  116482. /**
  116483. * This can helps recording videos from BabylonJS.
  116484. * This is based on the available WebRTC functionalities of the browser.
  116485. *
  116486. * @see http://doc.babylonjs.com/how_to/render_scene_on_a_video
  116487. */
  116488. var VideoRecorder = /** @class */ (function () {
  116489. /**
  116490. * Create a new VideoCapture object which can help converting what you see in Babylon to
  116491. * a video file.
  116492. * @param engine Defines the BabylonJS Engine you wish to record
  116493. * @param options Defines options that can be used to customized the capture
  116494. */
  116495. function VideoRecorder(engine, options) {
  116496. if (options === void 0) { options = null; }
  116497. if (!VideoRecorder.IsSupported(engine)) {
  116498. throw "Your browser does not support recording so far.";
  116499. }
  116500. var canvas = engine.getRenderingCanvas();
  116501. if (!canvas) {
  116502. throw "The babylon engine must have a canvas to be recorded";
  116503. }
  116504. this._canvas = canvas;
  116505. this._canvas.isRecording = false;
  116506. this._options = __assign({}, VideoRecorder._defaultOptions, options);
  116507. var stream = this._canvas.captureStream(this._options.fps);
  116508. this._mediaRecorder = new MediaRecorder(stream, { mimeType: this._options.mimeType });
  116509. this._mediaRecorder.ondataavailable = this._handleDataAvailable.bind(this);
  116510. this._mediaRecorder.onerror = this._handleError.bind(this);
  116511. this._mediaRecorder.onstop = this._handleStop.bind(this);
  116512. }
  116513. /**
  116514. * Returns wehther or not the VideoRecorder is available in your browser.
  116515. * @param engine Defines the Babylon Engine to check the support for
  116516. * @returns true if supported otherwise false
  116517. */
  116518. VideoRecorder.IsSupported = function (engine) {
  116519. var canvas = engine.getRenderingCanvas();
  116520. return (!!canvas && typeof canvas.captureStream === "function");
  116521. };
  116522. Object.defineProperty(VideoRecorder.prototype, "isRecording", {
  116523. /**
  116524. * True wether a recording is already in progress.
  116525. */
  116526. get: function () {
  116527. return !!this._canvas && this._canvas.isRecording;
  116528. },
  116529. enumerable: true,
  116530. configurable: true
  116531. });
  116532. /**
  116533. * Stops the current recording before the default capture timeout passed in the startRecording
  116534. * functions.
  116535. */
  116536. VideoRecorder.prototype.stopRecording = function () {
  116537. if (!this._canvas || !this._mediaRecorder) {
  116538. return;
  116539. }
  116540. if (!this.isRecording) {
  116541. return;
  116542. }
  116543. this._canvas.isRecording = false;
  116544. this._mediaRecorder.stop();
  116545. };
  116546. /**
  116547. * Starts recording the canvas for a max duration specified in parameters.
  116548. * @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.
  116549. * @param maxDuration Defines the maximum recording time in seconds.
  116550. * It default to 7 seconds. A value of zero will not stop automatically, you would need to call stopRecording manually.
  116551. * @return a promise callback at the end of the recording with the video data in Blob.
  116552. */
  116553. VideoRecorder.prototype.startRecording = function (fileName, maxDuration) {
  116554. var _this = this;
  116555. if (fileName === void 0) { fileName = "babylonjs.webm"; }
  116556. if (maxDuration === void 0) { maxDuration = 7; }
  116557. if (!this._canvas || !this._mediaRecorder) {
  116558. throw "Recorder has already been disposed";
  116559. }
  116560. if (this.isRecording) {
  116561. throw "Recording already in progress";
  116562. }
  116563. if (maxDuration > 0) {
  116564. setTimeout(function () {
  116565. _this.stopRecording();
  116566. }, maxDuration * 1000);
  116567. }
  116568. this._fileName = fileName;
  116569. this._recordedChunks = [];
  116570. this._resolve = null;
  116571. this._reject = null;
  116572. this._canvas.isRecording = true;
  116573. this._mediaRecorder.start(this._options.recordChunckSize);
  116574. return new Promise(function (resolve, reject) {
  116575. _this._resolve = resolve;
  116576. _this._reject = reject;
  116577. });
  116578. };
  116579. /**
  116580. * Releases internal resources used during the recording.
  116581. */
  116582. VideoRecorder.prototype.dispose = function () {
  116583. this._canvas = null;
  116584. this._mediaRecorder = null;
  116585. this._recordedChunks = [];
  116586. this._fileName = null;
  116587. this._resolve = null;
  116588. this._reject = null;
  116589. };
  116590. VideoRecorder.prototype._handleDataAvailable = function (event) {
  116591. if (event.data.size > 0) {
  116592. this._recordedChunks.push(event.data);
  116593. }
  116594. };
  116595. VideoRecorder.prototype._handleError = function (event) {
  116596. this.stopRecording();
  116597. if (this._reject) {
  116598. this._reject(event.error);
  116599. }
  116600. else {
  116601. throw new event.error;
  116602. }
  116603. };
  116604. VideoRecorder.prototype._handleStop = function () {
  116605. this.stopRecording();
  116606. var superBuffer = new Blob(this._recordedChunks);
  116607. if (this._resolve) {
  116608. this._resolve(superBuffer);
  116609. }
  116610. window.URL.createObjectURL(superBuffer);
  116611. if (this._fileName) {
  116612. BABYLON.Tools.Download(superBuffer, this._fileName);
  116613. }
  116614. };
  116615. VideoRecorder._defaultOptions = {
  116616. mimeType: "video/webm",
  116617. fps: 25,
  116618. recordChunckSize: 3000
  116619. };
  116620. return VideoRecorder;
  116621. }());
  116622. BABYLON.VideoRecorder = VideoRecorder;
  116623. })(BABYLON || (BABYLON = {}));
  116624. //# sourceMappingURL=babylon.videoRecorder.js.map
  116625. var BABYLON;
  116626. (function (BABYLON) {
  116627. BABYLON.Scene.prototype.createDefaultLight = function (replace) {
  116628. if (replace === void 0) { replace = false; }
  116629. // Dispose existing light in replace mode.
  116630. if (replace) {
  116631. if (this.lights) {
  116632. for (var i = 0; i < this.lights.length; i++) {
  116633. this.lights[i].dispose();
  116634. }
  116635. }
  116636. }
  116637. // Light
  116638. if (this.lights.length === 0) {
  116639. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  116640. }
  116641. };
  116642. BABYLON.Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  116643. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116644. if (replace === void 0) { replace = false; }
  116645. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116646. // Dispose existing camera in replace mode.
  116647. if (replace) {
  116648. if (this.activeCamera) {
  116649. this.activeCamera.dispose();
  116650. this.activeCamera = null;
  116651. }
  116652. }
  116653. // Camera
  116654. if (!this.activeCamera) {
  116655. var worldExtends = this.getWorldExtends();
  116656. var worldSize = worldExtends.max.subtract(worldExtends.min);
  116657. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  116658. var camera;
  116659. var radius = worldSize.length() * 1.5;
  116660. // empty scene scenario!
  116661. if (!isFinite(radius)) {
  116662. radius = 1;
  116663. worldCenter.copyFromFloats(0, 0, 0);
  116664. }
  116665. if (createArcRotateCamera) {
  116666. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  116667. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  116668. arcRotateCamera.wheelPrecision = 100 / radius;
  116669. camera = arcRotateCamera;
  116670. }
  116671. else {
  116672. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  116673. freeCamera.setTarget(worldCenter);
  116674. camera = freeCamera;
  116675. }
  116676. camera.minZ = radius * 0.01;
  116677. camera.maxZ = radius * 1000;
  116678. camera.speed = radius * 0.2;
  116679. this.activeCamera = camera;
  116680. var canvas = this.getEngine().getRenderingCanvas();
  116681. if (attachCameraControls && canvas) {
  116682. camera.attachControl(canvas);
  116683. }
  116684. }
  116685. };
  116686. BABYLON.Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  116687. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  116688. if (replace === void 0) { replace = false; }
  116689. if (attachCameraControls === void 0) { attachCameraControls = false; }
  116690. this.createDefaultLight(replace);
  116691. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  116692. };
  116693. BABYLON.Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  116694. if (pbr === void 0) { pbr = false; }
  116695. if (scale === void 0) { scale = 1000; }
  116696. if (blur === void 0) { blur = 0; }
  116697. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  116698. if (!environmentTexture) {
  116699. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  116700. return null;
  116701. }
  116702. if (setGlobalEnvTexture) {
  116703. if (environmentTexture) {
  116704. this.environmentTexture = environmentTexture;
  116705. }
  116706. }
  116707. // Skybox
  116708. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  116709. if (pbr) {
  116710. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  116711. hdrSkyboxMaterial.backFaceCulling = false;
  116712. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  116713. if (hdrSkyboxMaterial.reflectionTexture) {
  116714. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116715. }
  116716. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  116717. hdrSkyboxMaterial.disableLighting = true;
  116718. hdrSkyboxMaterial.twoSidedLighting = true;
  116719. hdrSkybox.infiniteDistance = true;
  116720. hdrSkybox.material = hdrSkyboxMaterial;
  116721. }
  116722. else {
  116723. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  116724. skyboxMaterial.backFaceCulling = false;
  116725. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  116726. if (skyboxMaterial.reflectionTexture) {
  116727. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  116728. }
  116729. skyboxMaterial.disableLighting = true;
  116730. hdrSkybox.infiniteDistance = true;
  116731. hdrSkybox.material = skyboxMaterial;
  116732. }
  116733. return hdrSkybox;
  116734. };
  116735. BABYLON.Scene.prototype.createDefaultEnvironment = function (options) {
  116736. if (BABYLON.EnvironmentHelper) {
  116737. return new BABYLON.EnvironmentHelper(options, this);
  116738. }
  116739. return null;
  116740. };
  116741. BABYLON.Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  116742. if (webVROptions === void 0) { webVROptions = {}; }
  116743. return new BABYLON.VRExperienceHelper(this, webVROptions);
  116744. };
  116745. })(BABYLON || (BABYLON = {}));
  116746. //# sourceMappingURL=babylon.sceneHelpers.js.map
  116747. 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"};
  116748. 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};"};
  116749. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  116750. globalObject["BABYLON"] = BABYLON;
  116751. //backwards compatibility
  116752. if(typeof earcut !== 'undefined') {
  116753. globalObject["Earcut"] = {
  116754. earcut: earcut
  116755. };
  116756. }
  116757. return BABYLON;
  116758. });